我有与这个问题相同的问题,但不想只向优化问题添加一个而是几个约束。
因此,例如,我想用和小于和小于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
?