除非我们设置了keepdims=True
,否则在对numpy.ndarray
求和时,它会降低数组的维数。然而,这似乎不适用于Scipy的稀疏矩阵:
import scipy.sparse
matrix = scipy.sparse.coo_matrix([[0, 1], [2, 1]])
print(matrix.shape) # (2, 2) as expected.
print(matrix.sum().shape) # () as expected.
print(matrix.sum(axis=0).shape) # (1, 2) but expected (2,).
print(matrix.sum(axis=0)[0].shape) # (1, 2) but expected (2,).
如示例中最后一行所示,我甚至不能选择结果向量。此外,尝试将总和的结果转换为密集的Numpy数组失败:
matrix.toarray() # This works.
matrix.sum(axis=0).toarray() # AttributeError: 'matrix' has no 'toarray'.
如何沿一维计算稀疏矩阵的和,并以密集数组的形式获得结果?
https://stackoverflow.com/questions/47602925
复制