【发布时间】: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__,即使它没有复制indices 和indptr,它也会扫描两次以找到最小值和最大值,它实际上只是设置@如果输入格式正确,则为 987654326@、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
【问题讨论】:
-
相关的
__init__是_cs_matrixin github.com/scipy/scipy/blob/v1.4.1/scipy/sparse/compressed.py。当您直接传递data,indices,indptr时,就是len(arg1) == 3的情况。如果dtypes正确,则不会进行复制。
标签: python scipy sparse-matrix