[PYTHON] Take the logarithm of the nonzero element of scipy.sparse

I did not find much even when I looked it up, so I made a note.

Reference: http://stackoverflow.com/questions/6256206/scipy-sparse-default-value

The point is that you can't do it with lil, but you can do it with coo, csr, csc.

>>> import numpy as np
>>> from scipy.sparse import lil_matrix
>>> a = lil_matrix((3,2))
>>> a[0,0] = 10
>>> a[0,1] = 3
>>> a[1,0] = 11
>>> a[1,1] = 100
>>> a[2,0] = 12
>>> a.todense()
matrix([[  10.,    3.],
        [  11.,  100.],
        [  12.,    0.]])
>>> b = a.tocsr()
>>> a.data
array([[10.0, 3.0], [11.0, 100.0], [12.0]], dtype=object)
>>> np.log(a.data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'log'
>>> b.data
array([  10.,    3.,   11.,  100.,   12.])
>>> np.log(b.data)
array([ 2.30258509,  1.09861229,  2.39789527,  4.60517019,  2.48490665])
>>> b.data = np.log(b.data)
>>> b.todense()
matrix([[ 2.30258509,  1.09861229],
        [ 2.39789527,  4.60517019],
        [ 2.48490665,  0.        ]])

Recommended Posts

Take the logarithm of the nonzero element of scipy.sparse
Take the execution log of Celery
Get the first element of queryset
Take a peek at the processing of LightGBM Tuner
Take a screenshot of the LCD with Python-LEGO Mindstorms
Take the value of SwitchBot thermo-hygrometer with Raspberry Pi
The beginning of cif2cell
the zen of Python
The story of sys.path.append ()
Revenge of the Types: Revenge of types
Get the number of occurrences for each element in the list
Get the index of each element of the confusion matrix in Python