[英]Substitute for numpy broadcasting using scipy.sparse.csc_matrix
我的代碼中有以下表達式:
a = (b / x[:, np.newaxis]).sum(axis=1)
其中b
是形狀的ndarray (M, N)
, x
是形狀的ndarray (M,)
。 現在, b
實際上是稀疏的,所以為了提高內存效率,我想在scipy.sparse.csc_matrix
或csr_matrix
。 但是,沒有實現這種方式的廣播(即使保證分割或乘法保持稀疏性)( x
的條目非零),並引發NotImplementedError
。 是否有sparse
功能我不知道會做我想要的? ( dot()
將沿錯誤的軸相加。)
如果b
是CSC格式,則b.data
具有b
的非零條目,並且b.indices
具有每個非零條目的行索引,因此您可以將您的除法視為:
b.data /= np.take(x, b.indices)
它比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
如果你就地進行划分,你可以在上面的例子中將時間減少一半,即:
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
要實現a = (b / x[:, np.newaxis]).sum(axis=1)
,可以使用a = b.sum(axis=1).A1 / x
。 A1
屬性返回1D ndarray,因此結果是1D ndarray,而不是matrix
。 這個簡潔的表達式有效,因為您既可以按x
縮放, 也可以沿軸1求和。例如:
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])
更一般地說,如果要使用向量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]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.