有效地重塑稀疏矩阵,Python,SciPy 0.12

2023-12-12

In 另一篇关于在 SciPy 中调整稀疏矩阵大小的文章当要添加更多行或列时,接受的答案有效,使用scipy.sparse.vstack or hstack, 分别。在 SciPy 0.12 中reshape or set_shape方法还没有实施。

SciPy 0.12 中是否有一些稳定的良好实践来重塑稀疏矩阵?最好能进行一些时间比较。


我不知道任何已建立的良好实践,所以这里有一个相当直接的 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

Example:

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]])

现在,我确信这里有几个定期贡献者可以想出更好的东西(更快,内存效率更高,填充更少......:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有效地重塑稀疏矩阵,Python,SciPy 0.12 的相关文章

随机推荐