curve_fit estimates parameters of f(x, a, b, ...). Nairobi rainfall in the comments is millimetres vs month index.
Goal
Fit a line to noisy y = 2.5x + 4 and print a, b.
from scipy.optimize import curve_fit
def f(x, a, b):
return a * x + b
rng = np.random.default_rng(0)
x = np.linspace(0, 10, 20)
y = 2.5 * x + 4 + rng.normal(scale=0.8, size=x.size)
popt, pcov = curve_fit(f, x, y)
print('a, b', popt.round(3))
print('stderr', np.sqrt(np.diag(pcov)).round(3))from scipy.optimize import curve_fit
def f(x, a, b):
return a * np.exp(-b * x)
x = np.linspace(0, 3, 15)
y = 10 * np.exp(-0.7 * x)
print(curve_fit(f, x, y)[0].round(3))from scipy.optimize import curve_fit
def f(x, a, b):
return a * x + b
x = np.array([1.0, 2, 3, 4])
y = np.array([80.0, 60, 110, 90]) # Nairobi-ish mm
print(curve_fit(f, x, y)[0].round(2))from scipy.optimize import curve_fit
def f(x, a, b):
return a * x + b
x = np.linspace(0, 5, 12)
y = 2 * x + 1
plt.scatter(x, y)
plt.plot(x, f(x, *curve_fit(f, x, y)[0]))
plt.show()
print('ok')