I have a function:
cost(X, model, reg = 1e-3, sparse)
And I need to pass this function to another one under the form:
f(X, model) f(X, model, reg = reg)
I am using lambda to do this:
f = lambda X, model: cost(X, model, sparse = np.random.rand(10,10))
And python complains that lambda got an unexpected argument reg. How do I do this correctly?
If I do the other way:
f = lambda X, model, reg: cost(X, model, reg = reg, sparse = np.random.rand(10,10))
Then it's not working in the first case.
Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.
In Kotlin, the lambda expression contains optional part except code_body.
You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.
A Lambda Function in Python programming is an anonymous function or a function having no name. It is a small and restricted function having no more than one line. Just like a normal function, a Lambda function can have multiple arguments with one expression.
Lambda's take the same signature as regular functions, and you can give reg
a default:
f = lambda X, model, reg=1e3: cost(X, model, reg=reg, sparse=np.random.rand(10,10))
What default you give it depends on what default the cost
function has assigned to that same parameter. These defaults are stored on that function in the cost.__defaults__
structure, matching the argument names. It is perhaps easiest to use the inspect.getargspec()
function to introspect that info:
from inspect import getargspec spec = getargspec(cost) cost_defaults = dict(zip(spec.args[-len(defaults:], spec.defaults)) f = lambda X, model, reg=cost_defaults['reg']: cost(X, model, reg=reg, sparse=np.random.rand(10,10))
Alternatively, you could just pass on any extra keyword argument:
f = lambda X, model, **kw: cost(X, model, sparse=np.random.rand(10,10), **kw)
have you tried something like
f = lambda X, model, **kw: cost(X, model, sparse = np.random.rand(10,10), **kw)
then reg
(and any other named argument you want to pass through (other than sparse)) should work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With