简体   繁体   中英

Join per line two different RDDs in just one - Scala

I'm programming a K-means algorithm in Spark-Scala. 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

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.

But my best effort has got just this: (you can check the first numbers are wrong: 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:

val result = parsedData.map { v =>
  val cluster = clusters.predict(v)
  s"$cluster ${v(0)} ${v(1)}"
}
result.saveAsTextFile("/some/output/path")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM