Numpy scipy.csr_矩阵导致的意外结果

Numpy scipy.csr_矩阵导致的意外结果,numpy,scipy,sparse-matrix,Numpy,Scipy,Sparse Matrix,这让我 >>> import numpy as np >>> from scipy.sparse import * >>> x1 = np.eye(3, dtype=float) >>> x2 = csr_matrix(x1, dtype=float, shape =x1.shape) >>> assert x2.todense().any()==x1.any() ## holds true >&g

这让我

>>> import numpy as np
>>> from scipy.sparse import *
>>> x1 = np.eye(3, dtype=float)
>>> x2 = csr_matrix(x1, dtype=float, shape =x1.shape)
>>> assert x2.todense().any()==x1.any()  ## holds true
>>> w = np.ones((3,1))
>>> dw1 = w - x1[:,0]
>>> dw2 = w - x2[:,0]


我的问题是为什么dw1和dw2不同?如果他们推迟,这是一个错误吗?非常感谢

这是一个切片/索引问题。这里有疑问的是

>>> print dw2
[[ 0.]
 [ 1.]
 [ 1.]]
这与稀疏无关。您已切片x1,获得1D数组。当它从w中减去时,numpy将这个数组广播回一个3乘3的矩阵(因为它等于这两个项的列数),我想这不是您想要的

看起来您只需要由x1的第一列组成的子矩阵。这将是

w - x1[:, 0]
返回

w - x1[:, [0]]
与其他结果一致


对于稀疏矩阵,您会自动获得子矩阵(而不是1D数组),因为索引对这些子矩阵的工作方式不同

这是因为这些切片分别是
1D
2D
-

array([[ 0.],
       [ 1.],
       [ 1.]])
另外,
w
是一个2D数组-

In [23]: x1[:,0]
Out[23]: array([ 1.,  0.,  0.])

In [24]: x2[:,0].toarray()
Out[24]: 
array([[ 1.],
       [ 0.],
       [ 0.]])

In [29]: x1[:,0].ndim
Out[29]: 1

In [30]: x2[:,0].toarray().ndim
Out[30]: 2
因此,随着
w的减法,w
分别沿
w的不同轴执行,即第二轴和第一轴。

x2
是稀疏矩阵,其行为非常类似于密集矩阵,例如
np.matrix(x1)
。这里
x2[:,0]
是(3,1)矩阵。
In [23]: x1[:,0]
Out[23]: array([ 1.,  0.,  0.])

In [24]: x2[:,0].toarray()
Out[24]: 
array([[ 1.],
       [ 0.],
       [ 0.]])

In [29]: x1[:,0].ndim
Out[29]: 1

In [30]: x2[:,0].toarray().ndim
Out[30]: 2
In [33]: w
Out[33]: 
array([[ 1.],
       [ 1.],
       [ 1.]])

In [34]: w.ndim
Out[34]: 2