i spotted unexpected behavior in scipy.sparse.csr_matrix, seems bug me. can confirm not normal? not expert in sparse structures may misunderstanding proper usage.
>>> 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 sparsity structure of csr_matrix expensive. lil_matrix more efficient. sparseefficiencywarning) >>> a/b matrix([[ nan]])
on other hand, numpy handles this:
>>> import numpy np >>> a=np.zeros((1,1)) >>> b=np.ones((1,1)) >>> a/b array([[ 0.]])
thanks
for sparse matrix/sparse matrix,
scipy/sparse/compressed.py
if np.issubdtype(r.dtype, np.inexact): # eldiv leaves entries outside combined sparsity # pattern empty, must filled manually. # nan, matrix 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)
the action explained in section.
try larger matrices
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.]])
so ever a
has 0s (no sparse values), division nan
. it's returning dense matrix, , filling in nan
.
without code, sparse element element division produces sparse matrix 'empty' off diagonal slots.
in [73]: a._binopt(b,'_eldiv_') out[73]: <2x2 sparse matrix of type '<class 'numpy.float64'>' 2 stored elements in compressed sparse row format> in [74]: a._binopt(b,'_eldiv_').a out[74]: array([[ 1., 0.], [ 0., 1.]])
the inverse might instructive
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.]])
it looks combined sparsity pattern
determined numerator. in further test looks after 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'>' 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'>' 4 stored elements in compressed sparse row format> in [142]: a1/b out[142]: matrix([[ 1., nan], [ inf, 1.]])
Comments
Post a Comment