Python 的 numpy.exp 函数中的溢出错误 [英] Overflow Error in Python's numpy.exp function

查看:79
本文介绍了Python 的 numpy.exp 函数中的溢出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样使用 numpy.exp:

cc = np.array([[0.120,0.34,-1234.1]])打印 1/(1+np.exp(-cc))

但这给了我错误:

/usr/local/lib/python2.7/site-packages/ipykernel/__main__.py:5: RuntimeWarning: exp 中遇到溢出

我不明白为什么?我怎样才能解决这个问题?似乎问题出在第三个数字 (-1234.1)

解决方案

正如 fuglede 所说,这里的问题是 np.float64 无法处理像 exp(1234.1).尝试使用 np.float128 代替:

<预><代码>>>>cc = np.array([[0.120,0.34,-1234.1]], dtype=np.float128)>>>抄送数组([[ 0.12, 0.34, -1234.1]], dtype=float128)>>>1/(1 + np.exp(-cc))数组([[0.52996405, 0.58419052, 1.0893812e-536]], dtype=float128)

但是请注意,使用扩展精度存在某些怪癖.它可能不适用于 Windows;你实际上并没有得到完整的 128 位精度;每当数字通过纯 python 时,您可能会失去精度.您可以在此处阅读有关详细信息的更多信息.

对于大多数实际用途,您可能可以将 1/(1 + ) 近似为零.也就是说,只需忽略警告并继续前进.Numpy 为您处理近似值(使用 np.float64 时):

<预><代码>>>>1/(1 + np.exp(-cc))/usr/local/bin/ipython3:1: RuntimeWarning: exp 中遇到溢出#!/usr/local/bin/python3.4数组([[ 0.52996405, 0.58419052, 0. ]])

如果你想取消警告,你可以使用 scipy.special.expit,正如 WarrenWeckesser 在对问题的评论中所建议的:

<预><代码>>>>从 scipy.special 导入导出>>>出口(cc)数组([[ 0.52996405, 0.58419052, 0. ]])

I want to use numpy.exp like this:

cc = np.array([
    [0.120,0.34,-1234.1]
])

print 1/(1+np.exp(-cc))

But this gives me error:

/usr/local/lib/python2.7/site-packages/ipykernel/__main__.py:5: RuntimeWarning: overflow encountered in exp

I can't understand why? How can I fix this? It seems the problem is with third number (-1234.1)

解决方案

As fuglede says, the issue here is that np.float64 can't handle a number as large as exp(1234.1). Try using np.float128 instead:

>>> cc = np.array([[0.120,0.34,-1234.1]], dtype=np.float128)
>>> cc
array([[ 0.12,  0.34, -1234.1]], dtype=float128)
>>> 1 / (1 + np.exp(-cc))
array([[ 0.52996405,  0.58419052,  1.0893812e-536]], dtype=float128)

Note however, that there are certain quirks with using extended precision. It may not work on Windows; you don't actually get the full 128 bits of precision; and you might lose the precision whenever the number passes through pure python. You can read more about the details here.

For most practical purposes, you can probably approximate 1 / (1 + <a large number>) to zero. That is to say, just ignore the warning and move on. Numpy takes care of the approximation for you (when using np.float64):

>>> 1 / (1 + np.exp(-cc))
/usr/local/bin/ipython3:1: RuntimeWarning: overflow encountered in exp
  #!/usr/local/bin/python3.4
array([[ 0.52996405,  0.58419052,  0.        ]])

If you want to suppress the warning, you could use scipy.special.expit, as suggested by WarrenWeckesser in a comment to the question:

>>> from scipy.special import expit
>>> expit(cc)
array([[ 0.52996405,  0.58419052,  0.        ]])

这篇关于Python 的 numpy.exp 函数中的溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆