我正在构建一个大型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__,即使它不复制indices和indptr,它也会扫描两次以找到最小值和最大值,如果输入格式良好,它只会设置data、indices和indptr成员,所以为了性能起见,我现在要做的是:
# [...] 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发布于 2020-03-07 17:11:34
下面是一个不复制定义数组而生成稀疏矩阵的示例:
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方法,查看它检查的一致性。
https://stackoverflow.com/questions/60576821
复制相似问题