2016-11-23 16 views
2

スパース行列から対角要素を削除します。行列が疎なので、これらの要素は一度削除すると保存しないでください。 setdiagscipyのスパース行列から対角要素を削除する

私はそれがlil_matrixを使用してみた場合、それが動作:

>>> a = np.ones((2,2)) 
>>> c = lil_matrix(a) 
>>> c.setdiag(0) 
>>> c 
<2x2 sparse matrix of type '<type 'numpy.float64'>' 
    with 2 stored elements in LInked List format> 

しかしcsr_matrixと、対角要素がストレージから削除されていないようです

scipyのダウンロードは、対角要素の値を設定する方法を提供します。高密度アレイを通じ

>>> b = csr_matrix(a) 
>>> b 
<2x2 sparse matrix of type '<type 'numpy.float64'>' 
    with 4 stored elements in Compressed Sparse Row format> 

>>> b.setdiag(0) 
>>> b 
<2x2 sparse matrix of type '<type 'numpy.float64'>' 
    with 4 stored elements in Compressed Sparse Row format> 

>>> b.toarray() 
array([[ 0., 1.], 
     [ 1., 0.]]) 

、我々はもちろんあります

>>> csr_matrix(b.toarray()) 
<2x2 sparse matrix of type '<type 'numpy.float64'>' 
    with 2 stored elements in Compressed Sparse Row format> 

これは意図したものですか?もしそうなら、それは圧縮された形式のcsr行列によるのでしょうか?スパースからデンスからスパースに移行する以外の方法がありますか?

答えて

2

単に要素を0に設定しても、csr行列の希薄さは変わりません。 eliminate_zerosを適用する必要があります。

In [807]: a=sparse.csr_matrix(np.ones((2,2))) 
In [808]: a 
Out[808]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>' 
    with 4 stored elements in Compressed Sparse Row format> 
In [809]: a.setdiag(0) 
In [810]: a 
Out[810]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>' 
    with 4 stored elements in Compressed Sparse Row format> 
In [811]: a.eliminate_zeros() 
In [812]: a 
Out[812]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>' 
    with 2 stored elements in Compressed Sparse Row format> 

CSR行列のスパース性を変更することは比較的高価であるため、彼らはあなたがスパース性を変更することなく、0に値を変更してみましょう。

In [829]: %%timeit a=sparse.csr_matrix(np.ones((1000,1000))) 
    ...: a.setdiag(0) 
100 loops, best of 3: 3.86 ms per loop 

In [830]: %%timeit a=sparse.csr_matrix(np.ones((1000,1000))) 
    ...: a.setdiag(0) 
    ...: a.eliminate_zeros() 
SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient. 
10 loops, best of 3: 133 ms per loop 

In [831]: %%timeit a=sparse.lil_matrix(np.ones((1000,1000))) 
    ...: a.setdiag(0) 
100 loops, best of 3: 14.1 ms per loop 
+0

正確に私が逃したもの。ありがとう! – kevad

関連する問題