【问题标题】:Convert RDD of Matrix to RDD of Vector将Matrix的RDD转换为Vector的RDD
【发布时间】:2021-11-30 20:47:20
【问题描述】:

我有一个 RDD[Matrix[Double]] 并想将其转换为 RDD[Vector](矩阵中的每一行都将转换为一个向量)。

我见过像Convert Matrix to RowMatrix in Apache Spark using Scala 这样的相关答案,但它是向量 RDD 的一个矩阵。而我的案例是Matrix的RDD。

【问题讨论】:

    标签: scala apache-spark apache-spark-mllib


    【解决方案1】:

    code to convert MatrixSeq[Vector] 上使用flatMap:

    // from https://stackoverflow.com/a/28172826/1206998
    def toSeqOfVector(m: Matrix): Seq[Vector] = {
      val columns = m.toArray.grouped(m.numRows)
      val rows = columns.toSeq.transpose // Skip this if you want a column-major RDD.
      rows.map(row => new DenseVector(row.toArray))
    }
    
    val matrices: RDD[Matrix] = ??? // your input
    val vectors:  RDD[Vector] = matrices.flatMap(toSeqOfVector)
    

    注意:这段代码我没有测试,但原理是这样的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 2016-01-07
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      相关资源
      最近更新 更多