Dot product between scipy sparse matrix and numpy

2019-08-27 00:13发布

问题:

I'm trying to calculate the dot product between a scipy parse matrix and a numpy array.

First I was using a numpy matrix, which you can see in the following code:

def power_iteration(matrix, n):
    b_k = np.random.rand(matrix.shape[1])
    for _ in range(n):
        b_k = np.dot(matrix, b_k)

    return b_k 

Here the matrix is a numpy matrix and no error occurs.

If you pass a scipy sparse matrix as a parameter, the following error occurs: ValueError: shapes (6762,6762) and (1,6762) not aligned: 6762 (dim 1) != 1 (dim 0)

I have changed

b_k = np.random.rand(matrix.shape[1])

into

b_k = np.random.rand(matrix.shape[1], 1)

which makes the dot product work, but doesn't return the right b_k shape. The shape I need is: (6762,)

Edit: so far I've tried to reshape like this:

b_k = np.reshape(b_k, (matrix.shape[1],))

but this transforms the shape (6762, 1) into (1, 6762), instead of (6762,)

Any tips? Thanks!

回答1:

Seems like in order to use np.dot on sparse matrix you'd need to convert it to dense matrix first with matrix.toarray(). Also see https://docs.scipy.org/doc/scipy/reference/sparse.html#matrix-vector-product