【问题标题】:reshape scipy csr matrix重塑 scipy csr 矩阵
【发布时间】:2018-04-29 15:21:23
【问题描述】:

如何有效地重塑和 scipy.sparse csr_matrix?

我需要在最后添加零行。 使用:

from scipy.sparse import csr_matrix
data = [1,2,3,4,5,6]
col = [0,0,0,1,1,1]
row = [0,1,2,0,1,2]
a = csr_matrix((data, (row, col)))
a.reshape(3,5)

我收到此错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/scipy/sparse/base.py", line 129, in reshape
self.__class__.__name__)
NotImplementedError: Reshaping not implemented for csr_matrix.

【问题讨论】:

    标签: scipy sparse-matrix reshape


    【解决方案1】:

    如果您能及早发现问题,只需包含一个形状参数:

    In [48]: a = csr_matrix((data, (row, col)))
    In [49]: a
    Out[49]: 
    <3x2 sparse matrix of type '<class 'numpy.int64'>'
        with 6 stored elements in Compressed Sparse Row format>
    In [50]: a = csr_matrix((data, (row, col)),shape=(3,5))
    In [51]: a
    Out[51]: 
    <3x5 sparse matrix of type '<class 'numpy.int64'>'
        with 6 stored elements in Compressed Sparse Row format>
    In [52]: a.A
    Out[52]: 
    array([[1, 4, 0, 0, 0],
           [2, 5, 0, 0, 0],
           [3, 6, 0, 0, 0]], dtype=int64)
    

    您也可以在平板电脑上hstack。确保它是稀疏版本:

    In [59]: z = sparse.coo_matrix(np.zeros((3,3)))
    In [60]: z
    Out[60]: 
    <3x3 sparse matrix of type '<class 'numpy.float64'>'
        with 0 stored elements in COOrdinate format>
    In [61]: sparse.hstack((a,z))
    Out[61]: 
    <3x5 sparse matrix of type '<class 'numpy.float64'>'
        with 6 stored elements in COOrdinate format>
    In [62]: _.A
    Out[62]: 
    array([[1., 4., 0., 0., 0.],
           [2., 5., 0., 0., 0.],
           [3., 6., 0., 0., 0.]])
    

    hstack 使用sparse.bmat。这结合了 2 个数组的 coo 属性,并创建了一个新的 coo 矩阵。

    【讨论】:

    • 我不知道我可以使用 sparse.hstack()。事实上,我需要的是 sparse.vstack(),但感谢这个想法!它有效!
    【解决方案2】:

    reshape() 方法将与即将发布的 scipy 1.1 中的 csr_matrix 对象一起使用。同时,您可以尝试Reshape sparse matrix efficiently, Python, SciPy 0.12 的代码来重塑稀疏矩阵。

    但是,您的示例不起作用,因为您正试图将形状为 (3, 2) 的数组重塑为形状为 (3, 5) 的数组。上面链接的代码和稀疏的reshape() 方法遵循与numpy 数组的reshape() 方法相同的规则:您不能更改数组的总大小。

    如果要更改总大小,最终可以使用resize() 方法(就地操作),但这也是 scipy 1.1 的新特性,因此尚未发布。

    相反,您可以构造一个新的稀疏矩阵,如下所示:

    In [57]: b = csr_matrix((a.data, a.indices, a.indptr), shape=(3, 5))
    
    In [58]: b.shape
    Out[58]: (3, 5)
    
    In [59]: b.A
    Out[59]: 
    array([[1, 4, 0, 0, 0],
           [2, 5, 0, 0, 0],
           [3, 6, 0, 0, 0]], dtype=int64)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-09
      • 2016-10-29
      • 1970-01-01
      • 2019-08-09
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多