减法遇到无效值-Softmax,Python

时间:2019-03-17 11:08:17

标签: python scipy softmax

我使用的是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函数,但仍然收到相同的警告。

1 个答案:

答案 0 :(得分:0)

输入数组中的

“ inf”使除法成为

"<non inf number>/inf"

给出“ 0” 和

"inf/inf" 

给出“ nan”

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