Github user sethah commented on a diff in the pull request:
https://github.com/apache/spark/pull/11119#discussion_r77013070
--- Diff:
mllib/src/test/scala/org/apache/spark/ml/clustering/KMeansSuite.scala ---
@@ -139,16 +145,32 @@ class KMeansSuite extends SparkFunSuite with
MLlibTestSparkContext with DefaultR
val kmeans = new KMeans()
testEstimatorAndModelReadWrite(kmeans, dataset,
KMeansSuite.allParamSettings, checkModelData)
}
+
+ test("Initialize using given cluster centers") {
+ val kmeans = new KMeans().setK(k).setSeed(1).setMaxIter(1)
+ val oneIterModel = kmeans.fit(dataset)
+ val twoIterModel = kmeans.copy(ParamMap(ParamPair(kmeans.maxIter,
2))).fit(dataset)
+ val oneMoreIterModel =
kmeans.setInitialModel(oneIterModel).fit(dataset)
+
+ twoIterModel.clusterCenters.zip(oneMoreIterModel.clusterCenters)
+ .foreach { case (center1, center2) => assert(center1 ~== center2
absTol 1E-8) }
+ }
}
object KMeansSuite {
def generateKMeansData(spark: SparkSession, rows: Int, dim: Int, k:
Int): DataFrame = {
val sc = spark.sparkContext
val rdd = sc.parallelize(1 to rows).map(i =>
Vectors.dense(Array.fill(dim)((i % k).toDouble)))
- .map(v => new TestRow(v))
+ .map(v => TestRow(v))
spark.createDataFrame(rdd)
}
+ def generateKMeansModel(dim: Int, k: Int, seed: Int = 42): KMeansModel =
{
+ val clusterCenters = (1 to k)
+ .map(i => MLlibVectors.dense(Array.fill(dim)(new
Random(seed).nextDouble)))
--- End diff --
Not sure it matters, but you're creating a new random generator every
single time with the same seed, so basically every number is the same. It
should probably be
````scala
val rng = new Random(seed)
val clusterCenters = (1 to k)
.map(i => MLlibVectors.dense(Array.fill(dim)(rng.nextDouble)))
````
Then again, I'm not sure we need this method at all, since it's only used
in one place.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]