代码之家  ›  专栏  ›  技术社区  ›  watchtower

Scipy给出了错误的矩阵乘法结果

  •  1
  • watchtower  · 技术社区  · 8 年前

    我正在使用 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)

    enter image description here

    Element-wise power of scipy.sparse matrix , Matrix power for sparse matrix in python 怎样 做矩阵乘法。我很感激任何帮助。

    1 回复  |  直到 8 年前
        1
  •  1
  •   l'L'l    8 年前

    你可以用 ** 符号:

    (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 .