我正在使用
scipy
.power()
方法不适用于稀疏矩阵。我用三种方法进行了检查:
import scipy as sp
import scipy.sparse
方法1:普通矩阵乘法
row = np.array([0, 3, 1, 0])
col = np.array([0, 3, 1, 2])
data = np.array([4, 5, 7, 9])
P1 = sp.sparse.coo_matrix((data, (row, col)), shape=(4, 4))
#Method 1
P1.power(4).todense() #gives wrong result
结果:
matrix([[ 256, 0, 6561, 0], #6561 isn't right
[ 0, 2401, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 625]], dtype=int32)
方法2:
P = P1.copy()
#calculate ^4
for loop in range(2):
P = P.dot(P)
P.todense()
输出
matrix([[ 256, 0, 576, 0],
[ 0, 2401, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 625]], dtype=int32)
方法3
P1.dot(P1).dot(P1).dot(P1).todense()
矩阵([[256,0,576,0],
[ 0, 2401, 0, 0],
[0,0,0,625]],数据类型=int32)
方法4:
你可以随时查看结果
this website (symbolab.com)
Element-wise power of scipy.sparse matrix
,
Matrix power for sparse matrix in python
怎样
做矩阵乘法。我很感激任何帮助。