减法中遇到的值无效 - Softmax,Python

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

我正在使用数值稳定的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函数,为什么我仍然会收到此错误,我该如何解决?谢谢!

另外,我还使用了scipy.special中给出的softmax函数,但仍然得到了同样的警告。

python scipy softmax
1个回答
0
投票

输入数组中的“inf”使得除法成为

"<non inf number>/inf"

给出“0”和

"inf/inf" 

这给了“南”

你应该从输入数组中消除“inf”。

© www.soinside.com 2019 - 2024. All rights reserved.