为什么挤压在稀疏数组上不起作用?

Pri*_*ham 2 python numpy scipy

我有以下代码:

import numpy as np
from scipy import sparse

x = np.eye(3)
print(x.sum(axis=1).shape)

x = sparse.eye(3)
print(x.sum(axis=1).shape)
print(x.sum(axis=1).squeeze().shape)
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

(3,)
(3, 1)
(1, 3)
Run Code Online (Sandbox Code Playgroud)

看起来squeeze没有按预期工作。我究竟做错了什么?

hpa*_*ulj 5

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)
Run Code Online (Sandbox Code Playgroud)

总和np生成一个数组,少一维(除非您使用keepdims参数)

In [9]: x.sum(axis=1)                                                                            
Out[9]: array([1., 1., 1.])
Run Code Online (Sandbox Code Playgroud)

稀疏和产生一个np.matrix对象。

In [10]: xs.sum(axis=1)                                                                          
Out[10]: 
matrix([[1.],
        [1.],
        [1.]])
In [11]: _.shape                                                                                 
Out[11]: (3, 1)
Run Code Online (Sandbox Code Playgroud)

np.matrix根据定义,总是 2d。但它确实有一个A1可以转换为ndarray并应用挤压的属性。

In [12]: xs.sum(axis=1).A1                                                                       
Out[12]: array([1., 1., 1.])
Run Code Online (Sandbox Code Playgroud)

Sparse 实际上是通过矩阵乘法来执行行或列求和:

In [21]: xs*np.matrix(np.ones((3,1)))                                                            
Out[21]: 
matrix([[1.],
        [1.],
        [1.]])
Run Code Online (Sandbox Code Playgroud)

稀疏矩阵 * np.matrix 生成 np.matrix

如果sum使用ndarray,结果将是ndarray和 可挤压的

In [22]: xs*np.ones((3,1))                                                                       
Out[22]: 
array([[1.],
       [1.],
       [1.]])
Run Code Online (Sandbox Code Playgroud)

请注意,我使用了*(我本来可以使用@);乘法(例如点)的稀疏定义具有优先权。

In [23]: np.matrix(np.ones((1,3)))*xs                                                            
Out[23]: matrix([[1., 1., 1.]])
Run Code Online (Sandbox Code Playgroud)

  • 我不知道“A1”,谢谢!那么,squeeze 不起作用,因为 np.matrix 始终是二维的? (2认同)