5
特定の条件を満たさない行を疎行列のためにゼロで置き換える最善の方法は何ですか?例えば、(私は普通、例示のためにアレイを使用):特定の条件を満たすscipy.sparse行列の行を0に設定する
a = np.array([[0,0,0,1,1],
[1,2,0,0,0],
[6,7,4,1,0], # sum > 10
[0,1,1,0,1],
[7,3,2,2,8], # sum > 10
[0,1,0,1,2]])
I置換するIは、その和ゼロの行と10以上であるすべての行を置換する
を[2]、[ 4]ゼロで、私の出力は次のようになりますので:
array([[0, 0, 0, 1, 1],
[1, 2, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 0, 1],
[0, 0, 0, 0, 0],
[0, 1, 0, 1, 2]])
これは、密行列のためにかなり単純です:
row_sum = a.sum(axis=1)
to_keep = row_sum >= 10
a[to_keep] = np.zeros(a.shape[1])
私がしようとすると、0
しかし、:
s = sparse.csr_matrix(a)
s[to_keep, :] = np.zeros(a.shape[1])
私はこのエラーを取得する:
raise NotImplementedError("Fancy indexing in assignment not "
NotImplementedError: Fancy indexing in assignment not supported for csr matrices.
そこで、私は、スパース行列の異なるソリューションを必要としています。私はこの思い付いた:
def zero_out_unfit_rows(s_mat, limit_row_sum):
row_sum = s_mat.sum(axis=1).T.A[0]
to_keep = row_sum <= limit_row_sum
to_keep = to_keep.astype('int8')
temp_diag = get_sparse_diag_mat(to_keep)
return temp_diag * s_mat
def get_sparse_diag_mat(my_diag):
N = len(my_diag)
my_diags = my_diag[np.newaxis, :]
return sparse.dia_matrix((my_diags, [0]), shape=(N,N))
これは、我々は、ゼロに恒等行列の対角の2番目と4番目の要素を設定した場合、その後プリマルチ行列の行がゼロに設定されているという事実に依存しています。
しかし、私はより良い、より多くの視差のある解決策があると感じます。より良い解決策はありますか?