gpt4 book ai didi

python - 如何给difference_evolution添加几个约束?

转载 作者:行者123 更新时间:2023-12-01 02:26:12 24 4
gpt4 key购买 nike

我遇到了与 this question 相同的问题但不想只向优化问题添加一个而是多个约束。

所以例如我想最大化 x1 + 5 * x2,但限制为 x1x2 之和小于 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更好/更直接的方法来添加多个约束?

最佳答案

一个例子是这样的::

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 10

关于python - 如何给difference_evolution添加几个约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com