2017-01-19 4 views
4

私は次のように作成したスパース行列のランダム行列を持っている:私は、特定の行のセルを反復し、2つの計算を実行したいSciPyの疎な行列の行をどのように反復処理するのですか?

import numpy as np 
from scipy.sparse import rand 
foo = rand(100, 100, density=0.1, format='csr') 

row1 = foo.getrow(bar1) 
row2 = foo.getrow(bar2) 

""" 
Like the following: 
sum1 = 0 
sum2 = 0 
for each cell x in row1: 
    sum1 += x 
    if the corresponding cell (in the same column) in row2 y is non-zero: 
     sum2 += x*y 
""" 
+1

解決策または効率的なソリューションをお探しですか? – tooty44

+0

効率的なもの、私はむしろ "todense"を使いたくないでしょう。 – tyebillion

答えて

2

は、ここでのアプローチだ -

# Get first row summation by simply using sum method of sparse matrix 
sum1 = row1.sum() 

# Get the non-zero indices of first row 
idx1 = row1.indices 
data1 = row1.data # Or get sum1 here with : `data1.sum()`. 

# Get the non-zero indices of second row and corresponding data 
idx2 = row2.indices 
data2 = row2.data 

# Get mask of overlap from row1 nonzeros on row2 nonzeros. 
# Select those from data2 and sum those up for the second summation o/p. 
sum2 = data1[np.in1d(idx1,idx2)].dot(data2[np.in1d(idx2,idx1)]) 

また、comments by @user2357112で示唆されているように、matrix-multiplicationを使用して2番目の合計

sum2 = sum((row1*row2.T).data) 
+1

'sum2'計算の大部分を簡略化するために' row1 * row2.T 'を使うことができます。 – user2357112

+0

@ user2357112良いアイデア!ポストに追加されました。ありがとう! – Divakar

+0

(row1 * row2.T).data [0]で断続的なエラーが発生します。衝突がない場合、これは機能しますか?製品が0のときは? – tyebillion

関連する問題