Spark mllib k-means 聚合

网友投稿 631 2022-11-09

Spark mllib k-means 聚合

Spark mllib k-means 聚合

K-Means算法是一种基于距离的聚类算法,采用迭代的方法,计算出K个聚类中心,把若干个点聚成K类。

package com.immooc.spark import org.apache.log4j.{Level, Logger} import org.apache.spark.mllib.clustering.KMeans import org.apache.spark.mllib.linalg.Vectors import org.apache.spark.{SparkConf, SparkContext} object KMeansTest { def main(args:Array[String]): Unit = { val conf = new SparkConf().setAppName("KMeansTest").setMaster("local[2]") val sc = new SparkContext(conf) Logger.getRootLogger.setLevel(Level.WARN) // 读取样本数据1,格式为LIBSVM format val data = sc.textFile("file:///Users/walle/Documents/D3/sparkmlib/kmeans_data.txt") val parsedData = data.map(s => Vectors.dense(s.split(' ').map(_.toDouble))).cache() // 新建KMeans聚类模型,并训练 val initMode = "k-means||" val numClusters = 4 val numIterations = 100 val model = new KMeans(). setInitializationMode(initMode). setK(numClusters). setMaxIterations(numIterations). run(parsedData) val centers = model.clusterCenters println("centers") for (i <- 0 to centers.length - 1) { println(centers(i)(0) + "\t" + centers(i)(1)) } // 误差计算 val WSSSE = model.computeCost(parsedData) println("Within Set Sum of Squared Errors = " + WSSSE) } }

1. 输出

centers 9.05 9.05 0.05 0.05 9.2 9.2 0.2 0.2 Within Set Sum of Squared Errors = 0.03000000000004321

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:cocos2d 3.0 屏幕适配
下一篇:springboot配置mysql数据库spring.datasource.url报错的解决
相关文章

 发表评论

暂时没有评论,来抢沙发吧~