2013-05-12 83 views

回答

7

我不知道任何已建立的良好实践,所以这里是一个相当简单的coo_matrix重塑函数。它将它的参数转换为一个coo_matrix,所以它会为其他稀疏格式实际工作(但它会返回一个coo_matrix)。

from scipy.sparse import coo_matrix 


def reshape(a, shape): 
    """Reshape the sparse matrix `a`. 

    Returns a coo_matrix with shape `shape`. 
    """ 
    if not hasattr(shape, '__len__') or len(shape) != 2: 
     raise ValueError('`shape` must be a sequence of two integers') 

    c = a.tocoo() 
    nrows, ncols = c.shape 
    size = nrows * ncols 

    new_size = shape[0] * shape[1] 
    if new_size != size: 
     raise ValueError('total size of new array must be unchanged') 

    flat_indices = ncols * c.row + c.col 
    new_row, new_col = divmod(flat_indices, shape[1]) 

    b = coo_matrix((c.data, (new_row, new_col)), shape=shape) 
    return b 

例子:

In [43]: a = coo_matrix([[0,10,0,0],[0,0,0,0],[0,20,30,40]]) 

In [44]: a.A 
Out[44]: 
array([[ 0, 10, 0, 0], 
     [ 0, 0, 0, 0], 
     [ 0, 20, 30, 40]]) 

In [45]: b = reshape(a, (2,6)) 

In [46]: b.A 
Out[46]: 
array([[ 0, 10, 0, 0, 0, 0], 
     [ 0, 0, 0, 20, 30, 40]]) 

现在,我敢肯定,有几个经常投稿这里能拿出更好的东西(更快,内存更高效,少填谁... :)

+0

更新:这个问题已经在解决[ENH:重塑稀疏矩阵#3957](https://github.com/scipy/scipy/pull/3957), @Warren Weckesser在这里的解决方案被选中。 – zaxliu 2015-09-18 11:18:24

0

我来回CSR矩阵一个工作的例子,但我不能保证它始终工作

扁平化矩阵A:

indices = zeros_like(A.indices) 
    indices[A.indptr[1:-1]] = A.shape[1] 
    indices = cumsum(indices)+A.indices 
    A_flat = sparse.csc_matrix((T_rot.data, indices,[0,size(A)]),shape=(prod(A.shape),1)) 

重塑矩阵A

indices = zeros_like(A.indices) 
    indices[A.indptr[1:-1]] = A.shape[1] 
    indices = cumsum(indices)+A.indices 

    indices %= N*A.shape[1] 
    indptr = r_[0, where(diff(indices)<0)[0]+1, size(A)] 
    A_reshaped = sparse.csc_matrix((A.data, indices,indptr),shape=(N*A.shape[1],A.shape[0]/N))