In [1]: from scipy import sparse
In [2]: x = np.eye(3)
In [3]: x
Out[3]:
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
In [4]: x.shape
Out[4]: (3, 3)
In [5]: xs = sparse.eye(3)
In [6]: xs
Out[6]:
<3x3 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements (1 diagonals) in DIAgonal format>
In [7]: print(xs)
(0, 0) 1.0
(1, 1) 1.0
(2, 2) 1.0
In [8]: xs.shape
Out[8]: (3, 3)
np sum 生成一个数组,维度少一(除非您使用keepdims 参数)
In [9]: x.sum(axis=1)
Out[9]: array([1., 1., 1.])
稀疏求和产生一个np.matrix 对象。
In [10]: xs.sum(axis=1)
Out[10]:
matrix([[1.],
[1.],
[1.]])
In [11]: _.shape
Out[11]: (3, 1)
np.matrix,根据定义,总是 2d。但它确实有一个 A1 属性,可以转换为 ndarray 并应用挤压。
In [12]: xs.sum(axis=1).A1
Out[12]: array([1., 1., 1.])
Sparse 实际上通过矩阵乘法来执行行或列求和:
In [21]: xs*np.matrix(np.ones((3,1)))
Out[21]:
matrix([[1.],
[1.],
[1.]])
稀疏矩阵 * np.matrix 产生 np.matrix
如果sum 使用ndarray,则结果将是ndarray,并且是可挤压的
In [22]: xs*np.ones((3,1))
Out[22]:
array([[1.],
[1.],
[1.]])
请注意,我使用了*(我本来可以使用@);乘法的稀疏定义(例如点)具有优先权。
In [23]: np.matrix(np.ones((1,3)))*xs
Out[23]: matrix([[1., 1., 1.]])