the basic problem given these constraints (this simple example, use case follows same format can introduce more variables):
x + y = c1 c2 <= x <= c3 c4 <= y <= c5 (where cx constants, , x , y variables), solve.
easy enough scipy.optimize.linprog. i'm able technically correct result.
example. using these specific constraints:
x + y = 50 5 <= x <= 65 10 <= y <= 40 we get:
>>> res = scipy.optimize.linprog([1,1], bounds=([5, 65], [10, 40]), a_eq=[[1,1]], b_eq=[50] ) >>> res.x array([ 40., 10.]) which technically correct. notice 2nd variable @ minimum. due business reasons, prefer more "fair" each variable gets go above min if possible, more along lines of (but not same as):
array([ 25., 25.]) so i've been thinking weighting midpoints. how can use scipy.optimize.linprog api (or other scipy optimization api) modify function being minimized such give higher priorities values closer midpoint of each variable range?
please see answer draft idea how approach kinds of problems. not best way , not effective algorithm kind of problem.
the problem here is, can not express idea smooth linear target function. need kind of distance measurement, has @ least quadratic in case of smooth functions.
the following code adds l2 of x vector norm penalty. helps in case, because l2 norm quadratic in components , therefore prefers components equally small on 1 larger , 1 smaller.
from scipy.optimize import fmin_slsqp # equality constraints h(x) = 0 def h(x): return x[0] + x[1] - 50 # inequality constraints g(x) >= 0 def g(x): return [ x[0] - 5, -x[0] + 65, x[1] - 10, -x[1] + 40, ] # target functions f1 = lambda x: x[0] + x[1] f2 = lambda x: x[0] + x[1] + sum(x**2) the results:
x = fmin_slsqp(f1, (5,45), f_eqcons=h, f_ieqcons=g) print(x) outputs:
optimization terminated successfully. (exit mode 0) current function value: 50.0 iterations: 1 function evaluations: 5 gradient evaluations: 1 [ 10. 40.] and penalized version:
x = fmin_slsqp(f2, (5,45), f_eqcons=h, f_ieqcons=g) print(x) prints
optimization terminated successfully. (exit mode 0) current function value: 1300.0 iterations: 3 function evaluations: 12 gradient evaluations: 3 [ 25. 25.]
Comments
Post a Comment