1

I try to fit data using least_squares from the scipy.optimize package. I had a working semi-solution and changed the fit function and suddenly get a

TypeError: <lambda>() takes exactly 4 arguments (5 given)

Here is the relevant part of the code:

from scipy.optimize import least_squares
def hill_fit(x,kd,start,end,n):
    return start+(end-start)*x**n/(kd**n+x**n)
fitfun_hill_err= lambda p,x,fix,err: hill_fit(x,p[0],p[1],p[2],fix[0])/err
p_init=[0.1,.1,.2] 
fix=np.array([.5] ).ravel()
least_squares(fitfun_hill_err, p_init, args=(x_data, y_data,fix,y_error),bounds=(0,500))

I want to fit the parameters in p[..], hence the lambda function.

x_data are the input data for the function, y_error is the uncertainty of the resulting data (y_data) and fix is an additional parameter passed to the function.

I had used the following function before (adjusting the parameters accordingly):

def func_fit(conc, Kd2, B, C, Rt, Lst, Kd1):
    Lt = conc
    e_tmp = e(Lt, Rt, Kd1, Lst, Kd2)
    d_tmp = d(Kd1, Kd2, Lst, Lt, Rt)
    f_tmp = f(Kd1, Kd2, Rt)
    theta_tmp = theta(d_tmp, e_tmp, f_tmp)
    FA_tmp = FA(B, C, d_tmp, e_tmp, f_tmp, theta_tmp, Kd1)

    return FA_tmp   

with e,d,f,theta and FA calling sub functions.

I had gone through the " I need to give least_squares the parameters in wrapped manner " before, that was why I introduced the lambda function, but I don't understand why it doesn't work anymore.

Please help me to understand the behavior of the least_square function and what I misunderstand here!

Thanks!

MaxS
  • 978
  • 3
  • 17
  • 34

1 Answers1

2

Follow the error message: TypeError: () takes exactly 4 arguments (5 given).

fitfun_hill_err= lambda p,x,fix,err

The lambda takes the parameters and 3 other arguments (x, fix, err). In total 4 arguments.

least_squares calls this function with the parameters and 4 other arguments (args=(x_data, y_data, fix, y_error)), in total 5 arguments.

There is a mismatch between expecting x and passing x_data and y_data.

w-m
  • 10,772
  • 1
  • 42
  • 49
  • 1
    Thanks!.In addition to anyone who reads this: I forgot to subtract y and the result of the hill_function in the lambda function! – MaxS Aug 13 '18 at 09:17