首页 文章

优化Scipy稀疏矩阵

提问于
浏览
0

我有一个稀疏矩阵,我目前正在枚举每一行,并根据每行的信息执行一些计算 . 每行完全独立于其他行 . 但是,对于大型矩阵,此代码非常慢(大约需要2个小时),我也无法将矩阵转换为密集矩阵(限制为8GB RAM) .

import scipy.sparse
import numpy as np

def process_row(a, b):
    """
    a - contains the row indices for a sparse matrix
    b - contains the column indices for a sparse matrix

    Returns a new vector of length(a)
    """

    return

def assess(mat):
    """
    """
    mat_csr = mat.tocsr()
    nrows, ncols = mat_csr.shape
    a = np.arange(ncols, dtype=np.int32)
    b = np.empty(ncols, dtype=np.int32)
    result = []

    for i, row in enumerate(mat_csr):
        # Process one row at a time
        b.fill(i)
        result.append(process_row(b, a))

    return result

if __name__ == '__main__':
    row  = np.array([8,2,7,4])
    col  = np.array([1,3,2,1])
    data = np.array([1,1,1,1])

    mat = scipy.sparse.coo_matrix((data, (row, col)))
    print assess(mat)

我正在寻找是否有任何方法可以更好地设计它,以便它的执行速度更快 . 本质上, process_row 函数采用(row,col)索引对(来自a,b)并使用另一个稀疏矩阵进行一些数学运算并返回结果 . 我没有更改此功能的选项,但它实际上可以处理不同的行/列对,并且不限于处理来自同一行的所有内容 .

1 回答

相关问题