Fitting a model to data in Python
curve_fit finds the parameters, and the covariance gives their error.
import numpy as np
from scipy import optimize
def learning(x, ceiling, rate):
return ceiling * (1 - np.exp(-rate * x))
rng = np.random.default_rng(6)
days = np.arange(1, 31)
observed = learning(days, 120, 0.12) + rng.normal(0, 3, size=30)
params, covariance = optimize.curve_fit(learning, days, observed,
p0=[100.0, 0.1])
errors = np.sqrt(np.diag(covariance))
print(params.round(3), errors.round(3))
residuals = observed - learning(days, *params)
print(round(np.std(residuals), 3))
How it works
- The model's first argument is x, the rest are parameters.
p0is the starting guess; a bad one can fail to converge.- The diagonal of the covariance gives one-sigma errors.
Keywords and builtins used here
asdeflearningprintreturnround
The run, in numbers
- Lines
- 19
- Characters to type
- 487
- Tokens
- 153
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 83 seconds.
Step 3 of 4 in Optimization, step 12 of 23 in Scientific computing with SciPy.