scipy Python最小化函数:将附加参数传递到约束字典

von4xj4u  于 2023-06-23  发布在  Python
关注(0)|答案(1)|浏览(141)

我不知道如何通过最小化函数向约束字典传递额外的参数。我可以成功地将额外的参数传递给目标函数。
最小化函数的文档在这里:http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize
constraints参数是一个具有字段'args'的dict,其中args是一个序列。我确信这是我需要传递额外参数的地方,但我不知道语法。最接近的是下面的:

  1. from scipy.optimize import minimize
  2. def f_to_min (x, p):
  3. return (p[0]*x[0]*x[0]+p[1]*x[1]*x[1]+p[2])
  4. f_to_min([1,2],[1,1,1]) # test function to minimize
  5. p=[] # define additional args to be passed to objective function
  6. f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)}) # define constraint
  7. p0=np.array([1,1,1])
  8. minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)

我得到以下错误

  1. ---------------------------------------------------------------------------
  2. IndexError Traceback (most recent call last)
  3. <ipython-input-19-571500063c9e> in <module>()
  4. 1 p0=np.array([1,1,1])
  5. ----> 2 minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)
  6. C:\Python27\lib\site-packages\scipy\optimize\_minimize.pyc in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
  7. 356 elif meth == 'slsqp':
  8. 357 return _minimize_slsqp(fun, x0, args, jac, bounds,
  9. --> 358 constraints, **options)
  10. 359 else:
  11. 360 raise ValueError('Unknown solver %s' % method)
  12. 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)
  13. 298 # meq, mieq: number of equality and inequality constraints
  14. 299 meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['eq']]))
  15. --> 300 mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['ineq']]))
  16. 301 # m = The total number of constraints
  17. 302 m = meq + mieq
  18. <ipython-input-18-163ef1a4f6fb> in <lambda>(x, p)
  19. ----> 1 f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)})
  20. IndexError: list index out of range

我正在访问附加参数的第一个元素,所以我不应该有超出范围的错误。
如果从minimize函数中删除constraints=f_to_min_cons参数,则上面的代码可以工作。

fsi0uk1n

fsi0uk1n1#

答案很简单,就是p = []没有元素,也没有长度,所以p[0]是越界的。
下面我们设置p = [0],运行时没有错误。当然,p实际上应该是什么,不是我们可以用给定的信息来回答的。

  1. import numpy as np
  2. from scipy.optimize import minimize
  3. def f_to_min (x, p):
  4. return (p[0]*x[0]*x[0]+p[1]*x[1]*x[1]+p[2])
  5. f_to_min([1,2],[1,1,1]) # test function to minimize
  6. p=[0] # define additional args to be passed to the constraint
  7. f_to_min_cons=({'type': 'ineq', 'fun': lambda x, p : x[0]+p[0], 'args': (p,)},) # define constraint
  8. p0=np.array([1,1,1]) # args to be passed to the objective function
  9. minimize(f_to_min, [1,2], args=(p0,), method='SLSQP', constraints=f_to_min_cons)

相关问题