Reputation: 399
I'm having some troubels fitting a curve with the scipy optimize package. My code is:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def Function_EXD_2(x, d, e):
return d*np.exp(-x/e)
x = np.array([135, 126, 120, 100, 90, 85, 80, 70, 65, 60])
y = np.array([207, 263, 401, 460, 531, 576, 1350, 2317, 2340, 2834])
popt, pcov = curve_fit(Function_EXD_2, x, y)
print(popt, pcov)
I amb getting popt = [1,1], so the optimitzation is not working. I've done the "same" in R and I'm exepcting popt = [44237.53, 22.21] aprox.
Could anyone help me with that please?
Many thanks!
Xevi
Upvotes: 0
Views: 45
Reputation: 5740
There are two problems:
0
I have flipped you data values and add bounds to the fit algorithm
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
x = np.array([135, 126, 120, 100, 90, 85, 80, 70, 65, 60])
y = np.array([207, 263, 401, 460, 531, 576, 1350, 2317, 2340, 2834])
# flip array values
x = x[::-1] - np.amin(x)
y = y[::-1]
# fit function
popt, pcov = curve_fit(func, x, y, bounds=(-10**6, 10**6))
# plot data
x_data = np.linspace(1, 80, 100)
plt.plot(x, y, '.')
plt.plot(x_data, func(x_data, popt[0], popt[1], popt[2]))
plt.show()
Output:
Upvotes: 1