a
,b
是具有整数数据类型的相同大小的1D numpy
ndarray
。
C
是2D scipy.sparse.lil_matrix
。
如果索引[a, b]
包含重复的索引,C[a, b] += np.array([1])
的每个唯一索引C
的{{1}}总是C
总是增加[a, b]
吗?
文档是否提到了这个?
示例:
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]]
答案 0 :(得分:1)
我不知道它已被记录
众所周知,由于缓冲,每个唯一索引只设置一次密集数组。我们必须使用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格式)时,将对重复项进行求和。