Convert Array[DenseVector] to CSV with Scala

╄→尐↘猪︶ㄣ 提交于 2019-12-24 21:06:21

问题


I am using Kmeans Spark function with Scala and I need to save the Cluster Centers obtained into a CSV. This val is type: Array[DenseVector].

val clusters = KMeans.train(parsedData, numClusters, numIterations)
val centers = clusters.clusterCenters

I was trying converting centers to a RDD file and then from RDD to DF, but I get a lot of problems (e.g, import spark.implicits._ / SQLContext.implicits._ is not working and I cannot use .toDF). I was wondering if there is another way to make a CSV easier.

Any suggestion?


回答1:


Without use of external libraries you can do that by simply writing to the file Java way.

import java.io.{ PrintWriter, File, FileOutputStream }

...

val pw = new PrintWriter(
    new File( "KMeans_centers.csv" )
)

centers
.foreach( vec =>
        pw.write( vec.toString.drop( 1 ).dropRight( 1 ) + "\n" )
    )

pw.close()

Resulting file

0.1,0.1,0.1
9.1,9.1,9.1

drop and dropRight are needed to remove [] around the converted vector.

Code and data are taken from the official example.



来源:https://stackoverflow.com/questions/48086945/convert-arraydensevector-to-csv-with-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!