Dot product between scipy sparse matrix and numpy array give ValueError

孤街醉人 提交于 2020-01-06 06:42:05

问题


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



来源:https://stackoverflow.com/questions/55776220/dot-product-between-scipy-sparse-matrix-and-numpy-array-give-valueerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!