【问题标题】:Scipy gives wrong result for matrix multiplicationScipy 给出了错误的矩阵乘法结果
【发布时间】: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 matrixMatrix power for sparse matrix in python),重点关注如何 进行矩阵乘法。如有任何帮助,我将不胜感激。

【问题讨论】:

  • p.power(2) 是“元素方面的力量”。 9**4 = 6561。您链接的第一个线程也这么说(甚至在标题中)。
  • 谢谢辛基。如果您可以添加答案,我可以接受。

标签: python numpy matrix scipy matrix-multiplication


【解决方案1】:

您可以使用** 表示法:

(P1**4).todense()

结果:

[[ 256    0  576    0]
 [   0 2401    0    0]
 [   0    0    0    0]
 [   0    0    0  625]]

编辑:关于.power() 没有返回预期结果的原因:

——正如Zinki 在他们的comment 中提到的那样:

p.power(2) 是“元素方面的力量”。 9**4 = 6561.

【讨论】:

  • 谢谢,我会的。非常恭敬地,问题不在于 how 进行乘法运算,而是关于为什么我得到一个不正确的答案。我相信有 50K 种乘法方法。
  • 不客气! Zinki 的评论或多或少总结了为什么你没有得到正确的结果。
  • 哦,谢谢...刚刚看到...太棒了。如果您可以编辑您的答案,我会接受。
猜你喜欢
  • 2011-06-22
  • 2023-04-07
  • 1970-01-01
  • 2014-11-29
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多