I want to optimize this function:
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)
Other functions are used to guess the result and calculate the stop condition.
But when I want to pass the code like this
anw_deco(anw_no763=anwtest,
a0=a0_aphfit,
a1=a1_aphfit,
wave_full=SGLI_waveno763,
wave_opt=wave_for_opt)
It suggests me
TypeError: <lambda>() missing 2 required positional arguments: 'C1' and 'S'
What is the problem?
The function to minimize
must receive a 1-D numpy array. Try unpacking the C0,C1,S
variables inside your function:
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)
You must also pass the function object to minimize
(i.e. without arguments), like this:
res,_ = minimize(cost_func_loca,x0=np.array([1,1,0.01]),bounds=bonds, tol=1e-6, options={'maxiter': 1e3},)