gpt4 book ai didi

apache-spark - Spark 中 RowMatrix 的矩阵转置

转载 作者:行者123 更新时间:2023-12-03 07:23:43 25 4
gpt4 key购买 nike

假设我有一个 RowMatrix。

  1. 我该如何转置它。 API文档好像没有转置方法。
  2. Matrix 有 transpose() 方法。但它不是分布式的。如果我有一个大于内存的大矩阵,我该如何转置它?
  3. 我已将 RowMatrix 转换为 DenseMatrix,如下所示

    DenseMatrix Mat = new DenseMatrix(m,n,MatArr);

    这需要将 RowMatrix 转换为 JavaRDD 并将 JavaRDD 转换为数组。

还有其他方便的方法来进行转换吗?

提前致谢

最佳答案

如果有人感兴趣,我已经实现了 @javadba 提议的分布式版本。

  def transposeRowMatrix(m: RowMatrix): RowMatrix = {
val transposedRowsRDD = m.rows.zipWithIndex.map{case (row, rowIndex) => rowToTransposedTriplet(row, rowIndex)}
.flatMap(x => x) // now we have triplets (newRowIndex, (newColIndex, value))
.groupByKey
.sortByKey().map(_._2) // sort rows and remove row indexes
.map(buildRow) // restore order of elements in each row and remove column indexes
new RowMatrix(transposedRowsRDD)
}


def rowToTransposedTriplet(row: Vector, rowIndex: Long): Array[(Long, (Long, Double))] = {
val indexedRow = row.toArray.zipWithIndex
indexedRow.map{case (value, colIndex) => (colIndex.toLong, (rowIndex, value))}
}

def buildRow(rowWithIndexes: Iterable[(Long, Double)]): Vector = {
val resArr = new Array[Double](rowWithIndexes.size)
rowWithIndexes.foreach{case (index, value) =>
resArr(index.toInt) = value
}
Vectors.dense(resArr)
}

关于apache-spark - Spark 中 RowMatrix 的矩阵转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30556478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com