简体   繁体   English

lambda 函数中的可选参数

[英]Optional argument in lambda function

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:我正在使用 lambda 来做到这一点:

f = lambda X, model: cost(X, model, sparse = np.random.rand(10,10))

And python complains that lambda got an unexpected argument reg. python 抱怨 lambda 得到了一个意想不到的参数 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.那么它在第一种情况下不起作用。

Lambda's take the same signature as regular functions, and you can give reg a default: Lambda 的签名与常规函数相同,您可以给reg一个默认值:

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.你给它的默认值取决于cost函数分配给相同参数的默认值。 These defaults are stored on that function in the cost.__defaults__ structure, matching the argument names.这些默认值存储在该函数的cost.__defaults__结构中,与参数名称匹配。 It is perhaps easiest to use the inspect.getargspec() function to introspect that info:使用inspect.getargspec()函数来检查该信息可能是最简单的:

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.然后reg (以及您想要传递的任何其他命名参数(稀疏除外))应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM