2016-07-22 12 views
3

私はscipy.sparse.csr_matrixで予期せぬ動作を発見しましたが、これは私のバグです。誰もこれが正常ではないことを確認できますか?私は疎な構造の専門家ではないので、適切な使用法を誤解している可能性があります。一方Scipy sparse csr matrixが0.0/1.0で返される

>>> import scipy.sparse 
>>> a=scipy.sparse.csr_matrix((1,1)) 
>>> b=scipy.sparse.csr_matrix((1,1)) 
>>> b[0,0]=1 
/home/marco/anaconda3/envs/py35/lib/python3.5/site-packages/scipy/sparse/compressed.py:730: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient. 
    SparseEfficiencyWarning) 
>>> a/b 
matrix([[ nan]]) 

、適切にこのハンドルnumpyの:スパースマトリックス/スパース行列について

>>> import numpy as np 
>>> a=np.zeros((1,1)) 
>>> b=np.ones((1,1)) 
>>> a/b 
array([[ 0.]]) 

おかげ

+1

'(a/b).toarray()'を試しましたか? –

+0

私にはバグのようです。 –

+0

'(a/b).tolist()'は[[nan]]を返します。 'a/b'は型の行列なので、' toarray'や 'todense'はありません。 – marcotama

答えて

1

scipyのダウンロード/疎/ compressed.py

if np.issubdtype(r.dtype, np.inexact): 
     # Eldiv leaves entries outside the combined sparsity 
     # pattern empty, so they must be filled manually. They are 
     # always nan, so that the matrix is completely full. 
     out = np.empty(self.shape, dtype=self.dtype) 
     out.fill(np.nan) 
     r = r.tocoo() 
     out[r.row, r.col] = r.data 
     out = np.matrix(out) 

このセクションでは、アクションについて説明します。

はこれまでaは0(なしスパース値)を有している場合ので、除算はnanで少し大きめの行列

In [69]: a=sparse.csr_matrix([[1.,0],[0,1]]) 
In [70]: b=sparse.csr_matrix([[1.,1],[0,1]]) 
In [72]: (a/b) 
Out[72]: 
matrix([[ 1., nan], 
     [ nan, 1.]]) 

でこれを試してみてください。それは密な行列を返して、nanを埋めています。

このコードがないと、要素除算によるスパース要素は、斜線のスロットから「空」のスパース行列を生成します。

In [73]: a._binopt(b,'_eldiv_') 
Out[73]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>' 
    with 2 stored elements in Compressed Sparse Row format> 
In [74]: a._binopt(b,'_eldiv_').A 
Out[74]: 
array([[ 1., 0.], 
     [ 0., 1.]]) 

combined sparsity patternは、分子によって決定されたように見えます

In [76]: b/a 
Out[76]: 
matrix([[ 1., inf], 
     [ nan, 1.]]) 
In [77]: b._binopt(a,'_eldiv_').A 
Out[77]: 
array([[ 1., inf], 
     [ 0., 1.]]) 

有益かもしれません。さらなるテストでは、eliminate_zerosの後にこのような外観があります。

In [138]: a1=sparse.csr_matrix(np.ones((2,2))) 
In [139]: a1 
Out[139]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>' 
    with 4 stored elements in Compressed Sparse Row format> 
In [140]: a1[0,1]=0 
In [141]: a1 
Out[141]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>' 
    with 4 stored elements in Compressed Sparse Row format> 
In [142]: a1/b 
Out[142]: 
matrix([[ 1., nan], 
     [ inf, 1.]]) 
+0

これはバグの原因です。私はここに修正を提出しました:https://github.com/scipy/scipy/pull/6405 – perimosocordiae

関連する問題