代码之家  ›  专栏  ›  技术社区  ›  Federico Caccia

重塑scipy csr矩阵

  •  0
  • Federico Caccia  · 技术社区  · 7 年前

    我怎样才能高效而简洁地重塑。稀疏csr\u矩阵?

    我需要在末尾添加零行。 使用:

    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.
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   hpaulj    7 年前

    如果可以尽早发现问题,只需包含一个形状参数:

    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 。它结合了 coo 属性,并生成新的 首席运营官 矩阵

        2
  •  3
  •   Warren Weckesser    7 年前

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

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

    如果要更改总大小,最终可以使用 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)