我在Canopy中使用python 2.7,并且我试图通过最小化数据和模型预测之间的均方误差来拟合模型的6个参数。我使用COBYLA,因为我需要参数值的界限,而且我没有梯度。
目前,我有:
import numpy as np
import scipy.optimize as opt
def cost_func(pars,y,x):
y_hat = model_output(pars,x)
mse = np.mean((y-y_hat)**2)
return mse
def make_constraints(par_min,par_max):
cons = []
for (i,(a,b)) in enumerate(zip(par_min,par_max)):
lower = lambda x: x[i] - a
upper = lambda x: b - x[i]
cons = cons + [lower] + [upper]
return cons
def estimate_parameters(par_min, par_max,par_init,x,y):
cons = make_constraints(par_min,par_max)
opt_pars = opt.fmin_cobyla(cost_func,pars,cons,args=([y,x]))
return opt_pars
然而我收到错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-63-9e84e10303e1> in <module>()
----> 1 opt_pars = estimate_parameters(par_min,par_max,par_init,x,y)
<ipython-input-61-f38615d82ee5> in estimate_parameters(par_min,par_max,par_init,x,y)
9 cons = make_constraints(par_min,par_max)
10
---> 11 opt_pars = opt.fmin_cobyla(cost_func,par_init,cons,args=([y,x]))
12 return opt_pars
/home/luke/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/optimize/cobyla.pyc in fmin_cobyla(func, x0, cons, args, consargs, rhobeg, rhoend, iprint, maxfun, disp, catol)
169
170 sol = _minimize_cobyla(func, x0, args, constraints=con,
--> 171 **opts)
172 if iprint > 0 and not sol['success']:
173 print("COBYLA failed to find a solution: %s" % (sol.message,))
/home/luke/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/optimize/cobyla.pyc in _minimize_cobyla(fun, x0, args, constraints, rhobeg, tol, iprint, maxiter, disp, catol, **unknown_options)
244 xopt, info = _cobyla.minimize(calcfc, m=m, x=np.copy(x0), rhobeg=rhobeg,
245 rhoend=rhoend, iprint=iprint, maxfun=maxfun,
--> 246 dinfo=info)
247
248 if info[3] > catol:
/home/luke/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/scipy/optimize/cobyla.pyc in calcfc(x, con)
238 f = fun(x, *args)
239 for k, c in enumerate(constraints):
--> 240 con[k] = c['fun'](x, *c['args'])
241 return f
242
TypeError: <lambda>() takes exactly 1 argument (3 given)
这个错误对我来说并不完全清楚,但我的理解是3个参数被传递给我的约束函数。但是,我无法解决这三个论点的来源。
我已经查看过有关此问题的其他stackoverflow问题并从中获取了我可以使用的内容,但我仍然遇到此问题
Specifying constraints for fmin_cobyla in scipy
Python SciPy: optimization issue fmin_cobyla : one constraint is not respected
Python: how to create many constraints for fmin_cobyla optimization using lambda functions
答案 0 :(得分:1)
如果consargs
的参数fmin_cobyla
为None
,则约束函数也会传递*args
,其中args
是赋予{{1}的参数}}。要不向约束函数传递其他参数,请使用fmin_cobyla
。
或者,在函数consargs=()
中,更改此
make_constraints
到
lower = lambda x: x[i] - a
upper = lambda x: b - x[i]