Python最小化函数:向约束字典传递额外参数
我不知道怎么通过最小化函数把额外的参数传递给约束字典。我可以成功地把额外的参数传递给目标函数。
关于最小化函数的文档在这里:http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize
约束参数是一个字典,其中有一个字段叫做 'args',这个 'args' 是一个序列。我确定我需要在这里传递额外的参数,但我不知道具体的语法是什么。我目前能做到的最接近的代码如下:
from scipy.optimize import minimize
def f_to_min (x, p):
return (p[0]*x[0]*x[0]+p[1]*x[1]*x[1]+p[2])
f_to_min([1,2],[1,1,1]) # test function to minimize
p=[] # define additional args to be passed to objective function
f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)}) # define constraint
p0=np.array([1,1,1])
minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)
我遇到了以下错误:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-19-571500063c9e> in <module>()
1 p0=np.array([1,1,1])
----> 2 minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)
C:\Python27\lib\site-packages\scipy\optimize\_minimize.pyc in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
356 elif meth == 'slsqp':
357 return _minimize_slsqp(fun, x0, args, jac, bounds,
--> 358 constraints, **options)
359 else:
360 raise ValueError('Unknown solver %s' % method)
C:\Python27\lib\site-packages\scipy\optimize\slsqp.pyc in _minimize_slsqp(func, x0, args, jac, bounds, constraints, maxiter, ftol, iprint, disp, eps, **unknown_options)
298 # meq, mieq: number of equality and inequality constraints
299 meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['eq']]))
--> 300 mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['ineq']]))
301 # m = The total number of constraints
302 m = meq + mieq
<ipython-input-18-163ef1a4f6fb> in <lambda>(x, p)
----> 1 f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)})
IndexError: list index out of range
我正在访问额外参数的第一个元素,所以不应该出现超出范围的错误。
如果你从最小化函数中移除 constraints=f_to_min_cons 这个参数,那么上面的代码就能正常工作。
1 个回答
2
简单来说,p = [] 这个空列表里没有任何元素,也没有长度,所以 p[0] 是超出范围的。
而如果我们把 p 设置为 [0],那么这个代码就可以正常运行了。至于 p 应该包含什么,这个问题根据提供的信息我们无法回答。
import numpy as np
from scipy.optimize import minimize
def f_to_min (x, p):
return (p[0]*x[0]*x[0]+p[1]*x[1]*x[1]+p[2])
f_to_min([1,2],[1,1,1]) # test function to minimize
p=[0] # define additional args to be passed to the constraint
f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)},) # define constraint
p0=np.array([1,1,1]) # args to be passed to the objective function
minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)