I've had to write two different functions (shown below), but I want to combine the two functions into one. Is there a way to do this?
softmax_a_set()
takes a list of numpy arrays, applies softmax()
to each individual numpy array, and then returns a list of processed numpy arrays.
def softmax(a_vector):
"""Compute a logit for a vector."""
denom = sum(numpy.exp(a_vector))
logit = numpy.exp(a_vector)/denom
return logit
def softmax_a_set(a_set):
"""computes logits for all vectors in a set"""
softmax_set = numpy.zeros(a_set.shape)
for x in range(0, len(a_set)):
softmax_set[x] = softmax(a_set[x])
return softmax_set
1 Answer 1
Why do you want to combine them into two functions? It’s possible, but I don’t think it would be an improvement. They’re two fairly distinct functions, and cramming the code for both into a single function would make the code less readable.
If you really need a single function that handles both, you could do something like:
def softmax(a):
if isinstance(a, vector):
return softmax_a_vector(a)
elif isinstance(a, set):
return softmax_a_set(a)
which gets what you want, but you keep the nice separation of code into distinct functions.
One other minor thing: you can improve the for loop in softmax_a_set
with enumerate:
for idx, a_vector in enumerate(a_set):
softmax_set[idx] = softmax(a_vector)
a_vector
as whatever is passed in, in this casea_set[x]
. Next, you definedenom
. Next, you definelogit
. Next, you uselogit
elsewhere, in this casesoftmax_set[x] = logit
. \$\endgroup\$