1
\$\begingroup\$

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
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Mar 21, 2016 at 12:06
\$\endgroup\$
2
  • \$\begingroup\$ Ah, I see. Emphasis on didn't. Defining a function is just a shortcut anyway. First, you define a_vector as whatever is passed in, in this case a_set[x]. Next, you define denom. Next, you define logit. Next, you use logit elsewhere, in this case softmax_set[x] = logit. \$\endgroup\$ Commented Mar 21, 2016 at 12:46
  • 2
    \$\begingroup\$ Why do you have/want to pack them into a single function? Following the Zen of Python, your solution looks perfectly fine. \$\endgroup\$ Commented Mar 21, 2016 at 16:44

1 Answer 1

1
\$\begingroup\$

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)
answered Mar 22, 2016 at 7:25
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.