
我试图在 cnn 的末尾实现 softmax,我得到的输出是 nan 和 zeros。我给 softmax 大约 10-20k 的高输入值我给了一个数组X=[2345,3456,6543,-6789,-9234]
我的功能是
def softmax (X):
B=np.exp(X)
C=np.sum(np.exp(X))
return B/C
Run Code Online (Sandbox Code Playgroud)
我收到错误 true divide and run time error
C:\Anaconda\envs\deep_learning\lib\site-packages\ipykernel_launcher.py:4: RuntimeWarning: invalid value encountered in true_divide
after removing the cwd from sys.path.
Run Code Online (Sandbox Code Playgroud)
如果应用softmax到大量数据,您可以尝试使用最大归一化:
import numpy as np
def softmax (x):
B=np.exp(x)
C=np.sum(np.exp(x))
return B/C
arr = np.array([1,2,3,4,5])
softmax(arr)
# array([0.01165623, 0.03168492, 0.08612854, 0.23412166, 0.63640865])
softmax(arr - max(arr))
# array([0.01165623, 0.03168492, 0.08612854, 0.23412166, 0.63640865])
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这不会影响 的结果softmax。将此应用到您的softmax:
def softmax(x):
B = np.exp(x - max(x))
C = np.sum(B)
return B/C
op_arr = np.array([2345,3456,6543,-6789,-9234])
softmax(op_arr)
# array([0., 0., 1., 0., 0.])
Run Code Online (Sandbox Code Playgroud)
根据softmax 函数,您需要迭代数组中的所有元素并计算每个元素的指数,然后将其除以所有元素的指数之和:
import numpy as np
a = [1,3,5]
for i in a:
print np.exp(i)/np.sum(np.exp(a))
0.015876239976466765
0.11731042782619837
0.8668133321973349
Run Code Online (Sandbox Code Playgroud)
但是,如果数字太大,指数可能会爆炸(计算机无法处理这么大的数字):
a = [2345,3456,6543]
for i in a:
print np.exp(i)/np.sum(np.exp(a))
__main__:2: RuntimeWarning: invalid value encountered in double_scalars
nan
nan
nan
Run Code Online (Sandbox Code Playgroud)
为避免这种情况,首先将数组中的最大值移为零。然后计算softmax。例如,计算[1, 3, 5]使用的 softmax[1-5, 3-5, 5-5]是[-4, -2, 0]。您也可以选择以矢量化方式实现它(正如您打算做的那样):
def softmax(x):
f = np.exp(x - np.max(x)) # shift values
return f / f.sum(axis=0)
softmax([1,3,5])
# prints: array([0.01587624, 0.11731043, 0.86681333])
softmax([2345,3456,6543,-6789,-9234])
# prints: array([0., 0., 1., 0., 0.])
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请查看cs231n课程页面。的实际问题:数字稳定性。标题正是我想要解释的。