本文介绍了如何在 Spark MLlib 中为 K-means 初始化聚类中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Spark MLlib 中运行 K-Means 时初始化聚类中心?

Is there a way to initialize cluster centers while running K-Means in Spark MLlib?

我尝试了以下操作:

model = KMeans.train(
    sc.parallelize(data), 3, maxIterations=0,
    initialModel = KMeansModel([(-1000.0,-1000.0),(5.0,5.0),(1000.0,1000.0)]))

initialModelsetInitialModel 在 spark-mllib_2.10 中不存在

initialModel and setInitialModel are not present in spark-mllib_2.10

推荐答案

从 Spark 1.5+ 开始,初始模型可以在 Scala 中使用 setInitialModel 设置,它采用 KMeansModel:

Initial model can set in Scala since Spark 1.5+ using setInitialModel which takes KMeansModel:

import org.apache.spark.mllib.clustering.{KMeans, KMeansModel}
import org.apache.spark.mllib.linalg.Vectors

val data = sc.parallelize(Seq(
    "[0.0, 0.0]", "[1.0, 1.0]", "[9.0, 8.0]", "[8.0,  9.0]"
)).map(Vectors.parse(_))

val initialModel = new KMeansModel(
   Array("[0.6,  0.6]", "[8.0,  8.0]").map(Vectors.parse(_))
)

val model = new KMeans()
  .setInitialModel(initialModel)
  .setK(2)
  .run(data)

和 PySpark 1.6+ 使用 initialModel 参数到 train 方法:

and PySpark 1.6+ using initialModel parameter to train method:

from pyspark.mllib.clustering import KMeansModel, KMeans
from pyspark.mllib.linalg import Vectors

data = sc.parallelize([
    "[0.0, 0.0]", "[1.0, 1.0]", "[9.0, 8.0]", "[8.0,  9.0]"
]).map(Vectors.parse)

initialModel = KMeansModel([
    Vectors.parse(v) for v in ["[0.6,  0.6]", "[8.0,  8.0]"]])
model = KMeans.train(data, 2, initialModel=initialModel)

如果这些方法中的任何一个不起作用,则意味着您使用的是早期版本的 Spark.

If any of these methods doesn't work it means that you're using an earlier version of Spark.

这篇关于如何在 Spark MLlib 中为 K-means 初始化聚类中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 16:26