使用 where 避免运行时警告

问题描述 投票:0回答:2

我想将函数应用于

numpy
数组,该数组会经历无穷大以达到正确的值:

def relu(x):
    odds = x / (1-x)
    lnex = np.log(np.exp(odds) + 1)
    return lnex / (lnex + 1)

x = np.linspace(0,1,10)
np.where(x==1,1,relu(x))

正确计算

array([0.40938389, 0.43104202, 0.45833921, 0.49343414, 0.53940413,
       0.60030842, 0.68019731, 0.77923729, 0.88889303, 1.        ])

但也发出警告:

3478817693.py:2: RuntimeWarning: divide by zero encountered in divide
  odds = x / (1-x)
3478817693.py:4: RuntimeWarning: invalid value encountered in divide
  return lnex / (lnex + 1)

如何避免警告?

请注意,性能在这里至关重要,因此我宁愿避免创建中间数组。

python numpy floating-point
2个回答
1
投票

另一种可能的解决方案,基于

np.divide
,以避免被零除。该解决方案的灵感来自@hpaulj 的评论。

def relu(x):
    odds = np.divide(x, 1-x, out=np.zeros_like(x), where=x!=1)
    lnex = np.log(np.exp(odds) + 1)
    return lnex / (lnex + 1)

x = np.linspace(0,1,10)
np.where(x==1,1,relu(x))

输出:

array([0.40938389, 0.43104202, 0.45833921, 0.49343414, 0.53940413,
       0.60030842, 0.68019731, 0.77923729, 0.88889303, 1.        ])

0
投票

一种方法是使用 np.setter()

对于您的代码,您可以执行以下操作:

np.seterr(divide='ignore',invalid='ignore')

#输出

{'divide': 'ignore', 'over': 'warn', 'under': 'ignore', 'invalid': 'ignore'}  # this shows what type of runtime warnings are ignored.

您的代码

def relu(x):
    odds = x / (1-x)
    lnex = np.log(np.exp(odds) + 1)
    return lnex / (lnex + 1)

x = np.linspace(0,1,10)
np.where(x==1,1,relu(x))

#输出

array([0.40938389, 0.43104202, 0.45833921, 0.49343414, 0.53940413,
       0.60030842, 0.68019731, 0.77923729, 0.88889303, 1.        ])


这篇文章讨论了处理 numpy 中被零除错误的其他方法。

我给你一个简单的例子:

x=np.linspace(0,1,10)
array([0.        , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
       0.55555556, 0.66666667, 0.77777778, 0.88888889, 1.        ])

如果你这样做:

odds = x / (1-x)

你将会得到:

RuntimeWarning: divide by zero encountered in divide
  odds = x / (1-x)

但是,如果你将

x
定义为

x=np.linspace(0,0.99999999,10)
array([0.        , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
       0.55555555, 0.66666666, 0.77777777, 0.88888888, 0.99999999])

您不会收到任何错误

odds = x / (1-x)
© www.soinside.com 2019 - 2024. All rights reserved.