简体   繁体   English

Python Scipy中的线性编程

[英]Linear programming in Python scipy

Objective: 目的:

maximize :((((alpha1*5000)+(alpha2*0.49431))-5000) + (((alpha1*5000)+(alpha2*0.49431))-0.49431)) 

constarints: 缺点:

mod(alpha) <= 1

Code: 码:

from scipy.optimize import minimize
alpha  = [0,0];v1 = 5000
v2 = 0.49431537320810676

def objective(alpha,sign = -1.0):
    alpha1 = alpha[0]
    alpha2 = alpha[1]
    return sign*((((alpha1*5000)+(alpha2*0.49431537320810676))-5000) + (((alpha1*5000)+(alpha2*0.49431537320810676))-0.49431537320810676)) 

def constraint1(alpha):

    return (1- abs (alpha[0]))

def constraint2(alpha):

    return (1- abs (alpha[1]))

con1 = {'type':'ineq','fun':constraint1}
con2 = {'type':'ineq','fun':constraint2}
cons = [con1,con2]

sol = minimize(objective,alpha,method='SLSQP',constraints = cons)

I have given the sign in the objective function to change the optimization to maximize. 我已经在目标函数中给出了将优化更改为最大的符号。

Solution: 解:

(sol.x)
 >>>>[ 1.00104909  0.99560862]

I have given the constraints for the alpha for it to be less than 1 , but getting the solutions more than 1. 我已经将alpha的约束条件设置为小于1,但将解决方案设置为大于1。

If you see examine the returned object sol , you will see that it has a property .message with the "value" 如果看到检查返回的对象sol ,则将看到它具有带有“值”的属性.message

'Positive directional derivative for linesearch'

which, according to this answer , implies failure to guarantee that the returned solution is optimal. 根据此答案 ,这意味着无法保证返回的解决方案是最优的。 Indeed, it violates the constraints. 确实,它违反了约束。

This behavior is probably due to the problem having a solution at the boundary of the domain of the optimization variables. 此行为可能是由于在优化变量的域边界处有解而导致的。 Indeed, CVXPY , which is a much better option for linear programming than SLSQP, returns the optimal optimization variable equal to [1,1] . 的确, CVXPY返回的最佳优化变量等于[1,1] ,它是线性编程比SLSQP更好的选择。

You may want to try scipy.optimize.linprog as a more suitable scipy function for linear programs, although I believe that it is not as fast as CVXPY (or other free LP packages). 您可能想尝试scipy.optimize.linprog作为更适合线性程序的scipy函数,尽管我认为它不如CVXPY(或其他免费LP软件包)快。

Constraints can be violated and are mainly used for relations between parameters. 约束可能会被违反,并且主要用于参数之间的关系。 What you are looking for is the keyword bounds. 您正在寻找的是关键字边界。

from scipy.optimize import minimize
alpha  = [0.,0.];v1 = 5000
v2 = 0.49431537320810676

def objective(alpha,sign = -1.0):
    alpha1 = alpha[0]
    alpha2 = alpha[1]
    return sign*(alpha1*v1+alpha2*v2-v1 + alpha1*v1+alpha2*v2-v2) 

sol = minimize(objective,alpha,method='SLSQP', bounds = ((-1,1),(-1,1)))
sol.x
>> array([ 1.,  1.])

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

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