Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

13. Fit parameters and their covariance

School of Engineering, Nazarbayev University

Track: advanced  ·  Prerequisites: Chapters 11 and 12

Reading: Bevington & Robinson, ch. 6–7 · Fornasini, ch. 10.4 · Rouaud, ch. II.C–D · Deming, Statistical Adjustment of Data · York et al. (2004)

A fit is rarely the end of an analysis. The fitted parameters are fed into further formulas: a predicted value at some new xx, an intercept with an axis, an activation energy, a half-life. Parameters obtained from the same data are correlated, and by Section 12.2 any quantity computed from more than one of them needs their covariance matrix. Quoting “a±uaa \pm u_a, b±ubb \pm u_b” and nothing else discards information that the reader cannot reconstruct.

This notebook

  1. derives the parameter covariance matrix of linear least squares;

  2. shows its consequences on a classic extrapolation, the gas-thermometer estimate of absolute zero;

  3. shows how centring the data removes the correlation;

  4. examines what happens to the weights when data are transformed to make a model linear;

  5. discusses unknown error bars, and errors in both variables.

13.1 Linear least squares in matrix form

A model is linear in its parameters if it can be written as

yi=∑j=1pAij βj,ory=Aβ,y_i = \sum_{j=1}^{p} A_{ij}\,\beta_j , \qquad\text{or}\qquad \boldsymbol y = \mathsf A\boldsymbol\beta ,

where the design matrix A\mathsf A contains known functions of xx. For a straight line the columns of A\mathsf A are 1 and xix_i; for a polynomial they are 1,xi,xi2,…1, x_i, x_i^2, \dots The model need not be linear in xx.

With independent data of standard uncertainties σi\sigma_i, collect the weights in W=diag⁡(1/σi2)\mathsf W = \operatorname{diag}(1/\sigma_i^2), which is the inverse of the data covariance matrix Cy\mathsf C_y. Then

χ2(β)=(y−Aβ)T W (y−Aβ).\chi^2(\boldsymbol\beta) = (\boldsymbol y - \mathsf A\boldsymbol\beta)^{\mathsf T}\,\mathsf W\,(\boldsymbol y - \mathsf A\boldsymbol\beta) .

Setting the gradient with respect to β\boldsymbol\beta to zero gives the normal equations ATWA β=ATWy\mathsf A^{\mathsf T}\mathsf W\mathsf A\,\boldsymbol\beta = \mathsf A^{\mathsf T}\mathsf W\boldsymbol y, with solution

β^=K y,K=(ATWA)−1ATW.\hat{\boldsymbol\beta} = \mathsf K\,\boldsymbol y , \qquad \mathsf K = (\mathsf A^{\mathsf T}\mathsf W\mathsf A)^{-1}\mathsf A^{\mathsf T}\mathsf W .

The estimate is a linear function of the data, so the general propagation law Cβ=K Cy KT\mathsf C_\beta = \mathsf K\,\mathsf C_y\,\mathsf K^{\mathsf T} of Section 12.1 applies exactly. With Cy=W−1\mathsf C_y = \mathsf W^{-1},

Cβ=(ATWA)−1ATW W−1 WA (ATWA)−1,\mathsf C_\beta = (\mathsf A^{\mathsf T}\mathsf W\mathsf A)^{-1}\mathsf A^{\mathsf T}\mathsf W\,\mathsf W^{-1}\,\mathsf W\mathsf A\,(\mathsf A^{\mathsf T}\mathsf W\mathsf A)^{-1} ,

which collapses to

Cβ=(ATWA)−1.\mathsf C_\beta = (\mathsf A^{\mathsf T}\mathsf W\mathsf A)^{-1} .

The diagonal elements are the squared parameter uncertainties; the off-diagonal elements are their covariances.

The straight line

For y=a+bxy = a + bx with equal uncertainties σ\sigma,

ATWA=1σ2(N∑xi∑xi∑xi2),Cβ=σ2Sxx(1N∑xi2−xˉ−xˉ1),\mathsf A^{\mathsf T}\mathsf W\mathsf A = \frac{1}{\sigma^2}\begin{pmatrix} N & \sum x_i \\ \sum x_i & \sum x_i^2 \end{pmatrix}, \qquad \mathsf C_\beta = \frac{\sigma^2}{S_{xx}}\begin{pmatrix} \tfrac1N\sum x_i^2 & -\bar x \\ -\bar x & 1 \end{pmatrix} ,

using N∑xi2−(∑xi)2=NSxxN\sum x_i^2 - (\sum x_i)^2 = N S_{xx}. The diagonal reproduces ua2u_a^2 and ub2u_b^2 of Chapter 11. The new element is

uab=−xˉ σ2Sxx,ρab=−xˉSxx/N+xˉ2.u_{ab} = -\frac{\bar x\,\sigma^2}{S_{xx}} , \qquad \rho_{ab} = -\frac{\bar x}{\sqrt{S_{xx}/N + \bar x^2}} .

If the data lie at positive xx, slope and intercept are negatively correlated. The reason is geometric: the line is pinned near the centroid (xˉ,yˉ)(\bar x, \bar y) of the data, and a line that pivots there to a steeper slope must cut the yy-axis lower. The further the data are from x=0x = 0 compared with their spread, the closer ρab\rho_{ab} is to -1.

13.2 Example: absolute zero from a gas thermometer

The pressure of a fixed amount of gas at constant volume is measured at temperatures between 0 and 100 °C. For an ideal gas the pressure is linear in the Celsius temperature θ\theta,

P=a+b θ,P = a + b\,\theta ,

and extrapolates to zero at θ0=−a/b\theta_0 = -a/b, the absolute zero. Two derived quantities will be considered: the pressure predicted at 50 °C (an interpolation) and θ0\theta_0 (a long extrapolation, and a ratio of the two correlated parameters). The data are simulated from an ideal gas with θ0=−273.15\theta_0 = -273.15 °C and a pressure noise of 0.25 kPa.

intercept = 101.489 +/- 0.14
slope     = 0.367871 +/- 0.0024
correlation(intercept, slope) = -0.845
chi2 / dof = 7.48 / 9 = 0.83

covariance matrix [intercept, slope]:
 [[ 1.98863636e-02 -2.84090909e-04]
 [-2.84090909e-04  5.68181818e-06]]

The two derived quantities

Predicted pressure at θ∗\theta^\ast. With P∗=a+b θ∗P^\ast = a + b\,\theta^\ast the sensitivity coefficients are 1 and θ∗\theta^\ast, so

uP∗2=ua2+θ∗2ub2+2 θ∗uab.u_{P^\ast}^2 = u_a^2 + \theta^{\ast 2}u_b^2 + 2\,\theta^\ast u_{ab} .

Absolute zero. With θ0=−a/b\theta_0 = -a/b the coefficients are ∂θ0/∂a=−1/b\partial\theta_0/\partial a = -1/b and ∂θ0/∂b=a/b2\partial\theta_0/\partial b = a/b^2, so

uθ02=ua2b2+a2ub2b4−2ab3 uab.u_{\theta_0}^2 = \frac{u_a^2}{b^2} + \frac{a^2u_b^2}{b^4} - \frac{2a}{b^3}\,u_{ab} .

Since uab<0u_{ab} < 0, the covariance term reduces the uncertainty of the interpolated pressure and increases that of the extrapolated zero.

P(50 C)    = 119.882 kPa
   u with covariance    : 0.075 kPa
   u ignoring covariance: 0.185 kPa
absolute zero = -275.88 C   (true value -273.15)
   u with covariance    : 2.12 K
   u ignoring covariance: 1.83 K

Which is right? As in Chapter 11 we can repeat the simulated experiment many times and look at the actual scatter of the results.

actual scatter of P(50 C) over 5000 experiments  : 0.073 kPa
actual scatter of absolute zero                   : 2.05 K
correlation of intercept and slope: observed -0.849, from the fit -0.845
<Figure size 1012x792 with 4 Axes>

Panel (b) shows what a covariance matrix means. The fitted pairs (a,b)(a, b) from repeated experiments do not fill the rectangle spanned by ±ua\pm u_a and ±ub\pm u_b (black cross). They lie along a tilted ellipse: a fit that returns a high intercept almost always returns a low slope. The ellipses are drawn from the covariance matrix of the single fit above, and they describe the cloud well.

Panel (c): the uncertainty of the fitted line with and without the covariance term. With it, the uncertainty has its minimum σ/N\sigma/\sqrt N at the centroid of the data. Without it, the curve has its minimum at θ=0\theta = 0 and is more than twice too large in the middle of the data.

Panel (d): for the absolute zero the error goes the other way. Ignoring the covariance gives an error bar that is too small, and the histogram of repeated experiments confirms the value obtained with the covariance.

So the same omission overestimates one derived quantity and underestimates another. There is no safe direction, and no rule of thumb replaces the covariance term.

13.3 Centring removes the correlation

The correlation between aa and bb is not a property of the data but of the way the line was parametrised. Measure xx from the centroid instead,

y=a′+b (x−xˉ).y = a' + b\,(x - \bar x) .

Then a′=yˉa' = \bar y is the height of the line at the centroid, ua′=σ/Nu_{a'} = \sigma/\sqrt N, the slope and its uncertainty are unchanged, and the off-diagonal element of Cβ\mathsf C_\beta is proportional to ∑(xi−xˉ)=0\sum(x_i - \bar x) = 0. The two parameters are uncorrelated and can be quoted and propagated as independent quantities. (For a weighted fit, use the weighted mean xˉw\bar x_w.)

intercept = 119.882 +/- 0.075
slope     = 0.367871 +/- 0.0024
correlation(intercept, slope) = +0.000
chi2 / dof = 7.48 / 9 = 0.83

absolute zero from the centred fit, no covariance needed: -275.88 +/- 2.12 C

The result is identical to the one obtained with the full covariance matrix. Whenever fit parameters are to be published for others to use, choosing a parametrisation in which they are nearly uncorrelated is a courtesy to the reader. The Arrhenius example Chapter 22 shows how much this matters when ρab=−0.999\rho_{ab} = -0.999.

13.4 Transforming the data transforms the weights

Many nonlinear models become straight lines after a transformation: an exponential decay y=Ae−kty = Ae^{-kt} is linear in ln⁡y\ln y, a power law in ln⁡y\ln y against ln⁡x\ln x, Michaelis–Menten kinetics in 1/v1/v against 1/[S]1/[S]. The transformation also acts on the error bars. By the one-variable rule of Chapter 3,

uln⁡y=uyy,u1/y=uyy2.u_{\ln y} = \frac{u_y}{y} , \qquad u_{1/y} = \frac{u_y}{y^2} .

If the original data have equal absolute uncertainties, the transformed data do not: for an exponential decay the points in the tail, where yy is small, have large uncertainties in ln⁡y\ln y and should count for little. An unweighted straight-line fit of the transformed data gives every point the same say, and the noisy tail then dominates the result.

There is a second, subtler effect. The logarithm is curved, so by Section 12.3 symmetric noise in yy becomes biased noise in ln⁡y\ln y: ⟨ln⁡y⟩≈ln⁡ytrue−12(uy/y)2\langle\ln y\rangle \approx \ln y_\text{true} - \tfrac12(u_y/y)^2. In the tail this pulls the points systematically downwards.

The simulation below generates decay data with constant absolute noise and estimates kk in three ways: (1) unweighted fit of ln⁡y\ln y; (2) weighted fit of ln⁡y\ln y with σln⁡y=σ/y\sigma_{\ln y} = \sigma/y; (3) a nonlinear least-squares fit of the untransformed data.

true k = 1.0;  26 of 48000 points were non-positive and dropped

method                       mean k    bias/k    scatter   typical quoted u
log fit, unweighted         1.0233   +2.33%    0.0773     0.0432
log fit, weighted           0.9854   -1.46%    0.0238     0.0238
nonlinear fit               0.9992   -0.08%    0.0235     0.0240

The unweighted logarithmic fit is the worst on every count: its scatter is three times that of the other two, it is biased by about +2 %+2\,\%, and the uncertainty it quotes is well below its actual scatter. The weighted logarithmic fit recovers the precision but keeps a bias of about −1.5 %-1.5\,\%, more than half its standard uncertainty. The reason is that the weights σ/y\sigma/y are computed from the noisy data themselves, so a point that happened to fluctuate upwards receives a larger weight. The nonlinear fit of the untransformed data is unbiased to within the noise of the simulation, and its quoted uncertainty matches its actual scatter.

The general advice follows. Linearising transformations were invented for graph paper. They remain excellent for looking at data, because the eye judges straightness well. For estimating parameters, either fit the original data with the original model (scipy.optimize.curve_fit returns the covariance matrix in the same form as above), or transform the weights together with the data.

The exception is data whose noise is proportional to the signal (constant relative uncertainty). Then uln⁡yu_{\ln y} is constant, and the unweighted fit of ln⁡y\ln y is the correct one. The Arrhenius example (Chapter 22) is of this kind.

13.5 When the error bars are unknown or doubtful

The covariance matrix (ATWA)−1(\mathsf A^{\mathsf T}\mathsf W\mathsf A)^{-1} scales with the assumed σi2\sigma_i^2. It contains no information from the residuals: double all the error bars and all parameter uncertainties double, whatever the data do. Two situations must be distinguished.

The error bars are trusted. Use them as they are, and use χν2\chi^2_\nu as a test of the model. In scipy.optimize.curve_fit this is absolute_sigma=True; in ep.linear_fit it is the default.

Only the relative weights are known (or nothing is known and all points are weighted equally). Then the overall scale is estimated from the residuals, by multiplying the covariance by χν2\chi^2_\nu, which amounts to assuming that the model is correct. This is absolute_sigma=False, the default of curve_fit, and scale_cov=True in ep.linear_fit. The goodness-of-fit test is then no longer available, since it has been used up.

A frequent mistake is to supply carefully estimated error bars and leave absolute_sigma at its default, in which case their absolute size is silently ignored.

true sigma = 0.25 kPa; fit performed with sigma = 0.5 kPa
  absolute error bars : u_b = 0.00477,  chi2/dof = 0.21  <- suspiciously small
  rescaled by chi2/dof: u_b = 0.00217
  fit with the correct sigma: u_b = 0.00238

probability of a chi-square this small by chance (9 degrees of freedom): 0.007

With the error bars taken at face value, the slope uncertainty is twice too large, and the very small χν2\chi^2_\nu is the warning. Rescaling by χν2\chi^2_\nu brings the uncertainty back to roughly the correct value, at the price of trusting the model.

13.6 Uncertainty in both variables

Ordinary least squares assumes that xx is exact. If xx is also noisy, two things happen.

The error bars are larger than they look. An error δx\delta x moves a point horizontally, which for a line of slope bb is equivalent to a vertical displacement b δxb\,\delta x. When the xx-errors are small compared with the range of xx, it is enough to replace each σy,i2\sigma_{y,i}^2 by the effective variance

σeff,i2=σy,i2+b2σx,i2,\sigma_{\text{eff},i}^2 = \sigma_{y,i}^2 + b^2\sigma_{x,i}^2 ,

using a preliminary estimate of bb. The pendulum example Chapter 20 does this.

The slope is biased towards zero. This is less well known and more dangerous. If the true xx values have spread sxs_x (standard deviation) and the measurement error of xx has standard deviation σx\sigma_x, the least-squares slope converges not to bb but to

bOLS→b sx2sx2+σx2.b_\text{OLS} \to b\,\frac{s_x^2}{s_x^2 + \sigma_x^2} .

The effect is called attenuation or regression dilution. It does not shrink with more data, and the quoted ubu_b gives no hint of it. When the ratio λ=σy2/σx2\lambda = \sigma_y^2/\sigma_x^2 of the two error variances is known, the unbiased alternative is Deming regression, which minimises the weighted perpendicular distances and has the closed form

b=Syy−λSxx+(Syy−λSxx)2+4λSxy22Sxy.b = \frac{S_{yy} - \lambda S_{xx} + \sqrt{(S_{yy} - \lambda S_{xx})^2 + 4\lambda S_{xy}^2}}{2S_{xy}} .
true slope                         : 0.5
ordinary least squares, mean slope : 0.4566   (typical quoted u_b = 0.0357)
attenuation formula                : 0.4533
Deming regression, mean slope      : 0.5021

With an xx-error of one unit on a range of ten, ordinary least squares underestimates the slope by 8 to 9 %, close to the prediction of the attenuation formula (which is exact only for many points), and more than the quoted ubu_b. Deming regression removes nearly all of the bias. For general problems with uncertainties in both variables (unequal error bars, nonlinear models), the keywords are orthogonal distance regression, total least squares and, for straight lines with correlated errors, the method of York.

Summary

  • For linear least squares, β^\hat{\boldsymbol\beta} is linear in the data and Cβ=(ATWA)−1\mathsf C_\beta = (\mathsf A^{\mathsf T}\mathsf W\mathsf A)^{-1} exactly.

  • Slope and intercept are correlated, with uab=−xˉσ2/Sxxu_{ab} = -\bar x\sigma^2/S_{xx}. Derived quantities need the covariance; ignoring it can err in either direction.

  • Centring the independent variable decorrelates the parameters.

  • Transformations change the weights and can introduce bias. Fit the original model, or transform the weights too.

  • Know whether your error bars are used absolutely or only relatively.

  • Errors in xx enlarge the effective error bars and bias the slope towards zero.

References

  • W. E. Deming, Statistical Adjustment of Data (Wiley, 1943).

  • D. York, N. M. Evensen, M. López Martínez and J. De Basabe Delgado, “Unified equations for the slope, intercept, and standard errors of the best straight line”, Am. J. Phys. 72, 367 (2004).

Exercises

  1. Derive uP∗u_{P^\ast} of Section 13.2 and show that it has its minimum σ/N\sigma/\sqrt N at θ∗=θˉ\theta^\ast = \bar\theta.

  2. Repeat the gas-thermometer simulation with data taken only between 0 and 30 °C (same number of points). How do ρab\rho_{ab} and uθ0u_{\theta_0} change? Is the distribution of θ0\theta_0 still symmetric?

  3. Fit a parabola to data with ep.general_linear_fit and plot the ±u\pm u band of the fitted curve, using the full 3×33\times3 covariance matrix.

  4. In Section 13.4, change the noise to be proportional to the signal (5 % of yy). Which of the three methods is now best, and why?

  5. For the attenuation example, use the effective-variance weights in an ordinary weighted fit. Does this remove the bias? Explain.