python - 在日志中遇到无效值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37496299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:28:09  来源:igfitidea点击:

python - invalid value encountered in log

pythonnumpymathcross-entropy

提问by helix

I have the following expression: log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))

我有以下表达式: log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))

it is giving me the following warning:

它给了我以下警告:

RuntimeWarning: invalid value encountered in log
  log = np.sum(np.nan_to_num(-y*np.log(a+ 1e-7)-(1-y)*np.log(1-a+ 1e-7)))

I don't understand what might be the invalid value or why am I getting it. Any and every help is appreciated.

我不明白什么可能是无效值或为什么我会得到它。任何和每一个帮助表示赞赏。

NOTE: This is a cross-entropy cost function where I added 1e-7to avoid having zeros inside log. y& aare numpy arrays and numpyis imported as np.

注意:这是一个交叉熵成本函数,我在其中添加1e-7以避免日志中出现零。y&a是 numpy 数组并numpy作为np.

回答by Elad Joseph

You probably still have negative values inside the log, which gives nan with real numbers.

您可能在日志中仍然有负值,这为 nan 提供了实数。

aand yshould represent probability between 0 to 1, So you need to check why do you have smaller/larger values there. Adding 1e-7 shows there is something fishy, because np.log(0)gives -inf, which I think is the value you want.

a并且y应该代表 0 到 1 之间的概率,所以你需要检查为什么你有更小/更大的值。添加 1e-7 表明有些可疑,因为np.log(0)给出了-inf,我认为这是您想要的值。

回答by WANG.Zhongzhi

You can use math.log()replacing numpy.log(), which could raise error

您可以使用math.log()替换numpy.log(),这可能会引发错误

>>> import numpy
>>> numpy.log(0)
-inf
>>> numpy.__version__
'1.3.0'
>>> import math
>>> math.log(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error