【问题标题】:Set directly data members in scipy sparse matrix在 scipy 稀疏矩阵中直接设置数据成员
【发布时间】:2020-03-08 02:02:23
【问题描述】:

我正在构建一个大型 CSR 稀疏矩阵,即使在稀疏格式下也使用相当多的内存,所以我想在创建矩阵时避免复制。我发现最有效的方法是直接构建压缩的稀疏行表示。但是,类初始化程序复制了我传递给它的数组,所以我直接设置了数据成员。示例:

from scipy import sparse
m = sparse.csr_matrix((5,5))
m.data = np.arange(5)
m.indices = np.arange(5)
m.indptr = np.arange(6)

这似乎可行,但我在文档中没有找到它,我想知道它是否受支持,是否破坏了我没有尝试过的东西。

此外,了解我是否可以使用没有怪癖的 memmapped 数组或使用不同的整数数据类型作为索引会很有用。

编辑:

接受的答案表明,只要索引类型正确,就不会发生复制。我检查了__init__,即使它没有复制indicesindptr,它也会扫描两次以找到最小值和最大值,它实际上只是设置@如果输入格式正确,则为 987654326@、indicesindptr 成员,所以为了性能,我现在正在做的是:

# [...] get shape and data from somewhere
m = sparse.csr_matrix(shape, dtype=data.dtype)
indices = np.empty(..., dtype=m.indices.dtype)
indptr = np.empty(..., dtype=m.indptr.dtype)
# [...] fill indices and indptr
m.data = data
m.indices = indices
m.indptr = indptr
# Possibly also do one or both of the following:
m.has_sorted_indices = True
m.has_canonical_format = True

【问题讨论】:

标签: python scipy sparse-matrix


【解决方案1】:

下面是一个不复制定义数组而制作稀疏矩阵的示例:

In [191]: data=np.arange(5) 
     ...: indices=np.arange(5).astype('int32') 
     ...: indptr=np.arange(6).astype('int32')                                                  
In [192]: M = sparse.csr_matrix((data,indices,indptr))                                         
In [193]: data.__array_interface__['data'], M.data.__array_interface__['data']                 
Out[193]: ((55897168, False), (55897168, False))
In [194]: indices.__array_interface__['data'], M.indices.__array_interface__['data']           
Out[194]: ((70189040, False), (70189040, False))
In [195]: indptr.__array_interface__['data'], M.indptr.__array_interface__['data']             
Out[195]: ((56184432, False), (56184432, False))

https://github.com/scipy/scipy/blob/v1.4.1/scipy/sparse/compressed.py

我写这句话时考虑到了__init__。还请查看 check_format 方法,了解它检查的一致性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 2018-03-18
    • 2017-03-26
    • 2017-03-31
    • 1970-01-01
    • 2023-04-10
    • 2017-07-21
    相关资源
    最近更新 更多