以下是我尝试计算softmax的小代码。它适用于单个阵列。但是随着数量的增加(例如1000等),它会爆炸
import numpy as np
def softmax(x):
print (x.shape)
softmax1 = np.exp(x)/np.sum(np.exp(x))
return softmax1
def test_softmax():
print "Running your code"
#print softmax(np.array([1,2]))
test1 = softmax(np.array([1,2]))
ans1 = np.array([0.26894142, 0.73105858])
assert np.allclose(test1, ans1, rtol=1e-05, atol=1e-06)
print ("Softmax values %s" % test1)
test2 = softmax(np.array([[1001,1002],[3,4]]))
print test2
ans2 = np.array([
[0.26894142, 0.73105858],
[0.26894142, 0.73105858]])
assert np.allclose(test2, ans2, rtol=1e-05, atol=1e-06)
if __name__ == "__main__":
test_softmax()
Run Code Online (Sandbox Code Playgroud)
我收到一个错误RuntimeWarning:exp遇到溢出运行您的代码softmax1 = np.exp(x)/np.sum(np.exp(x))