【发布时间】:2015-02-19 11:23:40
【问题描述】:
我有一维的csr_matrix 的总和,它返回一个一维向量。默认情况下,该类型为 numpy.matrix,形状为 (1, N)。但是,我想用形状为 (N,) 的numpy.array 来表示它。以下作品:
>>> import numpy as np; import scipy.sparse as sparse
>>> a = sparse.csr_matrix([[0,1,0,0],[1,0,0,0],[0,1,2,0]])
>>> a
Out[15]:
<3x4 sparse matrix of type '<class 'numpy.int64'>'
with 4 stored elements in Compressed Sparse Row format>
>>> a.todense()
Out[16]:
matrix([[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 1, 2, 0]], dtype=int64)
>>> a.sum(axis=0)
Out[17]: matrix([[1, 2, 2, 0]], dtype=int64)
>>> np.array(a.sum(axis=0)).ravel()
Out[18]: array([1, 2, 2, 0], dtype=int64)
但是,对于从 numpy 矩阵到 numpy 数组的转换,这最后一步似乎有点矫枉过正。我是否缺少可以为我执行此操作的功能?它应该通过以下单元测试。
def test_conversion(self):
a = sparse.csr_matrix([[0,1,0,0],[1,0,0,0],[0,1,2,0]])
r = a.sum(axis=0)
e = np.array([1, 2, 2, 0])
np.testing.assert_array_equal(r, e)
【问题讨论】:
-
请注意,虽然
a本身是一个稀疏矩阵,但总和是一个np.matrix。.A1之类的快捷方式适用于后者,但不适用于稀疏的。