python非线性规划(scipy.optimize.minimize)
# minimize函数
scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)
fun : 求最小值的目标函数
x0 : 变量的初始猜测值,如果有多个变量,需要给每个变量一个初始猜测值
method :求极值的方法
constraints : 约束条件,针对fun中为参数的部分进行约束限制
demo:
1.计算1/x + x 的最小值
from scipy.optimize import minimize
import numpy as np
# 计算 1/x + x 的最小值
def fun(x):
return 1/x[0] + x[0]
x0 = np.asarray((1))
res = minimize(fun,x0,method="SLSQP")
x = res.x
print("x:",x[0])
print(fun(x))
2.计算(2+x1)/(1+x2)-3x1+4x3的最小值,x1,x2,x3∈(0.1,0.9)
from scipy.optimize import minimize
import numpy as np
# 计算 (2+x1)/(1+x2)-3*x1+4*x3的最小值
# x1,x2,x3∈(0.1,0.9)
def fun2(x):
return (2+x[0])/(1+x[1])-3*x[0]+4*x[2]
# ineq : 表示大于等于0
# eq : 表示等于0
# x-0.1 >= 0
def constraint1(x):
return x[0]-0.1
# 0.9-x > =0
def constraint2(x):
return -(x[0]-0.9)
def constraint3(x):
return x[1]-0.1
def constraint4(x):
return -(x[1]-0.9)
def constraint5(x):
return x[2]-0.1
def constraint6(x):
return -(x[2]-0.9)
con1 = {'type':'ineq','fun':constraint1}
con2 = {'type':'ineq','fun':constraint2}
con3 = {'type':'ineq','fun':constraint3}
con4 = {'type':'ineq','fun':constraint4}
con5 = {'type':'ineq','fun':constraint5}
con6 = {'type':'ineq','fun':constraint6}
cons = ([con1,con2,con3,con4,con5,con6])
x0 = np.array([0,0,0])
res = minimize(fun2,x0,method="SLSQP",constraints=cons)
x = res.x
print("x1:",x[0])
print("x2:",x[1])
print("x3:",x[2])
print(fun2(x))
minf(x)=x1^2+x2^2+x3^2+8
x1^2-x2+x3^2>=0
x1+x2^2+x3^2<=20
-x1-x2^2+2=0
x2+2x3^2=3
x1,x2,x3>=0
from scipy import optimize as opt
import numpy as np
from scipy.optimize import minimize
# 目标函数
def objective(x):
return x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + 8
# 约束条件
def constraint1(x):
return x[0] ** 2 - x[1] + x[2] ** 2 # 不等约束
def constraint2(x):
return -(x[0] + x[1] ** 2 + x[2] ** 2 - 20) # 不等约束
def constraint3(x):
return -x[0] - x[1] ** 2 + 2
def constraint4(x):
return x[1] + 2 * x[2] ** 2 - 3 # 不等约束
con1 = {'type': 'ineq', 'fun': constraint1}
con2 = {'type': 'ineq', 'fun': constraint2}
con3 = {'type': 'eq', 'fun': constraint3}
con4 = {'type': 'eq', 'fun': constraint4}
cons = ([con1, con2, con3, con4]) # 4个约束条件
x0 = np.array([0, 0, 0])
# 计算
solution = minimize(objective, x0, method='SLSQP',constraints=cons)
x = solution.x
print('目标值: ' + str(objective(x)))
print('答案为')
print('x1 = ' + str(x[0]))
print('x2 = ' + str(x[1]))
# 输出:
# 目标值: 10.651091840572583
# 答案为
# x1 = 0.5521673412903173
# x2 = 1.203259181851855
I'm so cute. Please give me money.
- 本文链接:https://wentianhao.github.io/2020/03/31/%E9%9D%9E%E7%BA%BF%E6%80%A7%E8%A7%84%E5%88%92/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。
若没有本文 Issue,您可以使用 Comment 模版新建。