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

Ofe*_*fey 7 python arrays numpy scipy sparse-matrix

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

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

<447957346x5027974 sparse matrix of type '<type 'numpy.uint32'>'
    with -1005678730 stored elements in Compressed Sparse Row format>
Run Code Online (Sandbox Code Playgroud)

创建矩阵的源代码是:

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)
Run Code Online (Sandbox Code Playgroud)

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

ValueError:setting an array element with a sequence
Run Code Online (Sandbox Code Playgroud)

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

我糊涂了.

Jai*_*ime 9

您使用的是旧版SciPy.在稀疏矩阵的原始实现中,索引存储在int32变量中,即使在64位系统上也是如此.即使你uint32像他们一样定义它们,它们也会被铸造出来.因此,每当您的矩阵具有多于2^31 - 1非零条目时,就像您的情况一样,索引溢出并发生许多不好的事情.请注意,在您的情况下,奇怪的负数元素解释为:

>>> np.int32(np.int64(3289288566))
-1005678730
Run Code Online (Sandbox Code Playgroud)

好消息是,这已经被弄清楚了.我认为是相关的PR,尽管在那之后还有一些更多的修复.在任何情况下,如果您使用SciPy 0.14 的最新候选版本,您的问题应该消失.

  • Scipy(> = 0.14.0)使用所需的最小整数大小. (2认同)