Reputation: 35
I'm trying to fit a simple exponential fit to some data using scipy curve_fit, and the result is an exponential which is many orders of magnitude too big
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import math
import numpy as np
cases_DE = [16,18,26,48,74,79,130,165,203,262,545,670,800,1040,1224,1565,1966,2745,3675,4599,5813, 7272, 9367, 12327]
def simple_DE(A,c,t):
return A*math.e**(c*t)
range_thing = np.array(range(len(cases_DE)))
popt, pcov = curve_fit(simple_DE, range_thing, cases_DE, bounds=((-np.inf, 0), (np.inf, 1)))
print(popt)
plt.scatter(range_thing, simple_DE(*popt, range_thing))
plt.scatter(range_thing, cases_DE)
print(simple_DE(*popt, 20))
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Can anyone please show me where I have gone wrong?
Upvotes: 1
Views: 135
Reputation: 36239
It seems you confused the order of parameters. The function supplied to curve_fit
should have the following signature:
It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments:
ydata = f(xdata, *params) + eps
.
So you need to change the order of arguments of your simple_DE
function:
def simple_DE(t, A, c):
...
And similarly when plotting the fit:
plt.scatter(range_thing, simple_DE(range_thing, *popt))
Upvotes: 3