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
  • \$\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\$
    – zondo
    Mar 21 '16 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\$
    – AlexV
    Mar 21 '16 at 16:44

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.