Below is a small code I am trying to calculate the softmax. It works well for a single array. But with a larger number like 1000 etc, it blows up
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()
I get an error RuntimeWarning: overflow encountered in exp Running your code softmax1 = np.exp(x)/np.sum(np.exp(x))