Python:用于调用较低级函数的可选参数 [英] Python : optional arguments for function calling lower level functions

查看:177
本文介绍了Python:用于调用较低级函数的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能

def weights(vector, loss_function, clipping, max_iterations=100, tolerance=1e-5)

需要调用一个较低级别的损失函数,该函数可以是其中的任何一个,并且要在参数中传递矢量和裁剪:

which needs to call a lower level loss function which can be any of these with the vector and clipping passed in argument :

huber_loss(vector, clipping=2.38) cauchy_loss(vector, clipping=3.27) bisquare_loss(vector, clipping=1.04)

huber_loss(vector, clipping=2.38) cauchy_loss(vector, clipping=3.27) bisquare_loss(vector, clipping=1.04)

每个损失函数都有一个特殊的适当默认剪裁值,因此我们可以称它们为huber_loss(vector)或huber_loss(vector,2).

Each loss function has a special proper default clipping value so we can call them either huber_loss(vector) or huber_loss(vector,2) for example.

我希望在weights()中使裁剪参数为可选参数,而不在权重级别提供默认值,因为这将为所有损失函数提供相同的默认值,这是错误的.

I want to make the clipping parameter optional in weights() without giving a default value at weights' level because this would give the same default to all loss functions and that's wrong.

如何使裁剪参数的权重为可选,以便如果我们不给出值,则使用特定损失函数的默认值? (我知道我们可以设置默认Clipping = None并在损失函数中进行测试,如果Clipping = None,然后设置Clipping = 2.38等.但是我认为有一种更优雅的方法可以做到这一点.)

How to make the clipping parameter optional in weights so that if we don't give a value it uses the default value of the specific loss function ? (I know we can set default clipping=None and test in the loss function if clipping=None then set clipping = 2.38 etc.. but I think there's a much more elegant way to do it).

我试图通过这种方式解决问题:

I tried to solve the problem that way :

weights(vector, loss_function, max_iterations=100, tolerance=1e-5, *clipping)

但是如果我们想给裁剪指定一个特定的值而不指定max_iterations和公差,那是行不通的.

but if we want to give a specific value to clipping without specifying max_iterations and tolerance it doesn't work.

有什么主意如何以Pythonic优雅的方式解决这个问题?

Any idea how to solve this in a pythonic and elegant way ?

推荐答案

def weights(vector, loss_function, clipping=None, 
            max_iterations=100, tolerance=1e-5)

kwargs = {}
if clipping:
    kwargs['clipping'] = clipping

huber_loss(vector, **kwargs)

这篇关于Python:用于调用较低级函数的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆