Fitting a curve by shrinking the errors
Many models are curves with a few parameters, and fitting means choosing the parameters that make the curve sit close to the data. scipy.optimize.least_squares(fun, x0) does this. You write fun(p), which returns the vector of residuals, one for each data point, where a residual is the model value minus the data value. The function then minimises the cost . It starts at your guess x0 and takes steps using the Jacobian , the table of how each residual changes when each parameter changes. A Gauss–Newton step solves , and then moves the parameters by . For a model that is linear in its parameters one such step lands on the answer. bounds=(low, high) keeps parameters in a sensible range. curve_fit is a friendlier wrapper that takes the model directly.
Squared errors let one wild point dominate: a residual of counts . A robust loss grows more slowly for large residuals. With loss='soft_l1' and f_scale=1 the penalty is , where is the squared residual. Fitting yield curves is the classic use. The Nelson–Siegel curve is . It has a long-run level , a slope , a hump and a decay length in years, and four numbers describe the whole curve. After a fit, the noise level is estimated by , with points and parameters.
soft_l1. On real data, a Nelson–Siegel curve fitted by least_squares to the ten Treasury yields of 9 October 2026 (3 months to 30 years) has a level of , a slope of (the curve rises with maturity) and years, and misses the quoted yields by only basis points on average, and by at worst. Fitting parameters to points with leaves degrees of freedom and .- Residuals in, parameters out:
fun(p)returns model minus data, andleast_squaresshrinks the sum of squares. - Robust loss for outliers:
soft_l1stops one wild point from dragging the whole curve. - Four numbers for a curve: Nelson–Siegel summarises a yield curve with a level, a slope, a hump and a decay length.
Lab · what's graded
- A slope through the origin10 pts
- A Gauss–Newton step15 pts
- A robust penalty15 pts
- The noise level after a fit10 pts
- The arguments of least_squares10 pts
- A curve-fitting workflow10 pts
- Why a robust loss30 pts