• 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

    • fun:需要被最小化的目标函数(objective function)

    • x0:初始猜想值,形状(n, )

      • 大小为 (n,) 的实数元素数组,其中 “n” 是自变量的数量。
    • args:tuple元组,可选的 Optional

      • 传递给目标函数及其导数(fun、jac 和 hess 函数)的额外参数。
    • method : str or callable, 可选的
      求解器的类型,应该从下面选取一种
      如果未给出,则选择 BFGS、L-BFGS-B、SLSQP 之一,具体取决于问题是否有约束或界限。

            - 'Nelder-Mead' :ref:`(see here) `
            - 'Powell'      :ref:`(see here) `
            - 'CG'          :ref:`(see here) `
            - 'BFGS'        :ref:`(see here) `
            - 'Newton-CG'   :ref:`(see here) `
            - 'L-BFGS-B'    :ref:`(see here) `
            - 'TNC'         :ref:`(see here) `
            - 'COBYLA'      :ref:`(see here) `
            - 'SLSQP'       :ref:`(see here) `
            - 'trust-constr':ref:`(see here) `
            - 'dogleg'      :ref:`(see here) `
            - 'trust-ncg'   :ref:`(see here) `
            - 'trust-exact' :ref:`(see here) `
            - 'trust-krylov' :ref:`(see here) `
            - custom - a callable object (added in version 0.14.0),
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
    • jac: {callable, ‘2-point’, ‘3-point’, ‘cs’, bool}, optional ,目标函数的雅可比矩阵。

    • bounds:可选项,变量的边界(仅适用于L-BFGS-B,TNC和SLSQP)。以(min,max)对的形式定义 x 中每个元素的边界。如果某个参数在 min 或者 max 的一个方向上没有边界,则用 None 标识。如(None, max)

    • constraints:约束条件(只对 COBYLA 和 SLSQP)。

    • bounds:可选项,变量的边界(仅适用于L-BFGS-B,TNC和SLSQP)。以(min,max)对的形式定义 x 中每个元素的边界。如果某个参数在 min 或者 max 的一个方向上没有边界,则用 None 标识。如(None, max)

    • constraints:约束条件(只对 COBYLA 和 SLSQP)。

    2. Returns

    • res:优化结果
      • 优化结果表示为“OptimizeResult”对象。
      • 重要的属性是:x 解决方案数组,success 一个布尔标志,指示优化器是否成功退出,message 描述终止原因。 有关其他属性的描述,请参阅 OptimizeResult

    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 解决方案数组
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    执行结果:

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

    2)有约束求极值

    例2-1 计算 (2+x1)/(1+x2) - 3x1+4x3 的最小值, 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)
    
    • 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

    执行结果:

    • 0.773684210526435
    • True
    • [0.9 0.9 0.1]

    例2-2 解决以下优化问题
    m i n i m i z e x [ 0 ] , x [ 1 ] l o g 2 ( 1 + x [ 0 ] × 2 3 + l o g 2 x [ 1 ] × 3 4 ) minimize_{x[0],x[1]}log_2(1+\frac{x[0]\times2}{3}+log_2\frac{x[1]\times3}{4}) minimizex[0],x[1]log2(1+3x[0]×2+log24x[1]×3)
    s . t . s.t. s.t.
    l o g 2 ( 1 + x [ 0 ] × 2 5 ) ≥ 5 log_2(1+\frac{x[0]\times2}{5})\geq5 log2(1+5x[0]×2)5
    l o g 2 ( 1 + x [ 0 ] × 6 4 ) ) ≥ 5 log_2(1+\frac{x[0]\times6}{4}))\geq5 log2(1+4x[0]×6))5

    # 目标函数
    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
    • 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

    输出结果:

    • 11.329796332293162
    • True
    • [77.5 20.66666658]

    参考资料

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

  • 相关阅读:
    一个Python中优雅的数据分块方法
    CSS的元素显示模式和CSS的背景
    【JavaWeb】
    webpack
    9.14 c++基础
    最新最全面的Spring详解(一)——Spring概述与IOC容器
    一文学会Intellij IDEA的Debug功能
    Java回顾-String/StringBuilder/StringBuffer
    FFmpeg源码:ff_h2645_extract_rbsp函数分析
    Vue3 框架搭建以及使用报错
  • 原文地址:https://blog.csdn.net/weixin_46713695/article/details/126936708