问题
In Python I have a Matrix with some zero values, how can I apply a natural logarithm and obtain zero for when the matrix entry is zero? I am using numpy.log(matrix) to apply the natural logarithm function, but I am getting nan when the matrix entry is equal to zero, and I would like it to be zero instead
回答1:
You can do something like this:
arr = numpy.nan_to_num(numpy.log(matrix))
The behavior of nan_to_num replaces all the NaNs by zeroes.
You can find more information here:
- https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.nan_to_num.html
Another alternative is to pass a mask to the where=
argument of the np.log function.
回答2:
You can use np.where. The seterr is to turn off the warning.
RuntimeWarning: divide by zero encountered in log
In:
np.seterr(divide = 'ignore')
matrix = np.array([[10,0,5], [0,10,12]])
np.where(matrix == 0, 0, np.log(matrix))
Out:
array([[2.30258509, 0. , 1.60943791],
[0. , 2.30258509, 2.48490665]])
回答3:
You can use numpy.log1p
it will evaluate to zero if the entry is zero (since the Log of 1 is zero) and the reverse operation is numpy.expm1
.
You can find more information in the documentation:
- Log1p
- Expm1
回答4:
np.log
is a ufunc
that takes a where
parameter. That tells it which elements of x
will be used in the calculation. The rest are skipped. This is best used with a out
parameter, as follows:
In [25]: x = np.array([1.,2,0,3,10,0])
In [26]: res = np.zeros_like(x)
In [27]: idx = x>0
In [28]: np.log(x)
/usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in log
#!/usr/bin/python3
Out[28]:
array([0. , 0.69314718, -inf, 1.09861229, 2.30258509,
-inf])
In [29]: np.log(x, out=res, where=idx)
Out[29]:
array([0. , 0.69314718, 0. , 1.09861229, 2.30258509,
0. ])
来源:https://stackoverflow.com/questions/58102864/how-to-apply-a-natural-logarithm-to-a-matrix-and-obtain-zero-for-when-the-matrix