スパース行列から対角要素を削除したい。行列はスパースであるため、これらの要素は一度削除すると保存しないでください。
Scipyは、対角要素の値を設定する方法を提供します:setdiag
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では、対角要素がストレージから削除されていないようです。
>>> 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行列の圧縮形式によるものですか?スパースからデンス、そして再びスパースに移行する以外に回避策はありますか?
要素を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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加