python - 减法中遇到无效值 - Softmax,Python
问题描述
我正在使用 softmax 的数值稳定版本:-
def softmax(arr):
print(arr)
expArr=np.exp(arr-np.max(arr))
print(expArr)
return expArr/np.sum(expArr)
它被用作:-
def feedforward(x_i,W):
...
outputLayer = softmax(np.dot(network[-1],W[-1]))
...
这个函数被迭代调用:-
for j in range(len(x)):
....
network = feedforward(x[j],weights)
....
不过,对于某些数组序列,我会收到警告:-
RuntimeWarning: invalid value encountered in subtract
expArr=np.exp(arr-np.max(arr))
在警告之前进入函数的输入(和输出)是:-
input
[-1.36678160e+211 -1.97916134e+206 -5.44472726e+204 -5.47948095e+276
-6.30134248e+251 -4.04707279e+210 7.72371508e+204 1.34861349e+268
5.47948093e+276 1.06699784e+206]
output
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
input
[-7.06701455e+257 1.47067222e+250 inf -inf
-1.13669521e+298 -6.54589076e+254 8.22221348e+250 inf
-inf -5.44761594e+251]
digit.py:22: RuntimeWarning: invalid value encountered in subtract
expArr=np.exp(arr-np.max(arr))
output
[ 0. 0. nan 0. 0. 0. 0. nan 0. 0.]
input
[nan nan nan nan nan nan nan nan nan nan]
output
[nan nan nan nan nan nan nan nan nan nan]
我想知道即使我通过引入np.max(arr)
术语稳定了softmax函数,为什么我仍然会收到这个错误,我该如何解决?谢谢!
此外,我还使用了 中给出的 softmax 函数scipy.special
,但最终还是得到了相同的警告。
解决方案
输入数组中的“inf”使除法为
"<non inf number>/inf"
给出“0”和
"inf/inf"
这给了“南”
您应从输入数组中消除“inf”。
推荐阅读
- angularjs - Angularjs UI-Grid 右键单击不再起作用?
- android - 如何使 BottomAppBar 的浮动操作按钮透明?
- python - Python Pandas 数据透视表按 match_id 分组
- asp.net - 将 HTML 转换为 PDF 并附加到电子邮件 .NET
- c# - 在 LinqPad 中定义的类型不能被 Newtonsoft Json 序列化程序反序列化
- javascript - CKEDITOR 正在覆盖样式
- python - 格式化和捕获 sys.exc_info 错误消息
- python-3.x - 运行 preprocess.py 时出错
- python - 具有 bin 和聚合的 Pandas Groupby
- javascript - 获取令牌的请求未传递到下一个获取请求,返回 401