gpt4 book ai didi

scala - 如何计算 Apache Spark 中 RowMatrix 的倒数?

转载 作者:行者123 更新时间:2023-12-04 10:49:43 36 4
gpt4 key购买 nike

我有一个 X 分布式矩阵,采用 RowMatrix 形式。我正在使用 Spark 1.3.0。我需要能够计算X逆。

最佳答案

import org.apache.spark.mllib.linalg.{Vectors,Vector,Matrix,SingularValueDecomposition,DenseMatrix,DenseVector}
import org.apache.spark.mllib.linalg.distributed.RowMatrix

def computeInverse(X: RowMatrix): DenseMatrix = {
val nCoef = X.numCols.toInt
val svd = X.computeSVD(nCoef, computeU = true)
if (svd.s.size < nCoef) {
sys.error(s"RowMatrix.computeInverse called on singular matrix.")
}

// Create the inv diagonal matrix from S
val invS = DenseMatrix.diag(new DenseVector(svd.s.toArray.map(x => math.pow(x,-1))))

// U cannot be a RowMatrix
val U = new DenseMatrix(svd.U.numRows().toInt,svd.U.numCols().toInt,svd.U.rows.collect.flatMap(x => x.toArray))

// If you could make V distributed, then this may be better. However its alreadly local...so maybe this is fine.
val V = svd.V
// inv(X) = V*inv(S)*transpose(U) --- the U is already transposed.
(V.multiply(invS)).multiply(U)
}

关于scala - 如何计算 Apache Spark 中 RowMatrix 的倒数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29969521/

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