Skip to content
Advertisement

Create a callable function depending on one free parameter from an existing function with many parameters in python

The following is a code in matlab:

costFunc = @(p) nnCostFunction(p, input_layer_size, hidden_layer_size, ...
                               num_labels, X, y, lmbd);

it takes the function nnCostFunction, gives it all parameters except p, and turn it into a callable that depends on p.

i.e. you can either call the full function:

result = nnCostFunction(p, input_layer_size, hidden_layer_size,num_labels, X, y, lmbd)

or call the new function:

result = costFunction(p)

Is there any way to make something similar in Python?

Advertisement

Answer

You can use functools.partial:

from functools import partial

costFunc = partial(nnCostFunction, input_layer_size, hidden_layer_size, ...
                           num_labels, X, y, lmbd)

Then call it with just p:

costFunc(p)

Note, however, that p will be passed as the last argument, if you want it to be the first (or somewhere in the middle), you should wrap it in another function:

def costFunc(p):
    return nnCostFunction(p, input_layer_size, hidden_layer_size, ...
                               num_labels, X, y, lmbd)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement