Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create sparse RDD from scipy sparse matrix

I have a large sparse matrix from scipy (300k x 100k with all binary values, mostly zeros). I would like to set the rows of this matrix to be an RDD and then do some computations on those rows - evaluate a function on each row, evaluate functions on pairs of rows, etc.

Key thing is that it's quite sparse and I don't want to explode the cluster - can I convert the rows to SparseVectors? Or perhaps convert the whole thing to SparseMatrix?

Can you give an example where you read in a sparse array, setup rows into an RDD, and compute something from the cartesian product of those rows?

like image 243
cgreen Avatar asked Oct 25 '25 14:10

cgreen


1 Answers

I had this issue recently--I think you can convert directly by constructing the SparseMatrix with the scipy csc_matrix attributes. (Borrowing from Yang Bryan)

import numpy as np
import scipy.sparse as sps
from pyspark.mllib.linalg import Matrices

# create a sparse matrix
row = np.array([0, 2, 2, 0, 1, 2])
col = np.array([0, 0, 1, 2, 2, 2])
data = np.array([1, 2, 3, 4, 5, 6]) 
sv = sps.csc_matrix((data, (row, col)), shape=(3, 3))

# convert to pyspark SparseMatrix
sparse_matrix = Matrices.sparse(sv.shape[0],sv.shape[1],sv.indptr,sv.indices,sv.data)
like image 130
howlynkat Avatar answered Oct 27 '25 05:10

howlynkat