Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Spark org.apache.spark.mllib.linalg.Matrix to a file

The result of correlation in Spark MLLib is a of type org.apache.spark.mllib.linalg.Matrix. (see http://spark.apache.org/docs/1.2.1/mllib-statistics.html#correlations)

val data: RDD[Vector] = ... 

val correlMatrix: Matrix = Statistics.corr(data, "pearson")

I would like to save the result into a file. How can I do this?

like image 571
florins Avatar asked Apr 15 '15 12:04

florins


1 Answers

Here is a simple and effective approach to save the Matrix to hdfs and specify the separator.

(The transpose is used since .toArray is in column major format.)

val localMatrix: List[Array[Double]] = correlMatrix
    .transpose  // Transpose since .toArray is column major
    .toArray
    .grouped(correlMatrix.numCols)
    .toList

val lines: List[String] = localMatrix
    .map(line => line.mkString(" "))

sc.parallelize(lines)
    .repartition(1)
    .saveAsTextFile("hdfs:///home/user/spark/correlMatrix.txt")
like image 123
Dylan Hogg Avatar answered Sep 30 '22 08:09

Dylan Hogg