如何用Spark重构svd组件的原始矩阵

时间:2016-11-26 17:19:25

标签: scala apache-spark svd

我想重建(近似)在SVD中分解的原始矩阵。有没有办法在不必将V factor本地Matrix转换为DenseMatrix的情况下执行此操作?

以下是基于documentation的分解(请注意,评论来自doc示例)

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 :(得分: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)