【问题标题】:How to do operations with two vectors of different format in python如何在python中对两个不同格式的向量进行操作
【发布时间】:2013-05-15 16:40:23
【问题描述】:

我的一个向量的格式是 scipy.sparse.csr.csr_matrix,另一个是 numpy.ndarray。我在下面有一个实验代码:

import numpy as np
from scipy.sparse import csr_matrix

x = np.arange(5)+1
y = [1, 0, 0, 1, 2]
y = csr_matrix(y)
print type(x)
print type(y)

z = np.true_divide(y,x)
print z.shape

我得到 z.shape = (5L,) 并且不知道它是什么意思。如果我打印 z 它告诉我它是一个包含 3 个元素的行向量。 如何打印数字结果,例如来自 z 的 1*5 向量?我是 Python 和这些数学包的新手,只是想了解一些关于稀疏矩阵运算的知识。我的问题是如何正确有效地进行这样的操作,因为我想有一种方法不会每次都将稀疏表示恢复为密集。

谢谢!

【问题讨论】:

    标签: python numpy scipy sparse-matrix


    【解决方案1】:

    你可以这样做:

    import numpy as np
    from scipy.sparse import csr_matrix
    
    x = np.arange(5)+1
    
    y = [1, 0, 0, 1, 2]
    y = csr_matrix(y)
    
    x2 = 1.0 / np.matrix(x)
    
    z = y.multiply(x2)
    

    结果:

    >>> z
    matrix([[ 1.  ,  0.  ,  0.  ,  0.25,  0.4 ]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多