在 scipy optimize.minimize 目标函数中传递 args(在参数数量上出现错误) [英] Passing args in scipy optimize.minimize objective function ( getting error on number of arguments)
问题描述
我正在尝试使用 scipy 的 optimizer.minimize 函数,但我无法找出将 args 传递给目标函数的确切方法.我有以下代码,据我说应该可以正常工作,但在参数数量上给了我错误.
I'm trying to use scipy's optimizer.minimize function but I'm unable to figure out exact way to pass args to objective function. I have following code which according to me should work fine but is giving me error on number of arguments.
result = minimize(compute_cost, x0, args=(parameter), method='COBYLA',constraints=cons, options={'maxiter':10000,'rhobeg':20})
这里是目标函数的函数签名:def compute_cost(x,parameter)
Here is the function signature to objective function: def compute_cost(x,parameter)
parameter
是一个包含 51 个键值对的字典.
parameter
is a dict that has 51 key value pair.
这会导致以下错误:
capi_return 为 NULL回调 cb_calcfc_in__cobyla__user__routines 失败.回溯(最近一次调用最后一次):文件C:..
esource_optimizer.py",第 138 行,位于 <module>结果 = 最小化(compute_cost,x0,args=(参数),method='COBYLA',constraints=cons,options={'maxiter':10000,'rhobeg':20})文件C:Python27libsite-packagesscipyoptimize\_minimize.py",第 432 行,最小化返回_minimize_cobyla(乐趣,x0,参数,约束,**选项)文件C:Python27libsite-packagesscipyoptimizecobyla.py",第 246 行,在 _minimize_cobyla信息=信息)文件C:Python27libsite-packagesscipyoptimizecobyla.py",第 238 行,在 calcfcf = 乐趣(x, *args)类型错误:compute_cost() 正好需要 2 个参数(给出 52 个)
谁能帮我解决这个问题.
Can someone help me figure this out.
推荐答案
将args=(parameter)
改为args=(parameter,)
,所以args
是一个包含单个元素的元组.
Change args=(parameter)
to args=(parameter,)
, so args
is a tuple containing a single element.
args=(parameter)
等价于 args=parameter
.当你这样做时,parameter
的每个元素都作为一个单独的参数传递给你的目标函数.
args=(parameter)
is equivalent to args=parameter
. When you do that, each element of parameter
is passed as a separate argument to your objective function.
这篇关于在 scipy optimize.minimize 目标函数中传递 args(在参数数量上出现错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!