Python 运行时警告:日志中遇到除以零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21610198/
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-18 23:15:06  来源:igfitidea点击:

RuntimeWarning: divide by zero encountered in log

pythonnumpy

提问by GeauxEric

I am using numpy.log10 to calculate the log of an array of probability values. There are some zeros in the array, and I am trying to get around it using

我正在使用 numpy.log10 来计算概率值数组的对数。数组中有一些零,我正在尝试使用

result = numpy.where(prob > 0.0000000001, numpy.log10(prob), -10)

However, RuntimeWarning: divide by zero encountered in log10still appeared and I am sure it is this line caused the warning.

但是,RuntimeWarning: divide by zero encountered in log10还是出现了,我确定是这条线引起了警告。

Although my problem is solved, I am confused why this warning appeared again and again?

虽然我的问题解决了,但我很困惑为什么这个警告一次又一次出现?

采纳答案by user2357112 supports Monica

numpy.log10(prob)calculates the base 10 logarithm for all elements of prob, even the ones that aren't selected by the where. If you want, you can fill the zeros of probwith 10**-10or some dummy value before taking the logarithm to get rid of the problem. (Make sure you don't compute prob > 0.0000000001with dummy values, though.)

numpy.log10(prob)计算 的所有元素的以 10 为底的对数prob,即使是那些未被 选择的元素where。如果你愿意,你可以在取对数之前prob10**-10或一些虚拟值填充零以解决问题。(不过,请确保您不prob > 0.0000000001使用虚拟值进行计算。)

回答by Ramon Balthazar

I solved this by finding the lowest non-zero number in the array and replacing all zeroes by a number lower than the lowest :p

我通过找到数组中最低的非零数字并将所有零替换为低于最低的数字来解决这个问题:p

Resulting in a code that would look like:

生成的代码如下所示:

def replaceZeroes(data):
  min_nonzero = np.min(data[np.nonzero(data)])
  data[data == 0] = min_nonzero
  return data

 ...

prob = replaceZeroes(prob)
result = numpy.where(prob > 0.0000000001, numpy.log10(prob), -10)

Note that all numbers get a tiny fraction added to them.

请注意,所有数字都会添加一小部分。

回答by john ktejik

You can turn it off with seterr

您可以使用seterr关闭它

numpy.seterr(divide = 'ignore') 

and back on with

然后继续

numpy.seterr(divide = 'warn') 

回答by E.Zolduoarrati

This solution worked for me, use numpy.sterrto turn warningsoff followed by where

此解决方案对我有用,numpy.sterr用于warnings关闭其次where

numpy.seterr(divide = 'ignore')
df_train['feature_log'] = np.where(df_train['feature']>0, np.log(df_train['feature']), 0)

回答by Markus Dutschke

Just use the whereargument in np.log10

只需使用中的where参数np.log10

import numpy as np
np.random.seed(0)

prob = np.random.randint(5, size=4) /4
print(prob)

result = np.where(prob > 0.0000000001, prob, -10)
# print(result)
np.log10(result, out=result, where=result > 0)
print(result)

Output

输出

[1.   0.   0.75 0.75]
[  0.         -10.          -0.12493874  -0.12493874]