Scipy 稀疏矩阵特殊减法

Thi*_*hiS 5 python matrix scipy sparse-matrix

我正在做一个项目,我正在做很多矩阵计算。

我正在寻找一种聪明的方法来加速我的代码。在我的项目中,我正在处理一个大小为 100Mx1M 的稀疏矩阵,其中包含大约 10M 个非零值。下面的例子只是为了说明我的观点。

假设我有:

  • 大小为 (2) 的向量 v
  • 大小为 (3) 的向量 c
  • 大小为 (2,3) 的稀疏矩阵 X

    v = np.asarray([10, 20])
    c = np.asarray([ 2,  3,  4])
    data = np.array([1, 1, 1, 1])
    row  = np.array([0, 0, 1, 1])
    col  = np.array([1, 2, 0, 2])
    X = coo_matrix((data,(row,col)), shape=(2,3))
    X.todense()
    # matrix([[0, 1, 1],
    #         [1, 0, 1]])
    
    Run Code Online (Sandbox Code Playgroud)

目前我正在做:

result = np.zeros_like(v)
d = scipy.sparse.lil_matrix((v.shape[0], v.shape[0]))
d.setdiag(v)
tmp = d * X

print tmp.todense()
#matrix([[  0.,  10.,  10.],
#        [ 20.,   0.,  20.]])
# At this point tmp is csr sparse matrix

for i in range(tmp.shape[0]):
     x_i = tmp.getrow(i)
     result += x_i.data * ( c[x_i.indices] - x_i.data)
     # I only want to do the subtraction on non-zero elements    

print result
# array([-430, -380])
Run Code Online (Sandbox Code Playgroud)

我的问题是 for 循环,尤其是减法。我想找到一种方法,通过仅减去非零元素来矢量化此操作。

直接在减法上得到稀疏矩阵的东西:

matrix([[  0.,  -7.,  -6.],
       [ -18.,   0.,  -16.]])
Run Code Online (Sandbox Code Playgroud)

有没有办法巧妙地做到这一点?