1

我的向量之一是 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 和这些数学包的新手,只是想了解一些关于稀疏矩阵运算的知识。我的问题是如何正确有效地进行这样的操作,因为我猜有一种方法不会每次都将稀疏表示恢复为密集。

谢谢!

4

1 回答 1

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 ]])
于 2013-05-21T02:52:45.570 回答