访问 python 中特定矩阵行中的非零元素

Accessing non-zero elements in specific row of matrix in python

我有 python 中稀疏矩阵中非零元素位置的索引,形式为

(array([0, 1, 2], dtype=int32), array([2, 0, 0], dtype=int32), array([2, 1, 3]))

或者矩阵形式

[[0 2]
 [1 0]
 [2 0]]

我想用这个(或者其他方法,如果有的话)只对其他矩阵的相应非零元素进行逐行运算,像这样:

for r in range(rows):
    A[r,:] = np.dot(B[r,:],C.T)

基本上我需要一种方法来指定行,并且只从该行中选择与矩阵 B 中的非零元素相对应的元素。

我无法理解的部分是因为每个 row/column 可能有不同数量的条目。

我有点不明白第一个元组代表什么。它是稀疏数组的索引和值吗?例如

In [4]: arrays=(np.array([0, 1, 2], dtype=int), np.array([2, 0, 0], dtype=int), np.array([2, 1, 3], dtype=float))
...
In [6]: from scipy import sparse
In [7]: M=sparse.csr_matrix((arrays[2],(arrays[0],arrays[1])))
In [8]: M
Out[8]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Row format>
In [9]: M.A
Out[9]: 
array([[ 0.,  0.,  2.],
       [ 1.,  0.,  0.],
       [ 3.,  0.,  0.]])

In [10]: print(M)
  (0, 2)    2.0
  (1, 0)    1.0
  (2, 0)    3.0

为这样的数组定义了矩阵乘法:

In [12]: M*M.T
Out[12]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>
In [13]: (M*M.T).A
Out[13]: 
array([[ 4.,  0.,  0.],
       [ 0.,  1.,  3.],
       [ 0.,  3.,  9.]])
In [14]: M.A.dot(M.A.T)  # dense equivalent
Out[14]: 
array([[ 4.,  0.,  0.],
       [ 0.,  1.,  3.],
       [ 0.,  3.,  9.]])

我可以用这个数组实现逐行乘法:

In [21]: A=M.A      # dense array
In [22]: for r in range(3):
    print(np.dot(A[r,:],A[r,:]))
4.0
1.0
9.0
# actually this is just the diagonal

In [23]: for r in range(3):   # or with the nonzero elements
    I=np.nonzero(A[r,:])
    dot = np.dot(A[r,I[0]],A[r,I[0]])
    print(dot)
4.0
1.0
9.0

为了它的价值,nonzero returns 我从你的 post 开始复制的数组:

In [24]: np.nonzero(A)
Out[24]: (array([0, 1, 2], dtype=int32), array([2, 0, 0], dtype=int32))
In [25]: A[np.nonzero(A)]
Out[25]: array([ 2.,  1.,  3.])

稀疏矩阵还有一个nonzero方法:

In [26]: M.nonzero()
Out[26]: (array([0, 1, 2], dtype=int32), array([2, 0, 0], dtype=int32))

我觉得自己在四处挣扎,试图弄清问题和示例。

我发现你可以在 python 中使用布尔数组索引,所以下面是我想要实现的:

for r in range(rows):
    A[r,B[r,:]!=0] = np.dot(B[r , B[r,:]!=0], C[: , B[r,:]!=0].T)

看起来有点复杂,但它得到了正确的计算元素。唯一的问题是当 B 的维度大于它所索引的维度时会抛出索引越界错误。