Python數(shù)學(xué)建模系列(三):規(guī)劃問題之非線性規(guī)劃
非線性規(guī)劃
非線性規(guī)劃可以簡單分兩種,目標函數(shù)為凸函數(shù)or非凸函數(shù)
凸函數(shù)的非線性規(guī)劃,比如,有很多常用庫完成,比如cvxpy
非凸函數(shù)的非線性規(guī)劃(求極值),可以嘗試以下方法:
純數(shù)學(xué)方法,求導(dǎo)求極值 神經(jīng)網(wǎng)絡(luò)、深度學(xué)習(xí)(反向傳播算法中鏈式求導(dǎo)過程) scipy. optimize. minimize
scipy.optimize.minimize(fun,x0,args=(),method=None,jac=None,hess=None,hessp=None,bounds= None,constaints=() , tol= None,Callback= None, options=None)
fun:求最小值的目標函數(shù)
args:常數(shù)值
constraints :約束條件
method:求極值方法,一 般默認。
xO:變量的初始猜測值,注意minimize是局部最優(yōu)
例題 - 1
計算1/x + x 的最小值
from scipy.optimize import minimize
import numpy as np
def fun(args):
a = args
v = lambda x:a/x[0] + x[0]
return v
args = (1)
x0 = np.asarray((2))
res = minimize(fun(args), x0, method='SLSQP')
res
運行結(jié)果

例題 - 2
計算的最小值,其中范圍在0.1 到 0.9 之間
# 運行環(huán)境 Vs Code
from scipy.optimize import minimize
import numpy as np
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):
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)
args1 = (0.1, 0.9,0.1, 0.9,0.1, 0.9)
cons = con(args1)
x0 = np.asarray((0.5,0.5,0.5))
res = minimize(fun(args), x0, method='SLSQP',constraints=cons)
res.fun,res.success,res.x,res.status
# 結(jié)果
(-0.773684210526435, True, array([0.9, 0.9, 0.1]), 0)
結(jié)語
學(xué)習(xí)來源:B站及其課堂PPT,對其中代碼進行了復(fù)現(xiàn)
鏈接:
https://www.bilibili.com/video/BV12h411d7Dm?from=search&seid=5685064698782810720
文章僅作為學(xué)習(xí)筆記,記錄從0到1的一個過程
希望對您有所幫助,如有錯誤歡迎小伙伴指正~
評論
圖片
表情
