Reputation: 1113
I was trying to write a method to compute the SoftMax activation function that takes either a matrix or an array as input and apply the softmax function to each rows.
Here is what I tried:
import numpy as np
def softmaxSingle(x):
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
def softmax( x):
if np.shape(x)[0]>1:
result=[[]]*np.shape(x)[0]
for i in range(len(result)):
result[i]=list(softmaxSingle(x[i]))
return list(result)
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
When I tried SoftMax(x)
where x
is a matrix, It runs(although I don't know if it produces correct answer). When x
is just a list, it doesn't work
Upvotes: 0
Views: 241
Reputation: 7419
You can simply make a list
to np.array
conversion:
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
if isinstance(x, list):
x = np.array(x)
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
Upvotes: 1