简体   繁体   English

FMIN_COBYLA 上的约束函数(scipy 优化)

[英]Constraint functions on FMIN_COBYLA (scipy optimize)

I'm on Scipy Optimize, using the fmin_cobyla function.我在 Scipy Optimize 上,使用 fmin_cobyla 函数。 I've struggled to write constraint functions that:我一直在努力编写约束函数:

  1. make sure all items sum up to 1确保所有项目总和为 1
  2. make sure all items >= 0确保所有项目 >= 0

Does anyone have insight?有没有人有洞察力? For fmin_slsqp, for example, I had a function:例如,对于 fmin_slsqp,我有一个函数:

def w_constraint(w, v, x0, x1):
    return np.sum(w) - 1

As well as bounds in the function.以及函数中的边界。

But these don't work on cobyla.但这些对 cobyla 不起作用。

Formulate your equality as pair of inequalities.将你的等式表述为一对不等式。 Meaning:意义:

  • x == y becomes: x == y变为:
    • x >= y
    • x <= y = -x >= -y x <= y = -x >= -y

Of course this may introduce numerical troubles (hurting many kinds of solvers), but i saw this in multiple implementations of COBYLA-interfaces (with equality-constraint support implemented like that).当然,这可能会引入数值问题(伤害多种求解器),但我在 COBYLA 接口的多种实现中看到了这一点(具有像那样实现的等式约束支持)。

A comment from the documentation of NLopt :来自NLopt文档的评论

(The underlying COBYLA code only supports inequality constraints. Equality constraints are automatically transformed into pairs of inequality constraints, which in the case of this algorithm seems not to cause problems.) (底层的 COBYLA 代码仅支持不等式约束。等式约束会自动转换为不等式约束对,在此算法的情况下,这似乎不会引起问题。)

For Scipy.optimize.minimize function, the following should work:对于 Scipy.optimize.minimize 函数,以下应该有效:

def constraint_func(x_in):
    constraints_list = []
    constraints_list.append({'type': 'ineq', 'fun': lambda x: np.sum(x)-1})
    constraints_list.append({'type': 'ineq', 'fun': lambda x: -np.sum(x)+1})
    for i in range(len(x_in)):
        constraints_list.append({'type': 'ineq', 'fun': lambda x: x[i]})
    return constraints_list

constraints = constraint_func(x0)

res = scipy.optimize.minimize(fun, x0, method='COBYLA', constraints= constraints)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM