Scipy sparse matrix multiplication

青春壹個敷衍的年華 提交于 2019-12-04 21:43:00

问题


I have this example of matrix by matrix multiplication using numpy arrays:

import numpy as np
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
c = np.array([0,1,2])
m * c
array([[ 0,  2,  6],
       [ 0,  5, 12],
       [ 0,  8, 18]])

How can i do the same thing if m is scipy sparse CSR matrix? This gives dimension mismatch:

sp.sparse.csr_matrix(m)*sp.sparse.csr_matrix(c)

回答1:


You can call the multiply method of csr_matrix to do pointwise multiplication.

sparse.csr_matrix(m).multiply(sparse.csr_matrix(c)).todense()

# matrix([[ 0,  2,  6],
#         [ 0,  5, 12],
#         [ 0,  8, 18]], dtype=int64)



回答2:


When m and c are numpy arrays, then m * c is not "matrix multiplication". If you think it is then you may be making a mistake. To get matrix multiplication use a matrix class, like numpy's matrix or the scipy.sparse matrix classes.

The reason you are getting the failure is that from the matrix point of view c is a 1x3 matrix:

c = np.matrix([0, 1, 2]) 
c.shape    # (1,3)

c = sp.csc_matrix([0, 1, 2])
c.shape    # (1,3)

If what you want is the matrix multiplication with c then you need to use the transpose.

c = np.matrix([0, 1, 2]).transpose()
c.shape    # (3,1)

m = np.matrix([[1,2,3],[4,5,6],[7,8,9]])
m.shape    # (3,3)

m * c
# matrix([[ 8],
#         [17],
#         [26]])


来源:https://stackoverflow.com/questions/42537943/scipy-sparse-matrix-multiplication

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