使用 Scala 将 Array[DenseVector] 转换为 CSV
Convert Array[DenseVector] to CSV with Scala
我在 Scala 中使用 Kmeans Spark 函数,我需要将获得的聚类中心保存到 CSV 文件中。此 val 类型为:Array[DenseVector]
.
val clusters = KMeans.train(parsedData, numClusters, numIterations)
val centers = clusters.clusterCenters
我试图将 centers
转换为 RDD 文件,然后从 RDD 转换为 DF,但我遇到了很多问题(例如,导入 spark.implicits._ / SQLContext.implicits._ 不起作用而且我不能使用 .toDF
)。我想知道是否有另一种方法可以使 CSV 更容易。
有什么建议吗?
在不使用外部库的情况下,您可以通过简单地写入文件 Java 方式来做到这一点。
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()
结果文件
0.1,0.1,0.1
9.1,9.1,9.1
需要 drop
和 dropRight
来移除转换矢量周围的 []
。
代码和数据取自官方example.
我在 Scala 中使用 Kmeans Spark 函数,我需要将获得的聚类中心保存到 CSV 文件中。此 val 类型为:Array[DenseVector]
.
val clusters = KMeans.train(parsedData, numClusters, numIterations)
val centers = clusters.clusterCenters
我试图将 centers
转换为 RDD 文件,然后从 RDD 转换为 DF,但我遇到了很多问题(例如,导入 spark.implicits._ / SQLContext.implicits._ 不起作用而且我不能使用 .toDF
)。我想知道是否有另一种方法可以使 CSV 更容易。
有什么建议吗?
在不使用外部库的情况下,您可以通过简单地写入文件 Java 方式来做到这一点。
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()
结果文件
0.1,0.1,0.1
9.1,9.1,9.1
需要 drop
和 dropRight
来移除转换矢量周围的 []
。
代码和数据取自官方example.