Numpy(稀疏)重复索引增量

Numpy (sparse) repeated index increment

ab 是一维 numpy ndarray,大小相同,数据类型为整数。

C 是二维 scipy.sparse.lil_matrix.

如果索引 [a, b] 包含重复索引,对于 C 的每个唯一索引 [a, b]C[a, b] += np.array([1]) 是否总是递增 C 一次?

文档有提到这个吗?

示例:

import scipy.sparse as ss
import numpy as np
C = ss.lil_matrix((3,2), dtype=int)
a = np.array([0, 1, 2] * 4)
b = np.array([0, 1] * 6)
C[a, b] += np.array([1])
print(C.todense(), '\n')
C[a, b] += np.array([1])
print(C.todense())

结果:

[[1 1]
 [1 1]
 [1 1]] 

[[2 2]
 [2 2]
 [2 2]]

我不知道它有记录

众所周知,由于缓冲,密集数组每个唯一索引只设置一次。我们必须使用 add.at 来获得无缓冲的加法。

In [966]: C=sparse.lil_matrix((3,2),dtype=int)
In [967]: Ca=C.A
In [968]: Ca += 1
In [969]: Ca
Out[969]: 
array([[1, 1],
       [1, 1],
       [1, 1]])

In [970]: Ca=C.A
In [973]: np.add.at(Ca,(a,b),1)
In [974]: Ca
Out[974]: 
array([[2, 2],
       [2, 2],
       [2, 2]])

您的示例表明 lil 索引设置在缓冲意义上也起作用。但我必须查看代码才能确切了解原因。

据记载,coo 样式输入在重复项中求和。

In [975]: M=sparse.coo_matrix((np.ones_like(a),(a,b)), shape=(3,2))
In [976]: print(M)
  (0, 0)    1
  (1, 1)    1
  (2, 0)    1
  (0, 1)    1
  (1, 0)    1
  (2, 1)    1
  (0, 0)    1
  (1, 1)    1
  (2, 0)    1
  (0, 1)    1
  (1, 0)    1
  (2, 1)    1
In [977]: M.A
Out[977]: 
array([[2, 2],
       [2, 2],
       [2, 2]])
In [978]: M
Out[978]: 
<3x2 sparse matrix of type '<class 'numpy.int32'>'
    with 12 stored elements in COOrdinate format>
In [979]: M.tocsr()
Out[979]: 
<3x2 sparse matrix of type '<class 'numpy.int32'>'
    with 6 stored elements in Compressed Sparse Row format>
In [980]: M.sum_duplicates()
In [981]: M
Out[981]: 
<3x2 sparse matrix of type '<class 'numpy.int32'>'
    with 6 stored elements in COOrdinate format>

点以输入的 coo 格式存储,但当用于显示或计算(csr 格式)时,重复项被相加。