我有与这个问题相同的问题,但不想向优化问题添加一个约束,而是添加几个约束。
例如,我希望最大化x1 + 5 * x2,其约束条件是:x1和x2之和小于5,x2小于3 (不用说,实际问题要复杂得多,不能像这个问题那样直接抛到scipy.optimize.minimize中;它只是用来说明问题……)。
我可以面对这样一个丑陋的黑客:
from scipy.optimize import differential_evolution
import numpy as np
def simple_test(x, more_constraints):
# check wether all constraints evaluate to True
if all(map(eval, more_constraints)):
return -1 * (x[0] + 5 * x[1])
# if not all constraints evaluate to True, return a positive number
return 10
bounds = [(0., 5.), (0., 5.)]
additional_constraints = ['x[0] + x[1] <= 5.', 'x[1] <= 3']
result = differential_evolution(simple_test, bounds, args=(additional_constraints, ), tol=1e-6)
print(result.x, result.fun, sum(result.x))这个会打印出来
[ 1.99999986 3. ] -16.9999998396 4.99999985882就像人们预料的那样。
是否有比使用相当“危险”的eval更好/更直接的方法来添加几个约束?
发布于 2022-03-03 17:24:52
对于问题中描述的问题有一个适当的解决方案,即用演化强制执行多个非线性约束。
正确的方法是使用scipy.optimize.NonlinearConstraint函数。
在这里,我给出了一个非平凡的例子,在由两个圆的交集定义的区域内优化经典的Rosenbrock函数。
import numpy as np
from scipy import optimize
# Rosenbrock function
def fun(x):
return 100*(x[1] - x[0]**2)**2 + (1 - x[0])**2
# Function defining the nonlinear constraints:
# 1) x^2 + (y - 3)^2 < 4
# 2) (x - 1)^2 + (y + 1)^2 < 13
def constr_fun(x):
r1 = x[0]**2 + (x[1] - 3)**2
r2 = (x[0] - 1)**2 + (x[1] + 1)**2
return r1, r2
# No lower limit on constr_fun
lb = [-np.inf, -np.inf]
# Upper limit on constr_fun
ub = [4, 13]
# Bounds are irrelevant for this problem, but are needed
# for differential_evolution to compute the starting points
bounds = [[-2.2, 1.5], [-0.5, 2.2]]
nlc = optimize.NonlinearConstraint(constr_fun, lb, ub)
sol = optimize.differential_evolution(fun, bounds, constraints=nlc)
# Accurate solution by Mathematica
true = [1.174907377273171, 1.381484428610871]
print(f"nfev = {sol.nfev}")
print(f"x = {sol.x}")
print(f"err = {sol.x - true}\n")这将使用默认参数打印以下内容:
nfev = 636
x = [1.17490808 1.38148613]
err = [7.06260962e-07 1.70116282e-06]这里是由非线性约束(绿线内阴影)定义的函数(轮廓)和可行区域的可视化。约束全局极小值用黄点表示,洋红点表示无约束全局极小值。
该约束问题在可行区域边界的(x, y) ~ (-1.2, 1.4)上存在明显的局部极小值,使得局部优化器无法收敛到全局极小值。然而,differential_evolution始终按照预期找到全局最小值。

发布于 2017-11-18 18:26:28
以下是一个例子:
additional_constraints = [lambda(x): x[0] + x[1] <= 5., lambda(x):x[1] <= 3]
def simple_test(x, more_constraints):
# check wether all constraints evaluate to True
if all(constraint(x) for constraint in more_constraints):
return -1 * (x[0] + 5 * x[1])
# if not all constraints evaluate to True, return a positive number
return 10https://stackoverflow.com/questions/47369372
复制相似问题