Github user sethah commented on a diff in the pull request:
https://github.com/apache/spark/pull/17117#discussion_r104090529
--- Diff: mllib/src/main/scala/org/apache/spark/ml/clustering/KMeans.scala
---
@@ -337,15 +366,61 @@ class KMeans @Since("1.5.0") (
@Since("1.5.0")
override def transformSchema(schema: StructType): StructType = {
+ if ($(initMode) == MLlibKMeans.K_MEANS_INITIAL_MODEL) {
+ if (isSet(initialModel)) {
+ val initialModelK = $(initialModel).parentModel.k
+ if (initialModelK != $(k)) {
+ throw new IllegalArgumentException("The initial model's cluster
count = " +
+ s"$initialModelK, mismatched with k = $k.")
+ }
+ } else {
+ throw new IllegalArgumentException("Users must set param
initialModel if you choose " +
+ "'initialModel' as the initialization algorithm.")
+ }
+ } else {
+ if (isSet(initialModel)) {
+ logWarning(s"Param initialModel will take no effect when initMode
is $initMode.")
+ }
+ }
validateAndTransformSchema(schema)
}
+
+ @Since("2.2.0")
+ override def write: MLWriter = new KMeans.KMeansWriter(this)
}
@Since("1.6.0")
-object KMeans extends DefaultParamsReadable[KMeans] {
+object KMeans extends MLReadable[KMeans] {
@Since("1.6.0")
override def load(path: String): KMeans = super.load(path)
+
+ @Since("2.2.0")
+ override def read: MLReader[KMeans] = new KMeansReader
+
+ /** [[MLWriter]] instance for [[KMeans]] */
+ private[KMeans] class KMeansWriter(instance: KMeans) extends MLWriter {
+
+ override protected def saveImpl(path: String): Unit = {
+ DefaultParamsWriter.saveInitialModel(instance, path)
+ DefaultParamsWriter.saveMetadata(instance, path, sc)
+ }
+ }
+
+ private class KMeansReader extends MLReader[KMeans] {
+
+ override def load(path: String): KMeans = {
+ val metadata = DefaultParamsReader.loadMetadata(path, sc,
classOf[KMeans].getName)
+ val instance = new KMeans(metadata.uid)
+
+ DefaultParamsReader.getAndSetParams(instance, metadata)
+ DefaultParamsReader.loadInitialModel[KMeansModel](path, sc) match {
--- End diff --
This can be done as:
````scala
DefaultParamsReader.loadInitialModel[KMeansModel](path,
sc).foreach(instance.setInitialModel)
````
I think it's nicer, but I'm not sure if there is a universal preference for
side effects with options in Spark, so I'll leave it to you to decide.
---
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]