In [4]:
import numpy as np
def softmax(x):
x = np.asarray(x)
"""Compute softmax values for each sets of scores in x."""
if len(x.shape)>1:
x_t = np.transpose(x)
out = None
for k in range(x_t.shape[0]):
d = np.sum([np.exp(i) for i in x_t[k]])
res = np.asarray([np.exp(j)/d for j in x_t[k]])
if out==None:
out = res
else:
out=np.vstack((out,res))
return np.transpose(out)
else:
d = np.sum([np.exp(i) for i in x])
return np.asarray([np.exp(j)/d for j in x])
In [6]:
softmax([[1,2,3],[1,2,3]]
)
Out[6]:
In [ ]: