如何使用Spark从SVD分量重构原矩阵

3
我希望重构SVD分解后的原始矩阵(近似值)。有没有一种方法可以在不将V因子本地矩阵转换为DenseMatrix的情况下完成这个过程?这是基于documentation的分解(请注意,注释来自文档示例)。
import org.apache.spark.mllib.linalg.Matrix
import org.apache.spark.mllib.linalg.SingularValueDecomposition
import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.mllib.linalg.distributed.RowMatrix

val data = Array(
  Vectors.dense(1.0, 0.0, 7.0, 0.0, 0.0),
  Vectors.dense(2.0, 0.0, 3.0, 4.0, 5.0),
  Vectors.dense(4.0, 0.0, 0.0, 6.0, 7.0))

val dataRDD = sc.parallelize(data, 2)

val mat: RowMatrix = new RowMatrix(dataRDD)

// Compute the top 5 singular values and corresponding singular vectors.
val svd: SingularValueDecomposition[RowMatrix, Matrix] = mat.computeSVD(5, computeU = true)
val U: RowMatrix = svd.U  // The U factor is a RowMatrix.
val s: Vector = svd.s  // The singular values are stored in a local dense vector.
val V: Matrix = svd.V  // The V factor is a local dense matrix.

为了重建原始矩阵,我需要计算 U * 对角线(s) * 转置(V)。
首先要将奇异值向量 s 转换成对角矩阵 S。
import org.apache.spark.mllib.linalg.Matrices
val S = Matrices.diag(s)

但是当我尝试计算 U * 对角线(s) * 转置(V) 时,出现了以下错误。
val dataApprox = U.multiply(S.multiply(V.transpose))

我遇到了以下错误:

错误:类型不匹配; 找到:org.apache.spark.mllib.linalg.Matrix 需要:org.apache.spark.mllib.linalg.DenseMatrix

如果我将Matrix V转换为DenseMatrix Vdense,它就可以正常工作。
import org.apache.spark.mllib.linalg.DenseMatrix
val Vdense = new DenseMatrix(V.numRows, V.numCols,  V.toArray)
val dataApprox = U.multiply(S.multiply(Vdense.transpose))

有没有一种方法可以在不进行转换的情况下,从svd的输出中获取原始矩阵dataApprox的近似值?
1个回答

0

以下代码对我有效:

//numTopSingularValues=Features used for SVD
val latentFeatureArray=s.toArray

//Making a ListBuffer to Make a DenseMatrix for s
var denseMatListBuffer=ListBuffer.empty[Double]
val zeroListBuffer=ListBuffer.empty[Double]
var addZeroIndex=0
while (addZeroIndex < numTopSingularValues )
  {
    zeroListBuffer+=0.0D
    addZeroIndex+=1
  }
var addDiagElemIndex=0
while(addDiagElemIndex<(numTopSingularValues-1))
  {
    denseMatListBuffer+=latentFeatureArray(addDiagElemIndex)
    denseMatListBuffer.appendAll(zeroListBuffer)
    addDiagElemIndex+=1
  }
denseMatListBuffer+=latentFeatureArray(numTopSingularValues-1)

val sDenseMatrix=new DenseMatrix(numTopSingularValues,numTopSingularValues,denseMatListBuffer.toArray)

val vMultiplyS=V.multiply(sDenseMatrix)

val postMulWithUDenseMat=vMultiplyS.transpose

val dataApprox=U.multiply(postMulWithUDenseMat)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接