[英]How to apply a natural logarithm to a matrix and obtain zero for when the matrix entry is zero
在 Python 我有一個帶有一些零值的矩陣,當矩陣條目為零時,如何應用自然對數並獲得零? 我正在使用 numpy.log(matrix) 來應用自然對數 function,但是當矩陣條目等於零時我得到 nan,我希望它為零
你可以這樣做:
arr = numpy.nan_to_num(numpy.log(matrix))
nan_to_num 的行為將所有 NaN 替換為零。
您可以在這里找到更多信息:
另一種選擇是將掩碼傳遞給 np.log function 的where=
參數。
您可以使用 np.where。 seterr 是關閉警告。
在:
np.seterr(divide = 'ignore')
matrix = np.array([[10,0,5], [0,10,12]])
np.where(matrix == 0, 0, np.log(matrix))
出去:
array([[2.30258509, 0. , 1.60943791],
[0. , 2.30258509, 2.48490665]])
np.log
是一個帶有where
參數的ufunc
。 這告訴它x
的哪些元素將用於計算。 rest 被跳過。 這最好與out
參數一起使用,如下所示:
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. ])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.