Nonlinear least squares and curve fitting
| Problem | Minimise a sum of squares of residuals, typically to fit a model to data , and estimate the uncertainty of the fitted parameters |
| Devised by | Least squares: Adrien-Marie Legendre (1805) and Carl Friedrich Gauss (1809); Gauss-Newton: Gauss; damping: Kenneth Levenberg (1944) and Donald Marquardt (1963); the damping update used here: Hans Bruun Nielsen (1999) |
| Accuracy | Quadratic convergence for zero-residual problems, fast linear convergence for small residuals; parameter standard errors from the covariance |
| Cost | Per iteration: one Jacobian (analytic, or extra residual evaluations by differences) and an solve, with work to form |
| Read first | Newton and quasi-Newton methods: Newton, BFGS and L-BFGS, Linear least squares |
| API | LevenbergMarquardt, curve_fit, CurveFitResult |
Overview
Fitting a model to measurements is the most common optimisation problem in science. Given data , , and a model with parameters, the least-squares estimate minimises
where is the standard deviation of the noise in . If the noise is Gaussian, this is the maximum-likelihood estimate. When depends linearly on , is quadratic and the minimum comes from one linear least-squares solve; this entry is about the nonlinear case.
The sum-of-squares structure gives an approximate Hessian for free, which the Gauss-Newton
method exploits. The Levenberg-Marquardt method makes it robust by blending it with gradient
descent, and it is the standard algorithm for curve fitting: SciPy’s curve_fit, MINPACK’s
lmder, gnuplot’s fit and this library’s curve_fit all use it.
Where it is used
Fitting a nonlinear model to data is the most common optimisation task in science.
- Curve fitting. Exponential decays, spectral line shapes, growth curves and calibration functions fitted to measurements, as in
curve_fit. - Camera calibration and computer vision. Bundle adjustment and structure from motion minimise reprojection errors with Levenberg-Marquardt.
- Robotics and navigation. Estimating a pose or a map from many sensor measurements.
- Pharmacokinetics, chemistry, geophysics. Estimating rate constants and model parameters.
History
Least squares was published by Adrien-Marie Legendre in 1805, in an appendix on the orbits of comets, and by Carl Friedrich Gauss in 1809, who claimed to have used it since 1795 and justified it by the normal distribution of errors. Gauss’s most famous application was the recovery of the asteroid Ceres in 1801, from a few weeks of observations, by fitting an orbit to them. To solve the nonlinear equations he linearised them about the current estimate and solved the linear least-squares problem: the Gauss-Newton method.
Kenneth Levenberg, at the Frankford Arsenal in Philadelphia, proposed in 1944 to damp the Gauss-Newton step to keep it from overshooting. Donald Marquardt, a statistician at DuPont, rediscovered and refined the idea in 1963, scaling the damping by the diagonal of ; the resulting algorithm, distributed as a FORTRAN program, spread rapidly. Jorge Moré’s MINPACK implementation (1978) recast it as a trust-region method, and Hans Bruun Nielsen (1999) proposed the smooth damping update used here.
The idea
Gauss-Newton
could be minimised by any general method, but its special form, a sum of squares, makes a better one possible. Start by differentiating. Let be the Jacobian of the residuals, : row says how residual responds to each parameter. By the chain rule,
or in matrix form
The Hessian has two parts. The first, , involves only first derivatives of the model. The second involves second derivatives, each multiplied by a residual. That second part is small in two common situations: when the residuals are small (the model fits the data well), or when the model is nearly linear in the parameters (its second derivatives are small).
Gauss’s idea is to drop the second part. The approximate Hessian comes for free once the gradient has been computed, and it is always positive semidefinite, so it never points the step uphill. Newton’s step with this Hessian is the Gauss-Newton step,
There is a second way to arrive at the same step, which explains what it means. Linearise the residuals about the current parameters, , and minimise the length of the linearised residual, . That is a linear least-squares problem, and the equations above are its normal equations. Gauss-Newton thus solves a nonlinear fitting problem as a sequence of linear ones.
Gauss-Newton converges quadratically when the residuals at the solution are zero, and rapidly when they are small. But it has no safeguard: from a poor start the linearisation can be badly wrong and the iteration can diverge, and when is rank deficient (two parameters with the same effect on the model, say) the system has no unique solution.
The Levenberg-Marquardt method
Levenberg-Marquardt repairs both defects with one modification: it adds a positive damping term to the matrix,
The damping parameter moves the step continuously between two extremes.
- For small the added term is negligible and the step is the Gauss-Newton step: fast, but trustworthy only near the solution.
- For large the term dominates, and . Since is the gradient of , this is a short step in the (scaled) steepest descent direction: slow, but certain to reduce if short enough.
The damped matrix is also positive definite whenever , so the system can always be solved. Marquardt’s choice of , the diagonal of instead of the identity, makes the method give the same iterates if a parameter is measured in different units.
Adapting the damping. After each trial step, compare the reduction in that actually occurred with the reduction predicted by the linearised model. Their ratio measures how far the linearisation can be trusted.
- If , decreased. The step is accepted and is reduced, by the factor , moving towards Gauss-Newton. The better the agreement, the larger the reduction.
- Otherwise the step is rejected and is increased, by a factor that doubles with each consecutive failure, moving towards short gradient steps.
In effect the damping controls the radius of a trust region around the current point, within which the linear model is believed. The method behaves like gradient descent while far from the solution and like Gauss-Newton as it closes in.
Curve fitting and uncertainties
A fit is not complete without an estimate of how well the parameters are determined. Noise in the data moves the minimum of , and the parameters inherit an uncertainty from it.
Near the solution is approximately quadratic, with Hessian . A direction in parameter space along which rises steeply is well determined by the data; a direction along which it is nearly flat is poorly determined. This is why the covariance matrix of the fitted parameters is approximately the inverse of the Hessian,
provided the residuals were weighted by the true noise levels . The diagonal entries are the variances of the individual parameters, so the standard errors are ; the off-diagonal entries say how the errors of different parameters are correlated.
The quality of the fit as a whole is measured by . Each residual, being an error divided by its standard deviation, should have a square of about 1 on average, but fitting parameters uses up of the degrees of freedom. For a correct model and correct the expected value is , so the reduced chi-squared should be close to 1. A value much larger than 1 means the model does not describe the data, or the are too small; a value much smaller than 1 means the are too large.
If the noise level is unknown, this argument can be run backwards: assume the model is right and
estimate the noise from the scatter of the residuals. curve_fit (called with sigma = None)
does this by scaling by the reduced chi-squared, as SciPy does.
A Gaussian peak on a baseline, , fitted to 60 noisy points from a poor starting guess:
Figure 5.6. Fitting a Gaussian peak.
| parameter | true value | estimate | standard error | error / standard error |
|---|---|---|---|---|
| amplitude | 2 | 2.0039 | 0.0202 | +0.19 |
| centre | 4 | 4.0009 | 0.0086 | +0.11 |
| width | 0.8 | 0.7824 | 0.0100 | -1.76 |
| baseline | 0.3 | 0.3002 | 0.0092 | +0.02 |
Reduced (expected about 1 for a correct model and noise level), 11 iterations.
Every estimate lies within one standard error of the truth, as it should about two-thirds of the time.
Algorithm
Levenberg-Marquardt. Input: the residual function, optionally its Jacobian, and starting parameters .
- Initialise. Evaluate and at . Set the damping to , a small fraction of the scale of the matrix it will be added to.
- Test the gradient. If the largest component of in magnitude is tiny, stop: is a stationary point.
- Compute a trial step. Solve . If is tiny relative to , stop: the parameters have stopped changing.
- Evaluate it. Compute at (projected onto the bounds, if set), and the gain ratio : the actual reduction in divided by the reduction the linear model predicted.
- Accept or reject.
- If : move to , recompute there, and decrease . If fell by only a relatively tiny amount, stop.
- Otherwise: stay at and increase , by a factor that doubles at each consecutive rejection.
- Go to 2.
Each trial step costs one evaluation of the residuals and an solve; each accepted step also costs a Jacobian, which by forward differences is more evaluations of the residuals.
Curve fitting (curve_fit). Build the residuals ,
run the iteration above, and then compute at the solution, the standard
errors and . If no were given, use and multiply
by the reduced chi-squared.
Implementation
let diag: Vec<f64> = (0..n).map(|i| a[[i, i]].max(1e-12 * max_diag.max(1.0))).collect();
let mut damped = a.clone();
(0..n).for_each(|i| damped[[i, i]] += mu * diag[i]);
let h = match damped.solve(&(-&g)) {
Ok(h) => h,
Err(_) => {
mu *= nu;
nu *= 2.0;
continue;
}
};
let p_norm = p.iter().map(|v| v * v).sum::<f64>().sqrt();
if h.dot(&h).sqrt() <= tol * (p_norm + tol) {
converged = true;
break;
}
let mut trial: Vec<f64> = p.iter().zip(h.iter()).map(|(a, b)| a + b).collect();
self.project(&mut trial);
let step = Array1::from_shape_fn(n, |i| trial[i] - p[i]);
let r_trial = residuals(&trial);
let cost_trial = half_sum_squares(&r_trial);
// Predicted reduction of the linear model, ½ hᵀ(μ D h − g).
let predicted = 0.5 * (0..n).map(|i| step[i] * (mu * diag[i] * step[i] - g[i])).sum::<f64>();
let rho = if predicted > 0.0 { (cost - cost_trial) / predicted } else { -1.0 };
if rho > 0.0 && cost_trial.is_finite() {
let relative_drop = (cost - cost_trial) / cost.max(f64::MIN_POSITIVE);
p = trial;
r = r_trial;
cost = cost_trial;
jac = jac_at(&p, &r)?;
(a, g) = normal_equations(&jac, &r);
mu *= (1.0f64 / 3.0).max(1.0 - (2.0 * rho - 1.0).powi(3));
LevenbergMarquardt::solvetakes any residual function and an optional analytic Jacobian (forward differences otherwise), and returns the parameters, residuals, cost and the Jacobian at the solution.curve_fitbuilds the weighted residuals from a model and data, uses difference Jacobians, and returns the covariance, standard errors and chi-squared. A rank-deficient Jacobian (parameters that the data cannot separate) makes the covariance undefined and is an error.- Box bounds are enforced by projection.
In practice
//! Nonlinear least squares: fitting an exponential decay with uncertainties.
//!
//! Run with `cargo run -p lib_jsl_optimization --example optimization_least_squares`.
use lib_jsl_optimization::least_squares::{LevenbergMarquardt, curve_fit};
fn main() {
// Radioactive counts measured every 10 minutes, with their Poisson standard deviations.
let t: Vec<f64> = (0..10).map(|k| 10.0 * k as f64).collect();
let counts = [1031.0, 735.0, 589.0, 409.0, 331.0, 226.0, 187.0, 128.0, 109.0, 70.0];
let sigma: Vec<f64> = counts.iter().map(|c: &f64| c.sqrt()).collect();
// Model N(t) = N₀ e^(−t/τ).
let model = |t: f64, p: &[f64]| p[0] * (-t / p[1]).exp();
let fit = curve_fit(model, &t, &counts, Some(&sigma), vec![1000.0, 50.0], &LevenbergMarquardt::new()).unwrap();
println!("N₀ = {:.1} ± {:.1}", fit.parameters[0], fit.standard_errors[0]);
println!("τ = {:.2} ± {:.2} minutes (half-life {:.2})", fit.parameters[1], fit.standard_errors[1], fit.parameters[1] * 2f64.ln());
println!("reduced χ² = {:.2}", fit.reduced_chi_squared);
// The underlying solver takes any residual vector, here with an analytic Jacobian.
let residuals = |p: &[f64]| vec![p[0] - 1.0, 10.0 * (p[1] - p[0] * p[0])];
let jacobian = |p: &[f64]| vec![vec![1.0, 0.0], vec![-20.0 * p[0], 10.0]];
let r = LevenbergMarquardt::new().solve(residuals, Some(jacobian), vec![-1.2, 1.0]).unwrap();
println!("Rosenbrock as least squares: {:?} in {} iterations", r.parameters, r.iterations);
}
Strengths
- Fast and robust for fitting problems; only first derivatives are needed.
- Gives parameter uncertainties as a by-product.
Weaknesses
- Finds a local minimum: models with several minima (sums of exponentials or sinusoids) need good starting values.
- Converges slowly for problems with large residuals at the solution, where the dropped Hessian term matters.
- The covariance is a linearisation, unreliable for strongly nonlinear models or poorly determined parameters.
Exercises
- Show that for a linear model the Gauss-Newton method converges in one step.
- Show that the Levenberg-Marquardt step minimises subject to for some depending on .
- Fit to data both directly and by linear regression of . Why do the answers differ, and which is correct for additive Gaussian noise?
- Repeat the Gaussian-peak fit for 1000 noise realisations and check that the spread of the estimates matches the standard errors.
- Fit a sum of two Gaussians to data from a single Gaussian. What happens to the covariance?
Hints and answers
- For the Jacobian is the constant matrix , so the Gauss-Newton step solves and the quadratic objective is minimised exactly in one step.
- The constrained problem has the Lagrangian , whose stationarity condition is : the Levenberg-Marquardt equation. The radius is then .
- Regression on minimises errors in , which weights small values much more strongly and corresponds to multiplicative (log-normal) noise. For additive Gaussian noise the direct nonlinear fit is the maximum-likelihood estimate.
- The covariance of the estimates is at the solution. With 1000 realisations the sample standard deviations should agree with the standard errors to within a few per cent (about ).
- The two components are not separately identifiable (swapping them, or splitting the amplitude between them, fits equally well), so is nearly singular and the covariance has enormous, strongly correlated entries.
Further reading
- K. Levenberg, “A method for the solution of certain non-linear problems in least squares”, Quarterly of Applied Mathematics 2 (1944) 164–168.
- D. W. Marquardt, “An algorithm for least-squares estimation of nonlinear parameters”, Journal of the Society for Industrial and Applied Mathematics 11 (1963) 431–441.
- J. J. Moré, “The Levenberg-Marquardt algorithm: implementation and theory”, in Numerical Analysis, Lecture Notes in Mathematics 630, Springer, 1978, 105–116.
- K. Madsen, H. B. Nielsen and O. Tingleff, Methods for Non-Linear Least Squares Problems, 2nd ed., Technical University of Denmark, 2004.
- P. R. Bevington and D. K. Robinson, Data Reduction and Error Analysis for the Physical Sciences, 3rd ed., McGraw-Hill, 2003.