[英]Join per line two different RDDs in just one - Scala
I'm programming a K-means algorithm in Spark-Scala. 我正在Spark-Scala中编写K-means算法。 My model predicts in which cluster is each point. 我的模型预测每个点在哪个群集中。
Data 数据
-6.59 -44.68
-35.73 39.93
47.54 -52.04
23.78 46.82
....
Load the data 加载数据
val data = sc.textFile("/home/borja/flink/kmeans/points")
val parsedData = data.map(s => Vectors.dense(s.split(' ').map(_.toDouble))).cache()
Cluster the data into two classes using KMeans 使用KMeans将数据分为两类
val numClusters = 10
val numIterations = 100
val clusters = KMeans.train(parsedData, numClusters, numIterations)
Predict 预测
val prediction = clusters.predict(parsedData)
However, I need to put the result and the points in the same file, in the next format: 但是,我需要将结果和点以以下格式放入同一文件中:
[no title, numberOfCluster (1,2,3,..10), pointX, pointY]:
6 -6.59 -44.68
8 -35.73 39.93
10 47.54 -52.04
7 23.78 46.82
This is the entry of this executable in Python to print really nice the result. 这是Python中此可执行文件的条目,以打印出非常好的结果。
But my best effort has got just this: (you can check the first numbers are wrong: 68, 384, ...) 但我最大的努力就是这样:(您可以检查第一个数字是否正确:68、384,...)
var i = 0
val c = sc.parallelize(data.collect().map(x => {
val tuple = (i, x)
i += 1
tuple
}))
i = 0
val c2 = sc.parallelize(prediction.collect().map(x => {
val tuple = (i, x)
i += 1
tuple
}))
val result = c.join(c2)
result.take(5)
Result: 结果:
res94: Array[(Int, (String, Int))] = Array((68,(17.79 13.69,0)), (384,(-33.47 -4.87,8)), (440,(-4.75 -42.21,1)), (4,(-33.31 -13.11,6)), (324,(-39.04 -16.68,6)))
Thanks for your help! 谢谢你的帮助! :) :)
I don't have a spark cluster handy to test, but something like this should work: 我没有一个易于测试的Spark集群,但是这样的事情应该可以工作:
val result = parsedData.map { v =>
val cluster = clusters.predict(v)
s"$cluster ${v(0)} ${v(1)}"
}
result.saveAsTextFile("/some/output/path")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.