RowMatrix is a class in PySpark’s MLLib library that represents a distributed matrix consisting of rows. Each row in the matrix is represented as a SparseVector or DenseVector object. RowMatrix is useful for performing operations on large datasets that are too big to fit into memory on a single machine.
Creating a RowMatrix in PySpark
To create a RowMatrix in PySpark, you first need to create an RDD of vectors. You can create an RDD of DenseVectors by calling the parallelize() method on a list of NumPy arrays:
You can also create an RDD of SparseVectors by passing in an array of tuples representing the indices and values of each non-zero element:
This example creates a SparkSession object, creates an RDD of vectors, and creates a RowMatrix object from the RDD. It then converts the RowMatrix to an IndexedRowMatrix using the IndexedRowMatrix() constructor and the zipWithIndex() method, converts the IndexedRowMatrix to a CoordinateMatrix using the toCoordinateMatrix() method, transposes the CoordinateMatrix using the transpose() method, and converts the resulting transposed CoordinateMatrix back to an IndexedRowMatrix using the toIndexedRowMatrix() method. Finally, it computes the column similarities of the transposed IndexedRowMatrix using the columnSimilarities() method and prints the result.
Compute Singular Value Decomposition (SVD)
To compute the Singular Value Decomposition (SVD) of a RowMatrix, you call the computeSVD() method. The SVD is a factorization of a matrix into three matrices: U, S, and V. The U matrix is a unitary matrix whose columns are the left singular vectors of the original matrix. The V matrix is a unitary matrix whose columns are the right singular vectors of the original matrix. The S matrix is a diagonal matrix whose diagonal entries are the singular values of the original matrix.
The k parameter specifies the number of singular values to compute. The computeU parameter specifies whether to compute the U matrix.
Spark important urls to refer