在scipy优化中传递args.minimize目标函数(在参数数量上出现错误) [英] 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 is NULL
Call-back cb_calcfc_in__cobyla__user__routines failed.
Traceback (most recent call last):
File "C:\..\resource_optimizer.py", line 138, in <module>
result = minimize(compute_cost, x0, args=(parameter), method='COBYLA',constraints=cons, options={'maxiter':10000,'rhobeg':20})
File "C:\Python27\lib\site-packages\scipy\optimize\_minimize.py", line 432, in minimize
return _minimize_cobyla(fun, x0, args, constraints, **options)
File "C:\Python27\lib\site-packages\scipy\optimize\cobyla.py", line 246, in _minimize_cobyla
dinfo=info)
File "C:\Python27\lib\site-packages\scipy\optimize\cobyla.py", line 238, in calcfc
f = fun(x, *args)
TypeError: compute_cost() takes exactly 2 arguments (52 given)
capi_return is NULL
Call-back cb_calcfc_in__cobyla__user__routines failed.
Traceback (most recent call last):
File "C:\..\resource_optimizer.py", line 138, in <module>
result = minimize(compute_cost, x0, args=(parameter), method='COBYLA',constraints=cons, options={'maxiter':10000,'rhobeg':20})
File "C:\Python27\lib\site-packages\scipy\optimize\_minimize.py", line 432, in minimize
return _minimize_cobyla(fun, x0, args, constraints, **options)
File "C:\Python27\lib\site-packages\scipy\optimize\cobyla.py", line 246, in _minimize_cobyla
dinfo=info)
File "C:\Python27\lib\site-packages\scipy\optimize\cobyla.py", line 238, in calcfc
f = fun(x, *args)
TypeError: compute_cost() takes exactly 2 arguments (52 given)
有人可以帮我解决这个问题吗?
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优化中传递args.minimize目标函数(在参数数量上出现错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!