【问题标题】:Numpy (sparse) repeated index incrementNumpy(稀疏)重复索引增量
【发布时间】:2017-12-29 08:50:50
【问题描述】:

ab 是 1D numpy ndarray,大小与整数数据类型相同。

C 是一个二维的scipy.sparse.lil_matrix

如果索引[a, b] 包含重复索引,C[a, b] += np.array([1]) 是否总是为 C 的每个唯一索引增加一次 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]]

【问题讨论】:

    标签: python numpy indexing scipy sparse-matrix


    【解决方案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 格式)时,重复项被求和。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 2019-05-15
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多