gpt4 book ai didi

python - 如何在 scipy 中创建一个巨大的稀疏矩阵

转载 作者:太空狗 更新时间:2023-10-29 21:37:21 24 4
gpt4 key购买 nike

我正在尝试创建一个非常大的稀疏矩阵,其形状为 (447957347, 5027974)。并且,它包含 3,289,288,566 个元素。

但是,当我使用 scipy.sparse 创建一个 csr_matrix 时,它返回如下内容:

<447957346x5027974 sparse matrix of type '<type 'numpy.uint32'>'
with -1005678730 stored elements in Compressed Sparse Row format>

创建矩阵的源码是:

indptr = np.array(a, dtype=np.uint32)    # a is a python array('L') contain row index information
indices = np.array(b, dtype=np.uint32) # b is a python array('L') contain column index information
data = np.ones((len(indices),), dtype=np.uint32)
test = csr_matrix((data,indices,indptr), shape=(len(indptr)-1, 5027974), dtype=np.uint32)

而且,我还发现当我将一个 30 亿长的 python 数组转换为 numpy 数组时,它会引发错误:

ValueError:setting an array element with a sequence

但是,当我创建三个 10 亿长度的 python 数组,并将它们转换为 numpy 数组,然后追加它们时。它工作正常。

我很困惑。

最佳答案

您使用的是旧版本的 SciPy。在稀疏矩阵的原始实现中,索引存储在 int32 变量中,即使在 64 位系统上也是如此。即使您像您那样将它们定义为 uint32,它们也会被强制转换。因此,只要您的矩阵有超过 2^31 - 1 个非零条目,就像您的情况一样,索引就会溢出,并且会发生很多不好的事情。请注意,在您的情况下,元素的奇怪负数解释为:

>>> np.int32(np.int64(3289288566))
-1005678730

好消息是这已经被解决了。我想this是相关的 PR,尽管在那之后还有一些修复。在任何情况下,如果您使用 latest release candidate对于 SciPy 0.14,您的问题应该消失了。

关于python - 如何在 scipy 中创建一个巨大的稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23381497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com