Type at least 2 letters. Enter opens the first result, Esc closes.

    Probability and Statistics · Lesson 13 · Testing, experiments and regression

    Linear regression from the statistics view

    Intermediate 80 min 5 interactive figures 3 videos Colab notebook

    Before this lesson: lesson 04 (covariance of a random vector, Cov⁡(AX)=ACov⁡(X)A⊤\operatorname{Cov}(AX) = A\operatorname{Cov}(X)A^\top), lesson 05 (the multivariate Gaussian), lesson 08 (maximum likelihood), lesson 10 (priors and posteriors) and lesson 11 (tt-tests and pp-values). From linear algebra: least squares with QR and projections. Time: about 80 minutes, plus the notebook.


    Why this matters #

    • Is the effect real? Every regression table in a paper or an experiment report shows coefficients, standard errors and pp-values. A/B tests are often analysed by regression, with covariates to reduce variance (CUPED in lesson 12).
    • Uncertainty in predictions. A forecast needs an interval, and the right one is the prediction interval, not the confidence interval. Confusing them gives intervals that are far too narrow.
    • Fits in ML research. Scaling laws are linear fits of log loss against log compute; the uncertainty of the fitted exponent decides how far you can extrapolate. Linear probes on network features are regressions too.
    • Bayesian linear regression is the simplest Bayesian model with a closed-form posterior. It explains ridge and weight decay as a Gaussian prior, and it is the weight-space view of a Gaussian process (ml-for-science 07).

    1. Predict first #

    2. The picture #

    The running example. Five students report hours of study xx and an exam score yy (out of 10):

    xx (hours) 1 2 3 4 5
    yy (score) 2 4 5 4 5

    Least squares gives the line y^=2.2+0.6x\hat y = 2.2 + 0.6x (section 4 does every step). So each extra hour is worth 0.6 points. But five students are few. Another class of five would give another line. How much would the slope change?

    The model. We assume that the data come from a true line plus noise:

    yi=β0+β1xi+εi,y_i = \beta_0 + \beta_1 x_i + \varepsilon_i ,

    where the errors ε1,…,εn\varepsilon_1, \dots, \varepsilon_n are i.i.d. N(0,σ2)\mathcal N(0, \sigma^2). The xix_i are fixed (we condition on them). Only the noise is random. The fitted coefficients β^0,β^1\hat\beta_0, \hat\beta_1 are functions of the noisy yiy_i, so they are random variables. Their distribution over repeated data sets is the sampling distribution. You cannot see it from one data set, but you can simulate it:

    Interactive figure: loading…

    Press "New data set" a few times, then "Add 100 data sets". The orange line is the true line. Each data set gives a fitted line: the newest is yellow, earlier ones are faint blue. The histograms collect β^0\hat\beta_0 and β^1\hat\beta_1 over all data sets; the orange curves are the theory N(β,σ2(X⊤X)−1)\mathcal N(\beta, \sigma^2(X^\top X)^{-1}) from section 3. Make nn larger or σ\sigma smaller and watch the fan and the histograms get narrower.

    The fan is narrow in the middle of the data and wide at the ends. The fitted lines all pass close to the point (xˉ,yˉ)(\bar x, \bar y) and rotate around it. A small change of slope moves the line a lot far from xˉ\bar x and very little near it. This one fact explains the shape of every band below.

    Two questions, two bands. Take a new x0x_0.

    • Where is the mean response E[y∣x0]=β0+β1x0\mathbb{E}[y \mid x_0] = \beta_0 + \beta_1 x_0? The only uncertainty is in the fitted line. This gives the confidence band.
    • Where will one new observation y0y_0 fall? Now there are two sources: the uncertainty of the line, plus the new noise ε0\varepsilon_0. This gives the wider prediction band.
    Interactive figure: loading…

    Drag the yellow point along the line, then move the nn slider to the right. The orange band is the 95% confidence band for the mean; the violet band is the 95% prediction band for a new yy. Both are narrowest at xˉ\bar x. With large nn the orange band shrinks to the line, but the violet band stays about ±1.96σ\pm 1.96\sigma wide. A wider spread of xx makes the slope more precise (smaller SE, larger tt).

    Quick check

    Two designs have the same n=20n = 20 and the same noise σ\sigma. In design A the xx values are spread over [4,6][4, 6]; in design B over [0,10][0, 10] (evenly spaced in both). How do the standard errors of the slope compare?

    3. Definitions and main results #

    The model and the least-squares estimator #

    Write the data in matrix form. y∈Rny \in \mathbb{R}^n is the response, and X∈Rn×pX \in \mathbb{R}^{n \times p} is the design matrix: row ii holds the features of observation ii, and the first column is all ones (the intercept). In the exam example p=2p = 2. The linear model is

    y=Xβ+ε.y = X\beta + \varepsilon .

    We use these assumptions; each result says which ones it needs.

    Assumption
    A1 linear mean: E[y]=Xβ\mathbb{E}[y] = X\beta
    A2 XX is fixed and has full column rank pp (no column is a combination of the others)
    A3 errors have mean 0 and covariance σ2I\sigma^2 I: uncorrelated, with constant variance (homoscedastic)
    A4 errors are Gaussian: ε∼N(0,σ2I)\varepsilon \sim \mathcal N(0, \sigma^2 I)

    The ordinary least squares (OLS) estimator minimises the residual sum of squares RSS(β)=∥y−Xβ∥2\text{RSS}(\beta) = \|y - X\beta\|^2. Setting the gradient −2X⊤(y−Xβ)-2X^\top(y - X\beta) to zero gives the normal equations X⊤Xβ^=X⊤yX^\top X\hat\beta = X^\top y, so

    β^=(X⊤X)−1X⊤y.\hat\beta = (X^\top X)^{-1}X^\top y .

    In code, never form the inverse: factor X=QRX = QR and solve Rβ^=Q⊤yR\hat\beta = Q^\top y (linear algebra 12). The fitted values are y^=Xβ^=Hy\hat y = X\hat\beta = Hy with the hat matrix H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top. HH is the orthogonal projection onto the column space of XX. The residuals are e=y−y^=(I−H)ye = y - \hat y = (I - H)y. They are orthogonal to every column of XX: X⊤e=0X^\top e = 0. With an intercept column this says ∑iei=0\sum_i e_i = 0.

    OLS is the Gaussian maximum likelihood estimator. Under A4 the log-likelihood is ℓ(β,σ2)=−n2log⁡(2πσ2)−12σ2∥y−Xβ∥2\ell(\beta, \sigma^2) = -\frac n2 \log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\|y - X\beta\|^2. For any σ2\sigma^2, maximising over β\beta means minimising ∥y−Xβ∥2\|y - X\beta\|^2. So the MLE of β\beta is β^\hat\beta (lesson 08). The MLE of σ2\sigma^2 is RSS/n\text{RSS}/n, which is biased; see below.

    β^\hat\beta is a random vector #

    Theorem (sampling distribution of OLS). Under A1–A3, E[β^]=β\mathbb{E}[\hat\beta] = \beta and Cov⁡(β^)=σ2(X⊤X)−1\operatorname{Cov}(\hat\beta) = \sigma^2(X^\top X)^{-1}. Under A4 in addition,

    β^∼N(β, σ2(X⊤X)−1).\hat\beta \sim \mathcal N\big(\beta,\ \sigma^2 (X^\top X)^{-1}\big).

    Proof.

    1. Put y=Xβ+εy = X\beta + \varepsilon into the formula. With A=(X⊤X)−1X⊤A = (X^\top X)^{-1}X^\top (a fixed p×np \times n matrix): β^=AXβ+Aε=β+Aε\hat\beta = A X\beta + A\varepsilon = \beta + A\varepsilon, because AX=IAX = I.
    2. Mean: E[β^]=β+A E[ε]=β\mathbb{E}[\hat\beta] = \beta + A\,\mathbb{E}[\varepsilon] = \beta.
    3. Covariance (lesson 04, Cov⁡(Aε)=ACov⁡(ε)A⊤\operatorname{Cov}(A\varepsilon) = A\operatorname{Cov}(\varepsilon)A^\top): Cov⁡(β^)=A(σ2I)A⊤=σ2(X⊤X)−1X⊤X(X⊤X)−1=σ2(X⊤X)−1\operatorname{Cov}(\hat\beta) = A(\sigma^2 I)A^\top = \sigma^2 (X^\top X)^{-1}X^\top X(X^\top X)^{-1} = \sigma^2(X^\top X)^{-1}.
    4. Under A4, β^\hat\beta is an affine function of the Gaussian vector ε\varepsilon, so it is Gaussian (lesson 05). ■\blacksquare

    Simple regression. For one feature, X⊤X=(n∑xi∑xi∑xi2)X^\top X = \begin{pmatrix} n & \sum x_i \\ \sum x_i & \sum x_i^2\end{pmatrix}. Inverting it gives

    Var⁡(β^1)=σ2Sxx,Var⁡(β^0)=σ2(1n+xˉ2Sxx),Sxx=∑i=1n(xi−xˉ)2.\operatorname{Var}(\hat\beta_1) = \frac{\sigma^2}{S_{xx}}, \qquad \operatorname{Var}(\hat\beta_0) = \sigma^2\Big(\frac1n + \frac{\bar x^2}{S_{xx}}\Big), \qquad S_{xx} = \sum_{i=1}^n (x_i - \bar x)^2 .

    Three levers make the slope precise: less noise (small σ\sigma), more points, and points spread far from xˉ\bar x (large SxxS_{xx}). If you repeat the same design kk times, SxxS_{xx} grows by kk and the standard error shrinks by 1/k1/\sqrt k.

    Estimating σ2\sigma^2: why n−pn - p #

    σ2\sigma^2 is unknown. The natural estimate uses the residuals:

    s2=RSSn−p=1n−p∑i=1nei2.s^2 = \frac{\text{RSS}}{n - p} = \frac{1}{n - p}\sum_{i=1}^n e_i^2 .

    Theorem. Under A1–A3, E[s2]=σ2\mathbb{E}[s^2] = \sigma^2.

    Why n−pn - p and not nn (intuition). The fitted line is chosen to be close to the data, so the residuals are smaller than the true errors. The residual vector is orthogonal to the pp columns of XX, so it lives in a space of dimension n−pn - p: fitting has used up pp directions. With n=pn = p points the fit is exact and all residuals are 0. The n−pn - p is called the residual degrees of freedom.

    Proof: the trace of the hat matrix
    1. (I−H)X=X−X=0(I - H)X = X - X = 0, so e=(I−H)y=(I−H)(Xβ+ε)=(I−H)εe = (I - H)y = (I - H)(X\beta + \varepsilon) = (I - H)\varepsilon.
    2. I−HI - H is symmetric and idempotent ((I−H)2=I−H(I - H)^2 = I - H), so RSS=e⊤e=ε⊤(I−H)ε\text{RSS} = e^\top e = \varepsilon^\top (I - H)\varepsilon.
    3. For a random vector with mean 0 and covariance CC, E[ε⊤Mε]=tr⁡(MC)\mathbb{E}[\varepsilon^\top M\varepsilon] = \operatorname{tr}(MC) (write ε⊤Mε=tr⁡(Mεε⊤)\varepsilon^\top M\varepsilon = \operatorname{tr}(M\varepsilon\varepsilon^\top) and take the expectation). Here C=σ2IC = \sigma^2 I, so E[RSS]=σ2tr⁡(I−H)\mathbb{E}[\text{RSS}] = \sigma^2 \operatorname{tr}(I - H).
    4. tr⁡(H)=tr⁡(X(X⊤X)−1X⊤)=tr⁡((X⊤X)−1X⊤X)=tr⁡(Ip)=p\operatorname{tr}(H) = \operatorname{tr}\big(X(X^\top X)^{-1}X^\top\big) = \operatorname{tr}\big((X^\top X)^{-1}X^\top X\big) = \operatorname{tr}(I_p) = p (the trace is invariant under cyclic shifts).
    5. So E[RSS]=σ2(n−p)\mathbb{E}[\text{RSS}] = \sigma^2(n - p) and E[s2]=σ2\mathbb{E}[s^2] = \sigma^2. ■\blacksquare

    Under A4 one can say more: RSS/σ2∼χn−p2\text{RSS}/\sigma^2 \sim \chi^2_{n-p}, and s2s^2 is independent of β^\hat\beta. Independence follows from lesson 05: β^−β=Aε\hat\beta - \beta = A\varepsilon and e=(I−H)εe = (I - H)\varepsilon are jointly Gaussian, and Cov⁡(Aε,(I−H)ε)=σ2A(I−H)=0\operatorname{Cov}(A\varepsilon, (I - H)\varepsilon) = \sigma^2 A(I - H) = 0 because X⊤(I−H)=0X^\top(I - H) = 0.

    Standard errors, tt-tests and confidence intervals #

    Replace σ\sigma by ss in the covariance. The standard error of coefficient jj is

    SE⁡j=s[(X⊤X)−1]jj.\operatorname{SE}_j = s\sqrt{\big[(X^\top X)^{-1}\big]_{jj}} .

    Theorem. Under A1–A4,

    Tj=β^j−βjSE⁡j∼tn−p.T_j = \frac{\hat\beta_j - \beta_j}{\operatorname{SE}_j} \sim t_{n-p} .

    Proof.

    1. Z=(β^j−βj)/(σ[(X⊤X)−1]jj)∼N(0,1)Z = (\hat\beta_j - \beta_j)/\big(\sigma\sqrt{[(X^\top X)^{-1}]_{jj}}\big) \sim \mathcal N(0, 1) by the theorem above.
    2. V=(n−p)s2/σ2∼χn−p2V = (n - p)s^2/\sigma^2 \sim \chi^2_{n-p}, independent of ZZ (end of the proof block above).
    3. Tj=Z/V/(n−p)T_j = Z/\sqrt{V/(n - p)} (the unknown σ\sigma cancels). This ratio is the definition of Student's tn−pt_{n-p} distribution (lesson 06). ■\blacksquare

    This gives the usual tools (lesson 11):

    • tt-test of H0:βj=0H_0: \beta_j = 0: the tt-statistic is t=β^j/SE⁡jt = \hat\beta_j/\operatorname{SE}_j, and the two-sided pp-value is 2P(Tn−p>∣t∣)2P(T_{n-p} > |t|).
    • Confidence interval at level 95%: β^j±tn−p, 0.975SE⁡j\hat\beta_j \pm t_{n-p,\,0.975}\operatorname{SE}_j, where tn−p, 0.975t_{n-p,\,0.975} is the 0.975 quantile. For large n−pn - p it is close to 1.96; for n−p=3n - p = 3 it is 3.18.

    Confidence interval for the mean, prediction interval for a new yy #

    Let x0∈Rpx_0 \in \mathbb{R}^p be a new feature vector (with the leading 1). The prediction is y^0=x0⊤β^\hat y_0 = x_0^\top\hat\beta. Let h0=x0⊤(X⊤X)−1x0h_0 = x_0^\top (X^\top X)^{-1}x_0.

    • Mean response μ0=x0⊤β\mu_0 = x_0^\top\beta. Var⁡(y^0)=σ2h0\operatorname{Var}(\hat y_0) = \sigma^2 h_0, so the 95% confidence interval is y^0±tn−p, 0.975 sh0\hat y_0 \pm t_{n-p,\,0.975}\, s\sqrt{h_0}.
    • New observation y0=x0⊤β+ε0y_0 = x_0^\top\beta + \varepsilon_0, with new noise ε0\varepsilon_0 independent of the data. The error y0−y^0=ε0−x0⊤(β^−β)y_0 - \hat y_0 = \varepsilon_0 - x_0^\top(\hat\beta - \beta) is a sum of two independent terms, so Var⁡(y0−y^0)=σ2(1+h0)\operatorname{Var}(y_0 - \hat y_0) = \sigma^2(1 + h_0). The 95% prediction interval is y^0±tn−p, 0.975 s1+h0\hat y_0 \pm t_{n-p,\,0.975}\, s\sqrt{1 + h_0}.

    For simple regression h0=1n+(x0−xˉ)2Sxxh_0 = \frac1n + \frac{(x_0 - \bar x)^2}{S_{xx}}: smallest at x0=xˉx_0 = \bar x and growing quadratically away from it. That is the curved shape of the bands. As n→∞n \to \infty, h0→0h_0 \to 0: the confidence interval shrinks to a point, while the prediction interval tends to x0⊤β±1.96σx_0^\top\beta \pm 1.96\sigma.

    Quick check

    You fit a regression on n=106n = 10^6 points with noise σ=2\sigma = 2. What is the approximate half-width of the 95% prediction interval for one new yy at x0=xˉx_0 = \bar x?

    R2R^2, adjusted R2R^2 and the FF-test #

    With an intercept, the total sum of squares TSS=∑i(yi−yˉ)2\text{TSS} = \sum_i (y_i - \bar y)^2 splits into the explained part ∑i(y^i−yˉ)2\sum_i(\hat y_i - \bar y)^2 plus RSS (the cross term vanishes because ee is orthogonal to y^−yˉ1\hat y - \bar y\mathbf 1). The coefficient of determination is

    R2=1−RSSTSS∈[0,1],R^2 = 1 - \frac{\text{RSS}}{\text{TSS}} \in [0, 1] ,

    the fraction of the variance of yy that the model explains. In simple regression R2=r2R^2 = r^2, the squared sample correlation of xx and yy. Adding a feature never increases RSS, so R2R^2 never goes down, even for a useless feature. The adjusted R2=1−RSS/(n−p)TSS/(n−1)R^2 = 1 - \frac{\text{RSS}/(n - p)}{\text{TSS}/(n - 1)} compares variance estimates instead, and can go down.

    FF-test for nested models. A small model with p0p_0 columns is inside a big model with p1p_1 columns (the small model sets p1−p0p_1 - p_0 coefficients to 0). Under H0H_0 (the extra coefficients are 0) and A1–A4,

    F=(RSS0−RSS1)/(p1−p0)RSS1/(n−p1)∼Fp1−p0,  n−p1.F = \frac{(\text{RSS}_0 - \text{RSS}_1)/(p_1 - p_0)}{\text{RSS}_1/(n - p_1)} \sim F_{p_1 - p_0,\; n - p_1} .

    It asks: does the drop in RSS beat what noise alone would give? For one extra coefficient, F=t2F = t^2 and the two tests agree. The "overall FF-test" in regression output compares the model with the intercept-only model.

    Significance is not size. In simple regression t2=(n−2)R21−R2t^2 = (n - 2)\frac{R^2}{1 - R^2}. With n=1000n = 1000 and R2=0.02R^2 = 0.02: t=998⋅0.02/0.98=4.51t = \sqrt{998 \cdot 0.02/0.98} = 4.51 and p≈7⋅10−6p \approx 7 \cdot 10^{-6}. The slope is surely not 0, but xx explains only 2% of the variance of yy. A small pp-value says "there is an effect", not "the effect is large" or "the model predicts well".

    Quick check

    You add a column of pure random noise to the design matrix and refit. What happens?

    The Gauss–Markov theorem #

    Why least squares, and not another method? Call an estimator linear if it has the form β~=Cy\tilde\beta = Cy for a fixed matrix CC, and unbiased if E[β~]=β\mathbb{E}[\tilde\beta] = \beta for every β\beta.

    Theorem (Gauss–Markov). Under A1–A3 (no Gaussian assumption), OLS is the best linear unbiased estimator (BLUE): for every linear unbiased β~\tilde\beta, the matrix Cov⁡(β~)−Cov⁡(β^)\operatorname{Cov}(\tilde\beta) - \operatorname{Cov}(\hat\beta) is positive semidefinite. In particular, every coefficient and every combination c⊤βc^\top\beta has the smallest variance with OLS.

    Proof
    1. Write C=A+DC = A + D with A=(X⊤X)−1X⊤A = (X^\top X)^{-1}X^\top. Unbiasedness for every β\beta means CXβ=βCX\beta = \beta for all β\beta, so CX=ICX = I. Since AX=IAX = I, this gives DX=0DX = 0.
    2. Cov⁡(β~)=σ2CC⊤=σ2(AA⊤+AD⊤+DA⊤+DD⊤)\operatorname{Cov}(\tilde\beta) = \sigma^2 CC^\top = \sigma^2(AA^\top + AD^\top + DA^\top + DD^\top).
    3. AD⊤=(X⊤X)−1(DX)⊤=0AD^\top = (X^\top X)^{-1}(DX)^\top = 0, and DA⊤=(AD⊤)⊤=0DA^\top = (AD^\top)^\top = 0.
    4. So Cov⁡(β~)=σ2(X⊤X)−1+σ2DD⊤\operatorname{Cov}(\tilde\beta) = \sigma^2(X^\top X)^{-1} + \sigma^2 DD^\top, and DD⊤DD^\top is positive semidefinite. ■\blacksquare

    The theorem has limits. It compares only unbiased estimators: ridge regression is biased and can have a smaller mean squared error. It compares only linear ones: with heavy-tailed noise, a robust (nonlinear) fit can be much better. And it needs A3: with unequal variances, weighted least squares beats OLS.

    Multicollinearity #

    When two features are strongly correlated, the data cannot tell their effects apart. In the formula, X⊤XX^\top X is close to singular and (X⊤X)−1(X^\top X)^{-1} is large. A clean way to say it: with an intercept,

    Var⁡(β^j)=σ2Sxjxj (1−Rj2),\operatorname{Var}(\hat\beta_j) = \frac{\sigma^2}{S_{x_j x_j}\,(1 - R_j^2)} ,

    where Sxjxj=∑i(xij−xˉj)2S_{x_jx_j} = \sum_i (x_{ij} - \bar x_j)^2 and Rj2R_j^2 is the R2R^2 of a regression of feature jj on all the other features. The factor VIFj=1/(1−Rj2)\text{VIF}_j = 1/(1 - R_j^2) is the variance inflation factor. For two features with correlation ρ\rho, Rj2=ρ2R_j^2 = \rho^2: ρ=0.9\rho = 0.9 gives VIF 5.3 (standard errors 2.3 times larger), and ρ=0.99\rho = 0.99 gives VIF 50 (standard errors 7.1 times larger).

    Interactive figure: loading…

    Move the correlation slider from 0 to 0.99. Each blue dot is (β^1,β^2)(\hat\beta_1, \hat\beta_2) from one data set with the same features and new noise; the orange ellipse is the 95% region of N(β,σ2(X⊤X)−1)\mathcal N(\beta, \sigma^2(X^\top X)^{-1}) around the true β=(1,1)\beta = (1, 1). With correlated features the ellipse grows along the direction β1−β2\beta_1 - \beta_2 and tilts: the estimates are negatively correlated. The sum β1+β2\beta_1 + \beta_2 (the short axis) stays precise.

    Multicollinearity does not bias β^\hat\beta, and it does not hurt predictions at xx values like the training data. It makes single coefficients unstable, so do not read much into their signs or sizes. It is the statistical face of a large condition number (linear algebra 13).

    Diagnostics: when the assumptions fail #

    All the formulas above trust A1–A4. Residual plots check them: plot eie_i against the fitted values y^i\hat y_i (or against each feature, or against time). Under the model, this plot is a structureless band around 0.

    Assumption fails What the residual plot shows What goes wrong Common fix
    A1: the truth is curved a U shape or a wave β^\hat\beta is biased; predictions are wrong add features (x2x^2, splines), transform xx or yy
    A3: variance not constant (heteroscedastic) a fan: spread grows with y^\hat y β^\hat\beta is still unbiased, but the classical SEs are wrong (often too small) robust standard errors; weighted least squares; log⁡y\log y
    A3: errors correlated (time series, groups) waves in eie_i against time; clusters SEs too small: the data carry less information than nn suggests cluster or HAC standard errors; the block bootstrap (lesson 12)
    A4: errors not Gaussian skew or heavy tails (check a Q–Q plot) exact tt and FF tests fail for small nn; for large nn the CLT rescues them larger nn, the bootstrap, a robust fit
    one point dominates may show nothing (see below) the fit follows one point check leverage and influence

    Leverage. The diagonal entries hiih_{ii} of the hat matrix are the leverages: y^i=∑khikyk\hat y_i = \sum_k h_{ik} y_k, so hiih_{ii} measures how much yiy_i pulls its own fitted value. They lie in [0,1][0, 1] and add up to pp, so the average is p/np/n; a common flag is hii>2p/nh_{ii} > 2p/n. In simple regression hii=1n+(xi−xˉ)2Sxxh_{ii} = \frac1n + \frac{(x_i - \bar x)^2}{S_{xx}}: points with an extreme xx have high leverage. A high-leverage point pulls the line toward itself, so its own residual is small, and the residual plot can hide it. Measures of influence such as Cook's distance combine leverage and the residual.

    Interactive figure: loading…

    Try the four presets. Blue points are data, the orange line is the least-squares fit, and magenta points have high leverage (hii>2p/nh_{ii} > 2p/n). The right plot shows residuals against fitted values. Compare the classical and the robust standard error of the slope in each case: they agree for the good model and differ when the noise grows with xx.

    Heteroscedasticity-robust (sandwich) standard errors

    If Cov⁡(ε)=Ω\operatorname{Cov}(\varepsilon) = \Omega is diagonal but not σ2I\sigma^2 I, step 3 of the proof above gives Cov⁡(β^)=AΩA⊤=(X⊤X)−1X⊤ΩX(X⊤X)−1\operatorname{Cov}(\hat\beta) = A\Omega A^\top = (X^\top X)^{-1}X^\top\Omega X(X^\top X)^{-1}. The two outer factors are the "bread" and the middle is the "meat". White (1980) showed that you can replace Ω\Omega by diag⁡(e12,…,en2)\operatorname{diag}(e_1^2, \dots, e_n^2) (the HC0 estimator) and get a consistent estimate of the covariance, even though each ei2e_i^2 is a poor estimate of its own variance. The average over nn terms does the work. In small samples HC0 is too small; the HC3 variant uses ei2/(1−hii)2e_i^2/(1 - h_{ii})^2 and is the usual default. Cluster-robust and HAC (Newey–West) estimators extend the same sandwich to correlated errors.

    Correlation is not causation. A coefficient βj\beta_j measures how E[y]\mathbb{E}[y] changes with xjx_j when the other included features are held fixed. If a variable that affects both xjx_j and yy is left out (a confounder), β^j\hat\beta_j absorbs its effect. If the true model is y=β1x1+β2x2+εy = \beta_1 x_1 + \beta_2 x_2 + \varepsilon and you fit yy on x1x_1 alone, then E[β^1]=β1+β2δ\mathbb{E}[\hat\beta_1] = \beta_1 + \beta_2\delta, where δ\delta is the slope of x2x_2 on x1x_1 (the omitted-variable bias). Small standard errors do not fix this; see causal inference 01.

    Bayesian linear regression #

    The Bayesian view (lesson 10) treats β\beta itself as random. Keep the Gaussian likelihood with a known noise variance σ2\sigma^2, and put a Gaussian prior on the coefficients:

    y∣β∼N(Xβ,σ2I),β∼N(0,α−1I),y \mid \beta \sim \mathcal N(X\beta, \sigma^2 I), \qquad \beta \sim \mathcal N(0, \alpha^{-1}I) ,

    where α>0\alpha > 0 is the prior precision (a large α\alpha says "the coefficients are small").

    Theorem (Bayesian linear regression). The posterior is β∣y∼N(mN,SN)\beta \mid y \sim \mathcal N(m_N, S_N) with

    SN−1=αI+1σ2X⊤X,mN=1σ2 SNX⊤y,S_N^{-1} = \alpha I + \frac{1}{\sigma^2}X^\top X, \qquad m_N = \frac{1}{\sigma^2}\,S_N X^\top y ,

    and the posterior predictive distribution of a new y0y_0 at x0x_0 is N(x0⊤mN, σ2+x0⊤SNx0)\mathcal N\big(x_0^\top m_N,\ \sigma^2 + x_0^\top S_N x_0\big).

    Proof.

    1. Bayes: log⁡p(β∣y)=log⁡p(y∣β)+log⁡p(β)+const=−12σ2∥y−Xβ∥2−α2∥β∥2+const\log p(\beta \mid y) = \log p(y \mid \beta) + \log p(\beta) + \text{const} = -\frac{1}{2\sigma^2}\|y - X\beta\|^2 - \frac\alpha2\|\beta\|^2 + \text{const}.
    2. Expand ∥y−Xβ∥2=y⊤y−2β⊤X⊤y+β⊤X⊤Xβ\|y - X\beta\|^2 = y^\top y - 2\beta^\top X^\top y + \beta^\top X^\top X\beta and collect the terms in β\beta: log⁡p(β∣y)=−12β⊤(αI+1σ2X⊤X)β+β⊤1σ2X⊤y+const\log p(\beta \mid y) = -\frac12\beta^\top\big(\alpha I + \tfrac{1}{\sigma^2}X^\top X\big)\beta + \beta^\top\tfrac{1}{\sigma^2}X^\top y + \text{const}.
    3. The log-density of N(m,S)\mathcal N(m, S) is −12β⊤S−1β+β⊤S−1m+const-\frac12\beta^\top S^{-1}\beta + \beta^\top S^{-1}m + \text{const}. Matching the quadratic terms gives SN−1S_N^{-1}; matching the linear terms gives SN−1mN=X⊤y/σ2S_N^{-1}m_N = X^\top y/\sigma^2.
    4. Predictive: y0=x0⊤β+ε0y_0 = x_0^\top\beta + \varepsilon_0, with β∣y∼N(mN,SN)\beta \mid y \sim \mathcal N(m_N, S_N) and independent ε0∼N(0,σ2)\varepsilon_0 \sim \mathcal N(0, \sigma^2). The sum is Gaussian with mean x0⊤mNx_0^\top m_N and variance x0⊤SNx0+σ2x_0^\top S_N x_0 + \sigma^2. ■\blacksquare

    The posterior mean is ridge regression. Multiply inside and outside the inverse by σ2\sigma^2:

    mN=(X⊤X+ασ2I)−1X⊤y,m_N = (X^\top X + \alpha\sigma^2 I)^{-1}X^\top y ,

    the minimiser of ∥y−Xβ∥2+λ∥β∥2\|y - X\beta\|^2 + \lambda\|\beta\|^2 with λ=ασ2\lambda = \alpha\sigma^2. The posterior is Gaussian, so mNm_N is also the MAP estimate. Weight decay in a neural network is the same idea: a Gaussian prior on the weights.

    Two limits. With a flat prior (α→0\alpha \to 0), mN→β^m_N \to \hat\beta (OLS) and SN→σ2(X⊤X)−1S_N \to \sigma^2(X^\top X)^{-1}: the same matrix as the frequentist Cov⁡(β^)\operatorname{Cov}(\hat\beta). With known σ\sigma the 95% credible interval and the 95% confidence interval are then numerically equal, although they answer different questions. With much data, SNS_N shrinks like 1/n1/n and the predictive variance tends to the noise σ2\sigma^2, just like the prediction interval.

    Interactive figure: loading…

    Click in the plot to add data points; then move the prior precision α\alpha. Blue points are data. In aqua: the posterior mean line (thick), 12 lines sampled from the posterior (thin), and the 95% predictive band. The dashed grey line is least squares. "Clear points" shows the prior. A large α\alpha pulls the line toward 0 (strong ridge); a small α\alpha makes the mean line match least squares. Far from the data the band widens.

    The function-space view: a Gaussian process with a linear kernel

    Under the prior, (β,y)(\beta, y) is jointly Gaussian with Cov⁡(y)=α−1XX⊤+σ2I\operatorname{Cov}(y) = \alpha^{-1}XX^\top + \sigma^2 I and Cov⁡(β,y)=α−1X⊤\operatorname{Cov}(\beta, y) = \alpha^{-1}X^\top. Gaussian conditioning (lesson 05) gives mN=α−1X⊤(α−1XX⊤+σ2I)−1ym_N = \alpha^{-1}X^\top(\alpha^{-1}XX^\top + \sigma^2 I)^{-1}y. The push-through identity (αI+X⊤X/σ2)−1X⊤/σ2=α−1X⊤(α−1XX⊤+σ2I)−1(\alpha I + X^\top X/\sigma^2)^{-1}X^\top/\sigma^2 = \alpha^{-1}X^\top(\alpha^{-1}XX^\top + \sigma^2 I)^{-1} shows that the two forms agree. The second form only needs inner products xi⊤xk/αx_i^\top x_k/\alpha: this is a Gaussian process with the linear kernel k(x,x′)=x⊤x′/αk(x, x') = x^\top x'/\alpha. Replace the features by ϕ(x)\phi(x), or the kernel by any positive definite kernel, and you get GP regression (ml-for-science 07). The weight-space form solves a p×pp \times p system; the function-space form an n×nn \times n one.

    If σ2\sigma^2 is unknown too, a normal–inverse-gamma prior on (β,σ2)(\beta, \sigma^2) is conjugate. The predictive distribution is then a Student tt, the Bayesian counterpart of the tn−pt_{n-p} above.

    Quick check

    In Bayesian linear regression with prior β∼N(0,α−1I)\beta \sim \mathcal N(0, \alpha^{-1}I) and noise variance σ2\sigma^2, the posterior mean equals ridge regression with which penalty λ\lambda?

    Answers to section 1. (1) 4n4n points with the same design make SxxS_{xx} four times larger, so the standard error is divided by 4=2\sqrt 4 = 2. (2) Close to a fixed width: about ±1.96σ\pm 1.96\sigma (the noise of the new point does not shrink). (3) Yes. With n=1000n = 1000, R2=0.02R^2 = 0.02 gives t=4.51t = 4.51 and p≈7⋅10−6p \approx 7 \cdot 10^{-6}; with larger nn the pp-value is even smaller.

    4. Worked example #

    Back to the five students. Every number below is checked in section 5.

    Step 1: the matrices. With the intercept column,

    X=(1112131415),X⊤X=(5151555),X⊤y=(2+4+5+4+52+8+15+16+25)=(2066).X = \begin{pmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \\ 1 & 4 \\ 1 & 5 \end{pmatrix}, \qquad X^\top X = \begin{pmatrix} 5 & 15 \\ 15 & 55 \end{pmatrix}, \qquad X^\top y = \begin{pmatrix} 2 + 4 + 5 + 4 + 5 \\ 2 + 8 + 15 + 16 + 25 \end{pmatrix} = \begin{pmatrix} 20 \\ 66 \end{pmatrix}.

    Step 2: the coefficients. det⁡(X⊤X)=5⋅55−152=50\det(X^\top X) = 5 \cdot 55 - 15^2 = 50, so

    (X⊤X)−1=150(55−15−155),β^=150(55⋅20−15⋅66−15⋅20+5⋅66)=150(11030)=(2.20.6).(X^\top X)^{-1} = \frac{1}{50}\begin{pmatrix} 55 & -15 \\ -15 & 5 \end{pmatrix}, \qquad \hat\beta = \frac{1}{50}\begin{pmatrix} 55 \cdot 20 - 15 \cdot 66 \\ -15 \cdot 20 + 5 \cdot 66 \end{pmatrix} = \frac{1}{50}\begin{pmatrix} 110 \\ 30 \end{pmatrix} = \begin{pmatrix} 2.2 \\ 0.6 \end{pmatrix}.

    Step 3: residuals. Fitted values y^=2.2+0.6x=(2.8,3.4,4.0,4.6,5.2)\hat y = 2.2 + 0.6x = (2.8, 3.4, 4.0, 4.6, 5.2), so e=(−0.8,0.6,1.0,−0.6,−0.2)e = (-0.8, 0.6, 1.0, -0.6, -0.2). Check: ∑ei=0\sum e_i = 0 and ∑xiei=−0.8+1.2+3.0−2.4−1.0=0\sum x_i e_i = -0.8 + 1.2 + 3.0 - 2.4 - 1.0 = 0 (the residuals are orthogonal to both columns). RSS=0.64+0.36+1+0.36+0.04=2.4\text{RSS} = 0.64 + 0.36 + 1 + 0.36 + 0.04 = 2.4.

    Step 4: noise variance and standard errors. n−p=3n - p = 3, so s2=2.4/3=0.8s^2 = 2.4/3 = 0.8. The estimated covariance is

    s2(X⊤X)−1=0.850(55−15−155)=(0.88−0.24−0.240.08),s^2(X^\top X)^{-1} = \frac{0.8}{50}\begin{pmatrix} 55 & -15 \\ -15 & 5 \end{pmatrix} = \begin{pmatrix} 0.88 & -0.24 \\ -0.24 & 0.08 \end{pmatrix},

    so SE⁡(β^0)=0.88=0.938\operatorname{SE}(\hat\beta_0) = \sqrt{0.88} = 0.938 and SE⁡(β^1)=0.08=0.283\operatorname{SE}(\hat\beta_1) = \sqrt{0.08} = 0.283. (Check with the simple formula: Sxx=4+1+0+1+4=10S_{xx} = 4 + 1 + 0 + 1 + 4 = 10 and 0.8/10=0.283\sqrt{0.8/10} = 0.283.)

    Step 5: test and interval for the slope. t=0.6/0.283=2.12t = 0.6/0.283 = 2.12 with 3 degrees of freedom; the two-sided pp-value is 0.1240.124. With t3, 0.975=3.182t_{3,\,0.975} = 3.182, the 95% confidence interval is 0.6±3.182⋅0.283=0.6±0.90=(−0.30, 1.50)0.6 \pm 3.182 \cdot 0.283 = 0.6 \pm 0.90 = (-0.30,\ 1.50). It contains 0: five students are not enough to show that studying helps, even though the estimate is positive.

    Step 6: R2R^2 and FF. yˉ=4\bar y = 4, so TSS=4+0+1+0+1=6\text{TSS} = 4 + 0 + 1 + 0 + 1 = 6 and R2=1−2.4/6=0.6R^2 = 1 - 2.4/6 = 0.6. Adjusted R2=1−(2.4/3)/(6/4)=0.467R^2 = 1 - (2.4/3)/(6/4) = 0.467. The overall F=(6−2.4)/12.4/3=4.5=t2F = \frac{(6 - 2.4)/1}{2.4/3} = 4.5 = t^2, with the same p=0.124p = 0.124.

    Step 7: the two intervals at a new x0x_0. h0=15+(x0−3)210h_0 = \frac15 + \frac{(x_0 - 3)^2}{10} and s=0.8=0.894s = \sqrt{0.8} = 0.894.

    x0x_0 y^0\hat y_0 h0h_0 SE of the mean sh0s\sqrt{h_0} 95% CI for the mean SE for a new yy: s1+h0s\sqrt{1 + h_0} 95% prediction interval
    3 4.0 0.2 0.40 4.0±1.27=(2.73,5.27)4.0 \pm 1.27 = (2.73, 5.27) 0.98 4.0±3.12=(0.88,7.12)4.0 \pm 3.12 = (0.88, 7.12)
    6 5.8 1.1 0.94 5.8±2.99=(2.81,8.79)5.8 \pm 2.99 = (2.81, 8.79) 1.30 5.8±4.12=(1.68,9.92)5.8 \pm 4.12 = (1.68, 9.92)

    At x0=6x_0 = 6 we extrapolate outside the data, and the confidence interval is more than twice as wide as at xˉ=3\bar x = 3. The prediction interval is wide in both places, because one student's score is noisy.

    Step 8: the Bayesian version. Take one feature without intercept, prior precision α=1\alpha = 1, noise variance σ2=1\sigma^2 = 1, data x=(1,2)x = (1, 2), y=(1,3)y = (1, 3). Then X⊤X=1+4=5X^\top X = 1 + 4 = 5 and X⊤y=1+6=7X^\top y = 1 + 6 = 7.

    • SN=1/(α+5/σ2)=1/6S_N = 1/(\alpha + 5/\sigma^2) = 1/6 and mN=SN⋅7/σ2=7/6≈1.167m_N = S_N \cdot 7/\sigma^2 = 7/6 \approx 1.167.
    • Ridge with λ=ασ2=1\lambda = \alpha\sigma^2 = 1: 7/(5+1)=7/67/(5 + 1) = 7/6. Least squares gives 7/5=1.47/5 = 1.4: the prior shrinks the slope toward 0.
    • Predictive at x0x_0: mean 76x0\frac76 x_0, variance 1+x02/61 + x_0^2/6. At x0=1.5x_0 = 1.5: 1.3751.375, of which only 0.3750.375 is uncertainty about the slope. At x0=10x_0 = 10: 17.6717.67, of which 94% is uncertainty about the slope.
    Quick check

    In the exam example, a sixth student studies x=3x = 3 hours. Which interval should you report for this student's score, and roughly how wide is it?

    5. In code #

    NumPy and SciPy check the worked example. scipy.stats.linregress is the 1-D cross-check.

    import numpy as np
    from scipy import stats
    
    x = np.array([1., 2, 3, 4, 5])                 # hours of study
    y = np.array([2., 4, 5, 4, 5])                 # exam score
    X = np.column_stack([np.ones_like(x), x])      # intercept column + x
    n, p = X.shape
    
    Q, R = np.linalg.qr(X)                         # least squares through QR, no inverse of X^T X
    beta = np.linalg.solve(R, Q.T @ y)
    e = y - X @ beta
    s2 = e @ e / (n - p)                           # unbiased estimate of sigma^2
    XtX_inv = np.linalg.inv(R.T @ R)               # small p: fine for the standard errors
    se = np.sqrt(s2 * np.diag(XtX_inv))
    t = beta / se
    pval = 2 * stats.t.sf(np.abs(t), df=n - p)
    tq = stats.t.ppf(0.975, df=n - p)
    print(beta.round(3), round(e @ e, 3), round(s2, 3))          # [2.2 0.6] 2.4 0.8
    print(se.round(3), t.round(3), pval.round(3))                # [0.938 0.283] [2.345 2.121] [0.101 0.124]
    print((beta[1] - tq * se[1]).round(2), (beta[1] + tq * se[1]).round(2))   # -0.3 1.5
    
    R2 = 1 - e @ e / np.sum((y - y.mean())**2)
    lr = stats.linregress(x, y)                    # the 1-D check
    print(round(R2, 3), round(lr.slope, 3), round(lr.stderr, 3), round(lr.pvalue, 3))   # 0.6 0.6 0.283 0.124
    
    for x0 in (3.0, 6.0):                          # half-widths: CI for the mean, prediction interval
        v = np.array([1, x0]) @ XtX_inv @ np.array([1, x0])
        print(x0, round(beta[0] + beta[1] * x0, 2), (tq * np.sqrt(s2 * v)).round(2), (tq * np.sqrt(s2 * (1 + v))).round(2))
    # 3.0 4.0 1.27 3.12
    # 6.0 5.8 2.99 4.12
    
    # Bayesian linear regression = ridge with lambda = alpha * sigma^2
    alpha, sigma2 = 1.0, 0.8
    S_N = np.linalg.inv(alpha * np.eye(p) + X.T @ X / sigma2)
    m_N = S_N @ X.T @ y / sigma2
    ridge = np.linalg.solve(X.T @ X + alpha * sigma2 * np.eye(p), X.T @ y)
    print(m_N.round(3), np.allclose(m_N, ridge))   # [1.277 0.839] True
    

    The last line has a lesson of its own: this prior shrinks the intercept toward 0 too, and the slope grows to compensate. In practice one usually centres yy and the features, or leaves the intercept without a prior.

    6. Where it shows up #

    • Experiments and A/B tests. The treatment effect is the coefficient of a 0/1 treatment feature; adding pre-experiment covariates is regression adjustment (CUPED), which shrinks the standard error by about 1−ρ2\sqrt{1 - \rho^2} (lesson 12). A two-sample tt-test is exactly a regression on a group indicator.
    • Scaling laws and empirical fits in ML. A power law L=aC−bL = aC^{-b} is a line in log–log coordinates. The standard error of the slope bb and the prediction interval tell you how far the fit can be trusted, and extrapolation is the case x0x_0 far from xˉ\bar x, where both bands are widest.
    • Linear probes and attribution. Regressing a property on network activations is linear regression; with thousands of correlated features, multicollinearity makes single coefficients meaningless, so people use ridge.
    • Bayesian last layers and uncertainty. Bayesian linear regression on learned features gives cheap predictive uncertainty; with random Fourier features it approximates a Gaussian process. Thompson sampling with a linear model samples β\beta from N(mN,SN)\mathcal N(m_N, S_N) (reinforcement learning 03).
    • Trends in science. A warming trend in temperature data is a regression slope. The residuals of climate and weather series are autocorrelated, so the classical standard error is too small and the trend looks more significant than it is; corrected (HAC) standard errors or an effective sample size are needed.
    • Calibration of instruments. Fitting a sensor's response against known standards, then predicting the unknown quantity with an interval, is a textbook use of the prediction interval.

    7. Common mistakes #

    • Using the confidence interval for a single prediction. It covers the mean response only. A new observation needs the prediction interval, which includes σ2\sigma^2.
    • Dividing RSS by nn. That is the MLE and it is biased low; use n−pn - p, especially when pp is not small compared with nn.
    • Reading a small pp-value as a large effect. With large nn, tiny effects are significant. Report the estimate and its confidence interval, and look at R2R^2 or the size of the effect.
    • Trusting classical standard errors without looking at the residuals. Curvature biases the coefficients; heteroscedasticity and correlated errors make the standard errors wrong. Plot the residuals first.
    • Interpreting single coefficients under strong collinearity. Their signs can flip between similar data sets. Look at the VIF, or at combinations that are well determined.
    • Reading a coefficient as a causal effect. It is an association given the included features. Omitted confounders bias it, whatever the standard error.
    • Comparing R2R^2 across models with different numbers of features. R2R^2 always rises when features are added; use adjusted R2R^2, an FF-test or held-out error.
    • Forming (X⊤X)−1(X^\top X)^{-1} to fit the model. Solve with QR (or np.linalg.lstsq); the explicit inverse squares the condition number.

    8. Check yourself #

    1. Under A1–A3, show that the fitted values satisfy Cov⁡(y^)=σ2H\operatorname{Cov}(\hat y) = \sigma^2 H and the residuals Cov⁡(e)=σ2(I−H)\operatorname{Cov}(e) = \sigma^2(I - H). What does this say about the variance of a residual with high leverage?
      Answery^=Hy=Xβ+Hε\hat y = Hy = X\beta + H\varepsilon, so Cov⁡(y^)=Hσ2IH⊤=σ2H\operatorname{Cov}(\hat y) = H\sigma^2 IH^\top = \sigma^2 H (HH is symmetric and idempotent). e=(I−H)εe = (I - H)\varepsilon, so Cov⁡(e)=σ2(I−H)\operatorname{Cov}(e) = \sigma^2(I - H) and Var⁡(ei)=σ2(1−hii)\operatorname{Var}(e_i) = \sigma^2(1 - h_{ii}). A point with leverage close to 1 has a residual with variance close to 0: the line goes through it. This is why studentised residuals divide by s1−hiis\sqrt{1 - h_{ii}}.
    2. A regression on n=30n = 30 points with p=4p = 4 columns has RSS=52\text{RSS} = 52. Estimate σ\sigma. A coefficient has β^j=1.1\hat\beta_j = 1.1 and [(X⊤X)−1]jj=0.25[(X^\top X)^{-1}]_{jj} = 0.25. Is it significant at the 5% level?
      Answers2=52/26=2s^2 = 52/26 = 2, so s=1.414s = 1.414. SE⁡j=1.414⋅0.25=0.707\operatorname{SE}_j = 1.414 \cdot \sqrt{0.25} = 0.707, t=1.1/0.707=1.56t = 1.1/0.707 = 1.56 with 26 degrees of freedom. t26, 0.975=2.056>1.56t_{26,\,0.975} = 2.056 > 1.56, so no (p≈0.13p \approx 0.13).
    3. Why is the prediction band of simple regression curved (a hyperbola), and not two parallel lines?
      AnswerThe variance of the fitted line at x0x_0 is σ2(1n+(x0−xˉ)2Sxx)\sigma^2\big(\frac1n + \frac{(x_0 - \bar x)^2}{S_{xx}}\big): the uncertain slope moves the line more the farther you are from xˉ\bar x. The half-width is the square root of a quadratic in x0x_0, which is a hyperbola. Only the noise term σ2\sigma^2 is the same everywhere.
    4. You fit yy on x1x_1 and x2x_2 with correlation 0.950.95. Both tt-statistics are about 1, but the overall FF-test has p<10−6p < 10^{-6}. Explain.
      AnswerEach tt-test asks whether one coefficient is 0 *given* the other feature. With correlated features either one alone explains yy, so neither adds much given the other, and their SEs are inflated (VIF ≈10\approx 10). The FF-test asks whether both are 0, and together they clearly explain yy. The sum of the coefficients is well determined; the split between them is not.
    5. In Bayesian linear regression, what happens to mNm_N and SNS_N when α→∞\alpha \to \infty? And when the data set grows?
      Answerα→∞\alpha \to \infty: SN≈α−1I→0S_N \approx \alpha^{-1}I \to 0 and mN→0m_N \to 0; the prior wins and the data are ignored. As nn grows (with well-spread xx), X⊤XX^\top X grows like nn, so SN→0S_N \to 0 like 1/n1/n and mN→m_N \to the OLS estimate: the data win. The predictive variance tends to σ2\sigma^2.
    6. Why does β^\hat\beta stay unbiased under heteroscedastic errors, while its standard error does not?
      AnswerUnbiasedness uses only E[ε]=0\mathbb{E}[\varepsilon] = 0: E[β^]=β+A E[ε]=β\mathbb{E}[\hat\beta] = \beta + A\,\mathbb{E}[\varepsilon] = \beta. The covariance uses Cov⁡(ε)=σ2I\operatorname{Cov}(\varepsilon) = \sigma^2 I; with Cov⁡(ε)=Ω\operatorname{Cov}(\varepsilon) = \Omega it becomes AΩA⊤A\Omega A^\top, which the formula s2(X⊤X)−1s^2(X^\top X)^{-1} does not estimate. The sandwich estimator does.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Write the OLS estimator and its covariance under Cov⁡(ε)=σ2I\operatorname{Cov}(\varepsilon) = \sigma^2 I.

    2. What is the variance of the slope in simple regression?

    3. Why does the unbiased noise estimate divide RSS by n−pn - p?

    4. What is the tt-statistic for H0:βj=0H_0: \beta_j = 0, and its null distribution?

    5. How do the confidence interval for the mean and the prediction interval for a new yy at x0x_0 differ?

    6. Define R2R^2.

    7. State the Gauss–Markov theorem in one sentence.

    8. Which ridge penalty gives the posterior mean of Bayesian linear regression with prior N(0,α−1I)\mathcal N(0, \alpha^{-1}I)?

    9. What is the predictive variance of Bayesian linear regression at x0x_0?

    10. Two features have correlation 0.99. By how much are the standard errors of their coefficients inflated?

    Open the review →

    9. Interview angle #

    • "What are the assumptions of linear regression, and which ones matter for what?" — Linear mean (else biased coefficients); uncorrelated, constant-variance errors (else wrong standard errors, though β^\hat\beta stays unbiased); Gaussian errors (only for exact small-sample tt and FF tests); full-rank XX (else β^\hat\beta is not unique). Check them with residual plots.
    • "Derive the variance of β^\hat\beta." — β^=β+(X⊤X)−1X⊤ε\hat\beta = \beta + (X^\top X)^{-1}X^\top\varepsilon, and Cov⁡(Aε)=σ2AA⊤=σ2(X⊤X)−1\operatorname{Cov}(A\varepsilon) = \sigma^2 AA^\top = \sigma^2(X^\top X)^{-1}.
    • "Confidence interval vs prediction interval?" — Mean response vs one new observation; the second adds σ2\sigma^2 and does not shrink to zero.
    • "Your coefficient has p=0.001p = 0.001 but R2=0.01R^2 = 0.01. What do you tell the product team?" — There is very likely an association, but xx explains about 1% of the variation of yy; report the effect size with its interval, and do not claim the model predicts well. Check for confounders before claiming a causal effect.
    • "What is multicollinearity and how do you detect it?" — Correlated features inflate the variance of single coefficients (VIF=1/(1−Rj2)\text{VIF} = 1/(1 - R_j^2)); predictions are fine. Detect with VIFs or the condition number of XX; fix with ridge, by combining features, or by dropping one.
    • "Derive ridge regression from a Bayesian model." — Gaussian likelihood and prior N(0,α−1I)\mathcal N(0, \alpha^{-1}I); the negative log-posterior is 12σ2∥y−Xβ∥2+α2∥β∥2\frac{1}{2\sigma^2}\|y - X\beta\|^2 + \frac\alpha2\|\beta\|^2, whose minimiser is ridge with λ=ασ2\lambda = \alpha\sigma^2.
    • "Why is OLS called BLUE?" — Gauss–Markov; also say what it does not claim (biased estimators like ridge can have lower MSE).

    10. Practice #

    The notebook for this lesson has five exercises, each with a check cell and a folded solution:

    1. ols_table: coefficients, standard errors, tt-values and pp-values from scratch, checked against scipy.stats.linregress and against a simulation of the coefficient spread.
    2. Coverage of the 95% confidence interval for the slope by simulation, with Gaussian and with heteroscedastic errors (classical and robust standard errors).
    3. Coverage of the confidence interval for the mean and of the prediction interval for a new observation.
    4. blr_posterior and blr_predictive, with the check that mNm_N equals sklearn.linear_model.Ridge(alpha=α·σ², fit_intercept=False).
    5. The diabetes data set (sklearn.datasets.load_diabetes): a coefficient table, VIFs and a residual plot.

    11. Watch and read #

    The least-squares estimator as a projection, and its distribution under Gaussian noise.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Tests and confidence intervals for the coefficients, with the tt and χ2\chi^2 distributions.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A visual tour of least squares, R2R^2 and the FF-test with small examples.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play