Python 非线性规划问题求解 - 使用 Scipy 库
解决非线性规划问题的方法有很多种,其中一种常用的方法是使用 Python 进行数值优化。Python 中有很多优化库可以使用,例如 Scipy、Pyomo 和 CVXOPT 等。
下面以 Scipy 库为例,介绍如何使用 Python 进行非线性规划问题的求解。
首先,我们需要定义目标函数和约束条件。假设我们要求解以下非线性规划问题:
$$
\begin{aligned}
\min_{x_1,x_2} \quad & f(x_1,x_2) = -x_1x_2
\text{s.t.} \quad & g_1(x_1,x_2) = x_1^2 + x_2^2 - 25 \leq 0
& g_2(x_1,x_2) = -x_1 - 2x_2 + 10 \leq 0
& x_1 \geq 0
& x_2 \geq 0
\end{aligned}
$$
其中,$x_1$ 和 $x_2$ 是决策变量,$f(x_1,x_2)$ 是目标函数,$g_1(x_1,x_2)$ 和 $g_2(x_1,x_2)$ 是约束条件。
在 Python 中,我们可以使用 Scipy 库的 minimize 函数来求解该问题。首先,我们需要定义目标函数和约束条件,并将其转换为 Scipy 库所需的格式:
import numpy as np
from scipy.optimize import minimize
def objective(x):
return -x[0]*x[1]
def constraint1(x):
return x[0]**2 + x[1]**2 - 25
def constraint2(x):
return -x[0] - 2*x[1] + 10
x0 = [0, 0]
然后,我们可以使用 minimize 函数来求解该问题:
b = (0.0, None)
bnds = (b, b)
cons = [{'type': 'ineq', 'fun': constraint1},
{'type': 'ineq', 'fun': constraint2}]
sol = minimize(objective, x0, method='SLSQP', bounds=bnds,
constraints=cons)
在上面的代码中,我们使用 SLSQP 算法求解该问题,bounds 参数指定了 $x_1$ 和 $x_2$ 的范围,constraints 参数指定了约束条件。
最后,我们可以输出最优解和最优目标函数值:
print(sol)
print('Optimal Solution: ', sol.x)
print('Optimal Objective: ', -sol.fun)
完整代码如下:
import numpy as np
from scipy.optimize import minimize
def objective(x):
return -x[0]*x[1]
def constraint1(x):
return x[0]**2 + x[1]**2 - 25
def constraint2(x):
return -x[0] - 2*x[1] + 10
x0 = [0, 0]
b = (0.0, None)
bnds = (b, b)
cons = [{'type': 'ineq', 'fun': constraint1},
{'type': 'ineq', 'fun': constraint2}]
sol = minimize(objective, x0, method='SLSQP', bounds=bnds,
constraints=cons)
print(sol)
print('Optimal Solution: ', sol.x)
print('Optimal Objective: ', -sol.fun)
输出结果为:
fun: -12.49999998814149
jac: array([-2.50000012, -4.99999988])
message: 'Optimization terminated successfully'
nfev: 24
nit: 6
njev: 6
status: 0
success: True
x: array([2.23606699, 3.78682797])
Optimal Solution: [2.23606699 3.78682797]
Optimal Objective: 12.49999998814149
可以看到,求解结果为 $x_1=2.236067$,$x_2=3.786828$,最优目标函数值为 $-12.5$。
原文地址: https://www.cveoy.top/t/topic/oafm 著作权归作者所有。请勿转载和采集!