I have time varying data trace which I want to fit a function to. The inputs to the functions are lists and I want the curve_fit to optimize all values in the list to fit the curve. I have gotten so far-
from scipy.optimize import curve_fit
from matplotlib.pylab import plt
from numpy import exp
def ffunc2(x, a, b):
counter = 0
return_value = 0
while counter < len(a):
return_value += a[counter] * exp(b[counter] * x)
counter += 1
return return_value
# INITIAL DATA
x = [1, 2, 3, 5]
y = [1, 8, 81, 125]
number_variable = 2
# INTIAL GUESS
p0 = []
counter = 0
while counter < number_variable:
p0.append(0.0)
counter += 1
p, _ = curve_fit(ffunc2, x, y, p0=[0.0, 0.0])
I want to create a loop which iterates such that it gives me the best fit with maximum number of variables by minimizing the error.
I have found this discussion as well - Using scipy curve_fit for a variable number of parameters
from numpy import exp
from scipy.optimize import curve_fit
def wrapper_fit_func(x, N, *args):
a, b, c = list(args[0][:N]), list(args[0][N:2*N]), list(args[0][2*N:3*N])
return fit_func(x, a, b)
def fit_func(x, a, b):
counter = 0
return_value = 0
while counter < len(a):
return_value += a[counter] * exp(b[counter] * x)
counter += 1
return return_value
x = [1, 2, 3, 5]
y = [1, 8, 81, 125]
params_0 = [0,1.0,2.0,3.0,4.0,5.0]
popt, pcov = curve_fit(lambda x, *params_0: wrapper_fit_func(x, 3, params_0), x, y, p0=params_0)
But get an error -´´´ File "C:\python\lib\site-packages\scipy\optimize\minpack.py", line 387, in leastsq raise TypeError('Improper input: N=%s must not exceed M=%s' % (n, m)) TypeError: Improper input: N=6 must not exceed M=4 ´´´