The following is a code in matlab:
JavaScript
x
3
1
costFunc = @(p) nnCostFunction(p, input_layer_size, hidden_layer_size,
2
num_labels, X, y, lmbd);
3
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:
JavaScript
1
2
1
result = nnCostFunction(p, input_layer_size, hidden_layer_size,num_labels, X, y, lmbd)
2
or call the new function:
JavaScript
1
2
1
result = costFunction(p)
2
Is there any way to make something similar in Python?
Advertisement
Answer
You can use functools.partial
:
JavaScript
1
5
1
from functools import partial
2
3
costFunc = partial(nnCostFunction, input_layer_size, hidden_layer_size,
4
num_labels, X, y, lmbd)
5
Then call it with just p
:
JavaScript
1
2
1
costFunc(p)
2
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:
JavaScript
1
4
1
def costFunc(p):
2
return nnCostFunction(p, input_layer_size, hidden_layer_size,
3
num_labels, X, y, lmbd)
4