python非线性规划scipy.optimize.minimize介绍

0. 官方说明

在 python 里用非线性规划求极值,最常用的就是 scipy.optimize.minimize()。最小化一个或多个变量的标量函数。(Minimization of scalar function of one or more variables.)

scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)

在python脚本页面中,点击Ctrl+B或者Ctrl+左击,即可查看函数的定义、函数的使用案例

1. Parameters

2. Returns

3. 案例

1)无约束求极值

计算 1/x+x 的最小值

# coding=utf-8
from scipy.optimize import minimize
import numpy as np
 
#demo 1
#计算 1/x+x 的最小值
 def fun(args):
     a=args
     v=lambda x:a/x[0] +x[0]
     return v
 
 if __name__ == "__main__":
     args = (1)  #a
     x0 = np.asarray((2))  # 初始猜测值
     res = minimize(fun(args), x0, method='SLSQP')
     print(res.fun)  # 函数的最小值
     print(res.success)
     print(res.x)  # x 解决方案数组

执行结果:

2.0000000815356342 (函数的最小值)
True
[1.00028559]

2)有约束求极值

例2-1 计算 (2+x1)/(1+x2) – 3×1+4×3 的最小值, x1, x2, x3 都处于[0.1, 0.9] 区间内。

def fun(args):
    a,b,c,d = args
    v = lambda x: (a+x[0])/(b+x[1]) -c*x[0]+d*x[2]
    return v
    
def con(args):
    # 约束条件 分为eq 和ineq
    # eq表示 函数结果等于0 ; ineq 表示 表达式大于等于0  
    x1min, x1max, x2min, x2max, x3min, x3max = args
    cons = ({'type': 'ineq', 'fun': lambda x: x[0] - x1min},\
            {'type': 'ineq', 'fun': lambda x: -x[0] + x1max},\
            {'type': 'ineq', 'fun': lambda x: x[1] - x2min},\
            {'type': 'ineq', 'fun': lambda x: -x[1] + x2max},\
            {'type': 'ineq', 'fun': lambda x: x[2] - x3min},\
            {'type': 'ineq', 'fun': lambda x: -x[2] + x3max})
    return cons
 
# 定义常量值
args = (2,1,3,4)  # a,b,c,d

# 设置参数范围/约束条件
args1 = (0.1,0.9,0.1, 0.9,0.1,0.9)  # x1min, x1max, x2min, x2max
cons = con(args1)

# 设置初始猜测值  
x0 = np.asarray((0.5,0.5,0.5))

res = minimize(fun(args), x0, method='SLSQP',constraints=cons)
print(res.fun)
print(res.success)
print(res.x)

执行结果:

例2-2 解决以下优化问题
python非线性规划scipy.optimize.minimize介绍
python非线性规划scipy.optimize.minimize介绍
python非线性规划scipy.optimize.minimize介绍
python非线性规划scipy.optimize.minimize介绍

# 目标函数
def fun(a,b,c,d):
    def v(x):
        return np.log2(1+x[0]*a/b)+np.log2(1+x[1]*c/d)
    return v
    
#限制条件函数
def con(a,b,i):
    def v(x):
        return np.log2(1 + x[i] * a / b)-5
    return v

# 定义常量值
args = [2, 1, 3, 4]  # a,b,c,d
args1 = [2, 5, 6, 4] 

# 设置初始猜测值
x0 = np.asarray((0.5, 0.5))

#设置限制条件
cons = ({'type': 'ineq', 'fun': con(args1[0],args1[1],0)},
        {'type': 'ineq', 'fun': con(args1[2],args1[3],1)},
        )

res = minimize(fun(args[0], args[1], args[2], args[3]), x0, constraints=cons)
print(res.fun)
print(res.success)
print(res.x)

输出结果:

参考资料

[1] 官网资料 2022.9.19
[2] 非线性规划(scipy.optimize.minimize);

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年3月11日
下一篇 2023年3月11日

相关推荐