Github user rezazadeh commented on a diff in the pull request:

    https://github.com/apache/spark/pull/296#discussion_r11408048
  
    --- Diff: 
mllib/src/main/scala/org/apache/spark/mllib/linalg/distributed/RowMatrix.scala 
---
    @@ -0,0 +1,340 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.spark.mllib.linalg.distributed
    +
    +import java.util
    +
    +import breeze.linalg.{DenseMatrix => BDM, DenseVector => BDV, svd => 
brzSvd}
    +import breeze.numerics.{sqrt => brzSqrt}
    +import com.github.fommil.netlib.BLAS.{getInstance => blas}
    +
    +import org.apache.spark.mllib.linalg._
    +import org.apache.spark.rdd.RDD
    +import org.apache.spark.Logging
    +
    +/**
    + * Represents a row-oriented distributed Matrix with no meaningful row 
indices.
    + *
    + * @param rows rows stored as an RDD[Vector]
    + * @param nRows number of rows. A non-positive value means unknown, and 
then the number of rows will
    + *              be determined by the number of records in the RDD `rows`.
    + * @param nCols number of columns. A non-positive value means unknown, and 
then the number of
    + *              columns will be determined by the size of the first row.
    + */
    +class RowMatrix(
    +    val rows: RDD[Vector],
    +    private var nRows: Long,
    +    private var nCols: Int) extends DistributedMatrix with Logging {
    +
    +  /** Alternative constructor leaving matrix dimensions to be determined 
automatically. */
    +  def this(rows: RDD[Vector]) = this(rows, 0L, 0)
    +
    +  /** Gets or computes the number of columns. */
    +  override def numCols(): Long = {
    +    if (nCols <= 0) {
    +      // Calling `first` will throw an exception if `rows` is empty.
    +      nCols = rows.first().size
    +    }
    +    nCols
    +  }
    +
    +  /** Gets or computes the number of rows. */
    +  override def numRows(): Long = {
    +    if (nRows <= 0L) {
    +      nRows = rows.count()
    +      if (nRows == 0L) {
    +        sys.error("Cannot determine the number of rows because it is not 
specified in the " +
    +          "constructor and the rows RDD is empty.")
    +      }
    +    }
    +    nRows
    +  }
    +
    +  /**
    +   * Computes the Gramian matrix `A^T A`.
    +   */
    +  def computeGramianMatrix(): Matrix = {
    +    val n = numCols().toInt
    +    val nt: Int = n * (n + 1) / 2
    +
    +    // Compute the upper triangular part of the gram matrix.
    +    val GU = rows.aggregate(new BDV[Double](new Array[Double](nt)))(
    +      seqOp = (U, v) => {
    +        RowMatrix.dspr(1.0, v, U.data)
    +        U
    +      },
    +      combOp = (U1, U2) => U1 += U2
    +    )
    +
    +    RowMatrix.triuToFull(n, GU.data)
    +  }
    +
    +  /**
    +   * Computes the singular value decomposition of this matrix.
    +   * Denote this matrix by A (m x n), this will compute matrices U, S, V 
such that A = U * S * V'.
    +   *
    +   * There is no restriction on m, but we require `n^2` doubles to fit in 
memory.
    +   * Further, n should be less than m.
    +
    +   * The decomposition is computed by first computing A'A = V S^2 V',
    +   * computing svd locally on that (since n x n is small), from which we 
recover S and V.
    +   * Then we compute U via easy matrix multiplication as U =  A * (V * 
S^-1).
    +   * Note that this approach requires `O(n^3)` time on the master node.
    +   *
    +   * At most k largest non-zero singular values and associated vectors are 
returned.
    +   * If there are k such values, then the dimensions of the return will be:
    +   *
    +   * U is a RowMatrix of size m x k that satisfies U'U = eye(k),
    +   * s is a Vector of size k, holding the singular values in descending 
order,
    +   * and V is a Matrix of size n x k that satisfies V'V = eye(k).
    +   *
    +   * @param k number of singular values to keep. We might return less than 
k if there are
    +   *          numerically zero singular values. See rCond.
    +   * @param computeU whether to compute U
    +   * @param rCond the reciprocal condition number. All singular values 
smaller than rCond * sigma(0)
    +   *              are treated as zero, where sigma(0) is the largest 
singular value.
    +   * @return SingularValueDecomposition(U, s, V)
    +   */
    +  def computeSVD(
    +      k: Int,
    +      computeU: Boolean = false,
    +      rCond: Double = 1e-9): SingularValueDecomposition[RowMatrix, Matrix] 
= {
    +    val n = numCols().toInt
    +    require(k > 0 && k <= n, s"Request up to n singular values k=$k n=$n.")
    +
    +    val G = computeGramianMatrix()
    +
    +    // TODO: Use sparse SVD instead.
    +    val (u: BDM[Double], sigmaSquares: BDV[Double], v: BDM[Double]) =
    +      brzSvd(G.toBreeze.asInstanceOf[BDM[Double]])
    +    val sigmas: BDV[Double] = brzSqrt(sigmaSquares)
    +
    +    // Determine effective rank.
    +    val sigma0 = sigmas(0)
    +    val threshold = rCond * sigma0
    +    var i = 0
    +    while (i < k && sigmas(i) >= threshold) {
    +      i += 1
    +    }
    +    val sk = i
    +
    +    val s = Vectors.dense(util.Arrays.copyOfRange(sigmas.data, 0, sk))
    +    val V = Matrices.dense(n, sk, util.Arrays.copyOfRange(u.data, 0, n * 
sk))
    +
    +    if (computeU) {
    +      // N = Vk * Sk^{-1}
    +      val N = new BDM[Double](n, sk, util.Arrays.copyOfRange(u.data, 0, n 
* sk))
    +      var i = 0
    +      var j = 0
    +      while (j < sk) {
    +        i = 0
    +        val sigma = sigmas(j)
    +        while (i < n) {
    +          N(i, j) /= sigma
    +          i += 1
    +        }
    +        j += 1
    +      }
    +      val U = this.multiply(Matrices.fromBreeze(N))
    +      SingularValueDecomposition(U, s, V)
    +    } else {
    +      SingularValueDecomposition(null, s, V)
    +    }
    +  }
    +
    +  /**
    +   * Computes the covariance matrix, treating each row as an observation.
    +   * @return a local dense matrix of size n x n
    +   */
    +  def computeCovariance(): Matrix = {
    +    val n = numCols().toInt
    +
    +    if (n > 10000) {
    +      val mem = n * n * java.lang.Double.SIZE / java.lang.Byte.SIZE
    +      logWarning(s"The number of columns $n is greater than 10000! " +
    +        s"We need at least $mem bytes of memory.")
    +    }
    +
    +    val (m, mean) = rows.aggregate[(Long, BDV[Double])]((0L, 
BDV.zeros[Double](n)))(
    +      seqOp = (s: (Long, BDV[Double]), v: Vector) => (s._1 + 1L, s._2 += 
v.toBreeze),
    +      combOp = (s1: (Long, BDV[Double]), s2: (Long, BDV[Double])) => 
(s1._1 + s2._1, s1._2 += s2._2)
    +    )
    +
    +    // Update _m if it is not set, or verify its value.
    +    if (nRows <= 0L) {
    +      nRows = m
    +    } else {
    +      require(nRows == m,
    +        s"The number of rows $m is different from what specified or 
previously computed: ${nRows}.")
    +    }
    +
    +    mean :/= m.toDouble
    +
    +    // We use the formula Cov(X, Y) = E[X * Y] - E[X] E[Y], which is not 
accurate if E[X * Y] is
    +    // large but Cov(X, Y) is small, but it is good for sparse computation.
    +    // TODO: find a fast and stable way for sparse data.
    +
    +    val G = computeGramianMatrix().toBreeze.asInstanceOf[BDM[Double]]
    +
    +    var i = 0
    +    var j = 0
    +    val m1 = m - 1.0
    +    var alpha = 0.0
    +    while (i < n) {
    +      alpha = m / m1 * mean(i)
    +      j = 0
    +      while (j < n) {
    +        G(i, j) = G(i, j) / m1 - alpha * mean(j)
    +        j += 1
    +      }
    +      i += 1
    +    }
    +
    +    Matrices.fromBreeze(G)
    +  }
    +
    +  /**
    +   * Computes the top k principal components.
    +   * Rows correspond to observations and columns correspond to variables.
    +   * The principal components are stored a local matrix of size n-by-k.
    +   * Each column corresponds for one principal component,
    +   * and the columns are in descending order of component variance.
    +   *
    +   * @param k number of top principal components.
    +   * @return a matrix of size n-by-k, whose columns are principal 
components
    +   */
    +  def computePrincipalComponents(k: Int): Matrix = {
    +    val n = numCols().toInt
    +    require(k > 0 && k <= n, s"k = $k out of range (0, n = $n]")
    +
    +    val Cov = computeCovariance().toBreeze.asInstanceOf[BDM[Double]]
    --- End diff --
    
    toBreeze is claimed to be for use in tests only, but we use it for PCA 
here. maybe update the comment in toBreeze to say it is OK to use when the 
matrix can fit on one machine


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---

Reply via email to