I need to write a for-loop with object mutation in Scala. In machine learning, when clustering (distributing samples into optimally separate groups), in order to decide on optimal number of groups in a set, clustering algorithm is run with different group numbers, some error metric is calculated for each group number. Optimal group number is where graph of number of groups make an elbow against error metric.
In Spark ML library, a KMeans object is used to cluster where group number is passed as a parameter. So, I calculate error metric to draw elbow graph as follows:
var baseClusterer = new KMeans()
.setFeaturesCol("scaledFeatures")
.setPredictionCol("clusters")
.setSeed(0)
2 to 10 map {
baseClusterer = baseClusterer.setK(k)
baseClusterer.fit(scaledDF).computeCost(scaledDF)
}
I have to declare clusterer object as a var and mutate it every iteration. Is there a more scala way to write this?