使用 scipy.optimize 通过多个变量和边界最小化函数
Minimize a function by multiple variables and boundaries using scipy.optimize
我要优化这个功能:
def cost_func(adg_guess,wave_guess,wave_opt,C0,C1,S):
ka=0
for wave in wave_guesse:
ka=ka+(adg_guess[find(wave,wave_guess)]-C0*np.exp(-S*(wave-440))-C1)^2
return ka
from scipy.optimize import minimize
from scipy.optimize import Bounds
def anw_deco(anw_no763,a0,a1,wave_full,wave_opt):
adg380_init,aph380_init=anw_de_gues(anw_no763)
aph_gu=aph_guess(wave_full,a0,a1,aph380_init)
adg_gu=adg_guess(anw_no763,aph_gu)
cost_func_loca=lambda C0,C1,S:cost_func(C0=C0,
C1=C1,
S=S,
adg_guess=adg_gu,
wave_guess=wave_full,
wave_opt=wave_opt)
bonds=Bounds([0,0,0],[np.inf,np.inf,0.03])
res,_ = minimize(cost_func_loca(C0,C1,S),x0=np.array([1,1,0.01]),bounds=bonds, tol=1e-6, options={'maxiter': 1e3},)
C0=res[1]
C1=res[2]
S=res[3]
dlta=dta(adg_guess,S,C0,C1,wave_full)
if np.mean(dlta)<0.01:
adg_fit=C0*np.exp(-S*(wave_full-440))+C1
return anw_no763,adg_fit,S
else:
anw_deco(anw_no763-dlta)
其他函数用于猜测结果和计算停止条件
但是当我想像这样传递代码时
anw_deco(anw_no763=anwtest,
a0=a0_aphfit,
a1=a1_aphfit,
wave_full=SGLI_waveno763,
wave_opt=wave_for_opt)
它建议我
TypeError: <lambda>() missing 2 required positional arguments: 'C1' and 'S'
有什么问题?
minimize
的函数必须接收一维 numpy 数组。尝试解压函数中的 C0,C1,S
变量:
def cost_func_loca(x) =
C0,C1,S=x
return cost_func(C0=C0,
C1=C1,
S=S,
adg_guess=adg_gu,
wave_guess=wave_full,
wave_opt=wave_opt)
您还必须将函数对象传递给 minimize
(即不带参数),如下所示:
res,_ = minimize(cost_func_loca,x0=np.array([1,1,0.01]),bounds=bonds, tol=1e-6, options={'maxiter': 1e3},)
我要优化这个功能:
def cost_func(adg_guess,wave_guess,wave_opt,C0,C1,S):
ka=0
for wave in wave_guesse:
ka=ka+(adg_guess[find(wave,wave_guess)]-C0*np.exp(-S*(wave-440))-C1)^2
return ka
from scipy.optimize import minimize
from scipy.optimize import Bounds
def anw_deco(anw_no763,a0,a1,wave_full,wave_opt):
adg380_init,aph380_init=anw_de_gues(anw_no763)
aph_gu=aph_guess(wave_full,a0,a1,aph380_init)
adg_gu=adg_guess(anw_no763,aph_gu)
cost_func_loca=lambda C0,C1,S:cost_func(C0=C0,
C1=C1,
S=S,
adg_guess=adg_gu,
wave_guess=wave_full,
wave_opt=wave_opt)
bonds=Bounds([0,0,0],[np.inf,np.inf,0.03])
res,_ = minimize(cost_func_loca(C0,C1,S),x0=np.array([1,1,0.01]),bounds=bonds, tol=1e-6, options={'maxiter': 1e3},)
C0=res[1]
C1=res[2]
S=res[3]
dlta=dta(adg_guess,S,C0,C1,wave_full)
if np.mean(dlta)<0.01:
adg_fit=C0*np.exp(-S*(wave_full-440))+C1
return anw_no763,adg_fit,S
else:
anw_deco(anw_no763-dlta)
其他函数用于猜测结果和计算停止条件
但是当我想像这样传递代码时
anw_deco(anw_no763=anwtest,
a0=a0_aphfit,
a1=a1_aphfit,
wave_full=SGLI_waveno763,
wave_opt=wave_for_opt)
它建议我
TypeError: <lambda>() missing 2 required positional arguments: 'C1' and 'S'
有什么问题?
minimize
的函数必须接收一维 numpy 数组。尝试解压函数中的 C0,C1,S
变量:
def cost_func_loca(x) =
C0,C1,S=x
return cost_func(C0=C0,
C1=C1,
S=S,
adg_guess=adg_gu,
wave_guess=wave_full,
wave_opt=wave_opt)
您还必须将函数对象传递给 minimize
(即不带参数),如下所示:
res,_ = minimize(cost_func_loca,x0=np.array([1,1,0.01]),bounds=bonds, tol=1e-6, options={'maxiter': 1e3},)