Machine Learning with Spark (4/5) - unsupervised learning


Machine Learning with Spark

Unsupervised learning


  • spark 2.0.0 or higher, preferable with pre-built hadoop. Download link
  • scala 2.11.8 or higher. Download link

This will be a brief introduction to Spark and KMeans Clustering. KMeans it's a very popular method utilized in data mining which in short it aims at partitioning the observations (data points) into k number of clusters, each belonging to the cluster with the nearest mean. This link explains how KMeans Clustering works.

To work with KMeans in Spark, we will need to import the following libraries.

import{KMeans => KM}
import{VectorAssembler => VA}

Assuming that our data set is loaded into a dataframe called df, next we will create a features vector using the VectorAssembler and prepare the data. Since this is unsupervised learning, we have no label column, only features.

val assembler = new VA().setInputCols(df.columns).setOutputCol("features")
val data = assembler.transform(df).select("features")

Next, we need to instantiate KM and we chose the number of clusters, in this case three. Setting the seed is optional and it's being used only for reproducibility purposes.

val kmeans = new KM().setK(3).setSeed(196L)

There is no right or wrong number of deciding how many clusters your data set should be divided into. However, there are a couple of methods which will help in deciding an appropriate number. One of the most used is the Elbow method.

Next we will fit the data and then we will evaluate the clustering by calculating the sum of squared errors.

val model =

val sse = model.computeCost(data)
println(s"Within Set Sum of Squared Errors ${sse}")

To check the cluster's parameters and its values, you could run model.extractParamMap. Other metrics are available at model.summary.

To printout the centers of the cluster: model.clusterCenters.foreach(println).

And in the end some useful links:

[+] Useful links
  • [Download Spark](
  • [Machine Learning Guide](
  • [15 hours of machine learning videos](
  • [Part 1/5 Machine Learning with Spark](
  • [Part 2/5 Machine Learning with Spark](
  • [Part 3/5 Machine Learning with Spark](
  • [Clustering with Spark](

  • > ==Disclaimer==: This is by no means an original work it is merely meant to serve as a compilation of thoughts, code snippets and teachings from different sources.