【发布时间】:2019-03-24 01:11:38
【问题描述】:
我正在使用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)
方法二:
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()
输出:
matrix([[ 256, 0, 576, 0],
[ 0, 2401, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 625]], dtype=int32)
方法四:
可以在this website (symbolab.com)查看结果
关于此主题的其他主题(Element-wise power of scipy.sparse matrix、Matrix power for sparse matrix in python),重点关注如何 进行矩阵乘法。如有任何帮助,我将不胜感激。
【问题讨论】:
-
p.power(2)是“元素方面的力量”。9**4=6561。您链接的第一个线程也这么说(甚至在标题中)。 -
谢谢辛基。如果您可以添加答案,我可以接受。
标签: python numpy matrix scipy matrix-multiplication