使用scipy.sparse.csc_matrix替换numpy广播

Jua*_*uan 8 python numpy scipy sparse-matrix

我的代码中有以下表达式:

a = (b / x[:, np.newaxis]).sum(axis=1)
Run Code Online (Sandbox Code Playgroud)

在哪里b是形状的ndarray (M, N),并且x是形状的ndarray (M,).现在,b实际上是稀疏的,所以对于内存效率我想用a scipy.sparse.csc_matrix或替换csr_matrix.然而,没有实现这种方式的广播(即使保证分割或乘法保持稀疏性)(条目x非零),并且提出a NotImplementedError.有sparse没有我不知道的功能会做我想做的事情?(dot()将沿错误的轴总和.)

Jai*_*ime 7

如果b是CSC格式,则b.data具有非零条目b,并且b.indices具有每个非零条目的行索引,因此您可以将您的分区视为:

b.data /= np.take(x, b.indices)
Run Code Online (Sandbox Code Playgroud)

它比Warren优雅的解决方案更为讨厌,但在大多数情况下它可能也会更快:

b = sps.rand(1000, 1000, density=0.01, format='csc')
x = np.random.rand(1000)

def row_divide_col_reduce(b, x):
    data = b.data.copy() / np.take(x, b.indices)
    ret = sps.csc_matrix((data, b.indices.copy(), b.indptr.copy()),
                         shape=b.shape)
    return ret.sum(axis=1)

def row_divide_col_reduce_bis(b, x):
    d = sps.spdiags(1.0/x, 0, len(x), len(x))
    return (d * b).sum(axis=1)

In [2]: %timeit row_divide_col_reduce(b, x)
1000 loops, best of 3: 210 us per loop

In [3]: %timeit row_divide_col_reduce_bis(b, x)
1000 loops, best of 3: 697 us per loop

In [4]: np.allclose(row_divide_col_reduce(b, x),
   ...:             row_divide_col_reduce_bis(b, x))
Out[4]: True
Run Code Online (Sandbox Code Playgroud)

如果你就地进行划分,你可以在上面的例子中将时间减少一半,即:

def row_divide_col_reduce(b, x):
    b.data /= np.take(x, b.indices)
    return b.sum(axis=1)

In [2]: %timeit row_divide_col_reduce(b, x)
10000 loops, best of 3: 131 us per loop
Run Code Online (Sandbox Code Playgroud)


War*_*ser 6

要实现a = (b / x[:, np.newaxis]).sum(axis=1),您可以使用a = b.sum(axis=1).A1 / x.该A1属性返回1D ndarray,因此结果是1D ndarray,而不是a matrix.这个简洁的表达式有效,因为您可以沿轴1 缩放x 求和.例如:

In [190]: b
Out[190]: 
<3x3 sparse matrix of type '<type 'numpy.float64'>'
        with 5 stored elements in Compressed Sparse Row format>

In [191]: b.A
Out[191]: 
array([[ 1.,  0.,  2.],
       [ 0.,  3.,  0.],
       [ 4.,  0.,  5.]])

In [192]: x
Out[192]: array([ 2.,  3.,  4.])

In [193]: b.sum(axis=1).A1 / x
Out[193]: array([ 1.5 ,  1.  ,  2.25])
Run Code Online (Sandbox Code Playgroud)

更一般地说,如果要使用向量缩放稀疏矩阵的行x,可以b在左侧乘以包含1.0/x对角线的稀疏矩阵.该函数scipy.sparse.spdiags可用于创建这样的矩阵.例如:

In [71]: from scipy.sparse import csc_matrix, spdiags

In [72]: b = csc_matrix([[1,0,2],[0,3,0],[4,0,5]], dtype=np.float64)

In [73]: b.A
Out[73]: 
array([[ 1.,  0.,  2.],
       [ 0.,  3.,  0.],
       [ 4.,  0.,  5.]])

In [74]: x = array([2., 3., 4.])

In [75]: d = spdiags(1.0/x, 0, len(x), len(x))

In [76]: d.A
Out[76]: 
array([[ 0.5       ,  0.        ,  0.        ],
       [ 0.        ,  0.33333333,  0.        ],
       [ 0.        ,  0.        ,  0.25      ]])

In [77]: p = d * b

In [78]: p.A
Out[78]: 
array([[ 0.5 ,  0.  ,  1.  ],
       [ 0.  ,  1.  ,  0.  ],
       [ 1.  ,  0.  ,  1.25]])

In [79]: a = p.sum(axis=1)

In [80]: a
Out[80]: 
matrix([[ 1.5 ],
        [ 1.  ],
        [ 2.25]])
Run Code Online (Sandbox Code Playgroud)