加载中...
非线性规划
发表于:2021-11-08 | 分类: 机器学习课程(魏)

image-20211208163755018

1
2
3
4
5
6
7
8
9
10
11
12
13
def minimize(fun: Callable,
x0: ndarray,
args: Union[Iterable, tuple, None] = (),
method: Union[str, Callable, None] = None,
jac: Union[Callable, str, bool, None] = None,
hess: str = None,
hessp: Optional[Callable] = None,
bounds: Union[Iterable, Bounds, None] = None,
constraints: Optional[dict] = (),
tol: Optional[float] = None,
callback: Optional[Callable] = None,
options: Optional[dict] = None) -> Any
#Minimization of scalar function of one or more variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 # 不等约束

# 边界约束,都大于零
b = (0.0, None)
bnds = (b, b ,b)

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 = ([0, 0, 0])
#使用函数minimize求解最小值,传入参数:objective目标函数,x0初始值,method使用QP问题解决方法,bounds取值范围,constraints约束套件
solution = minimize(objective, x0, method='SLSQP', bounds=bnds, constraints=cons)
x = solution.x
print(solution)
print('目标值: ' + str(objective(x)))
print('答案为')
print('x1 = ' + str(x[0]))
print('x2 = ' + str(x[1]))
     fun: 10.651091840572583
     jac: array([1.10433471, 2.40651834, 1.89564812])
 message: 'Optimization terminated successfully'
    nfev: 71
     nit: 15
    njev: 15
  status: 0
 success: True
       x: array([0.55216734, 1.20325918, 0.94782404])
目标值: 10.651091840572583
答案为
x1 = 0.5521673412903173
x2 = 1.203259181851855
1

上一篇:
随机森林
下一篇:
基于支持向量机的分类预测
本文目录
本文目录