【问题标题】:Error converting large sparse matrix to COO将大型稀疏矩阵转换为 COO 时出错
【发布时间】:2014-09-08 21:06:52
【问题描述】:

我在尝试 vstack 两个大型 CSR 矩阵时遇到了以下问题:

    /usr/lib/python2.7/dist-packages/scipy/sparse/coo.pyc in _check(self)
    229                 raise ValueError('negative row index found')
    230             if self.col.min() < 0:
--> 231                 raise ValueError('negative column index found')
    232
    233     def transpose(self, copy=False):

ValueError: negative column index found

我可以通过尝试将大型 lil 矩阵转换为 coo 矩阵来非常简单地重现此错误。以下代码适用于 N=10**9,但适用于 N=10**10。

from scipy import sparse
from numpy import random
N=10**10
x = sparse.lil_matrix( (1,N) )
for _ in xrange(1000):
    x[0,random.randint(0,N-1)]=random.randint(1,100)

y = sparse.coo_matrix(x)

我对 coo 矩阵有大小限制吗?有没有解决的办法?

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    看起来您已达到 32 位整数的限制。这是一个快速测试:

    In [14]: np.array([10**9, 10**10], dtype=np.int64)
    Out[14]: array([ 1000000000, 10000000000])
    
    In [15]: np.array([10**9, 10**10], dtype=np.int32)
    Out[15]: array([1000000000, 1410065408], dtype=int32)
    

    目前,大多数稀疏矩阵表示采用 32 位整数索引,因此它们根本无法支持那么大的矩阵。

    编辑:从 0.14 版开始,scipy 现在支持 64 位索引。如果你能升级,这个问题就会消失。

    【讨论】:

    • 你是绝对正确的。升级到 0.14.0 解决了这个问题。
    【解决方案2】:

    有趣的是,您的第二个示例在我的安装中运行良好。

    错误消息“找到负列索引”听起来像是某处溢出。我检查了最新的来源,结果如下:

    • 实际的索引数据类型在scipy.sparse.sputils.get_index_dtype中计算
    • 错误消息来自模块scipy.sparse.coo

    异常来自这种代码:

        idx_dtype = get_index_dtype(maxval=max(self.shape))
        self.row = np.asarray(self.row, dtype=idx_dtype)
        self.col = np.asarray(self.col, dtype=idx_dtype)
        self.data = to_native(self.data)
    
        if nnz > 0:
            if self.row.max() >= self.shape[0]:
                raise ValueError('row index exceeds matrix dimensions')
            if self.col.max() >= self.shape[1]:
                raise ValueError('column index exceeds matrix dimensions')
            if self.row.min() < 0:
                raise ValueError('negative row index found')
            if self.col.min() < 0:
                raise ValueError('negative column index found')
    

    这是一个明显的溢出错误 - 可能是 - 2**31。

    如果你想调试它,试试:

    import scipy.sparse.sputils
    import numpy as np
    
    scipy.sparse.sputils.get_index_dtype((np.array(10**10),))
    

    它应该返回int64。如果不存在问题。

    哪个版本的 SciPy?

    【讨论】:

    • 我运行的是 0.13.3,它没有函数 scipy.sparse.sputils.get_index_dtype。升级到 0.14.0 解决了这个问题,get_index_dtype 实际上返回 int64。
    猜你喜欢
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2021-11-25
    • 2017-07-02
    • 1970-01-01
    相关资源
    最近更新 更多