Skip to content
BIASED

Least squares

Linear regression as a global model with one weight per feature — the normal equations, the fit as a projection, Gaussian noise and the standard errors of the weights, collinearity, R² and its traps, robust losses.

One formula for all the data

The topic Nearest neighbours predicts from nearby examples. Least squares instead fits one rule for the whole sample. Its prediction is a(x)=w⊤xa(x)=w^\top x; a column of ones supplies an intercept. The design matrix X∈Rn×dX\in\mathbb R^{n\times d} contains the features, and y∈Rny\in\mathbb R^n contains the targets.

“Linear” means linear in the unknown weights. Columns may contain xx, x2x^2 or log⁡x\log x on its domain. Their values must be computable before choosing the weights. A weight inside ewxe^{wx} does not meet this condition.

The objective is the average squared residual,

Q(w)=1n∥Xw−y∥2.Q(w)=\frac1n\lVert Xw-y\rVert^2.

Multiplying it by a positive constant leaves its minimizer unchanged. Squared error has convenient geometry, but it also gives large residuals a large influence. We will connect the fitting rule, its assumptions and its validation.

The normal equations

Recall the normal equations from Mathematics for ML. Differentiating the residual sum of squares gives 2X⊤(Xw−y)2X^\top(Xw-y). Setting this to zero gives

X⊤Xw^=X⊤y.X^\top X\hat w=X^\top y.

If the columns are independent, X⊤XX^\top X is positive definite and the solution is unique. If columns are dependent, several weight vectors give the same fitted values. Having at least as many rows as columns is necessary for full column rank, but is not sufficient.

For four points x=(0,1,2,3)x=(0,1,2,3), y=(1,3,2,5)y=(1,3,2,5), fit an intercept and slope. Then

X⊤X=(46614),X⊤y=(1122).X^\top X=\begin{pmatrix}4&6\\6&14\end{pmatrix},\qquad X^\top y=\begin{pmatrix}11\\22\end{pmatrix}.

Solving gives w^=(1.1,1.1)\hat w=(1.1,1.1). Residuals r=y−Xw^r=y-X\hat w are (−0.1,0.8,−1.3,0.6)(-0.1,0.8,-1.3,0.6), with sum of squares 2.72.7. These are a small explicit calculation, not a measured benchmark. The formula explains the result; a numerical implementation should normally factorize XX with QR or SVD.

The fit as a projection

The normal equations also say X⊤r=0X^\top r=0: the residual is orthogonal to every feature column. Predictions lie in the column space of XX, and the fit is the closest point in that space to yy. This orthogonality is in the space of all nn targets, not an angle between a residual segment and a line in an ordinary scatter plot.

For any alternative weights ww, Pythagoras gives

∥y−Xw∥2=∥y−Xw^∥2+∥X(w^−w)∥2.\lVert y-Xw\rVert^2=\lVert y-X\hat w\rVert^2+\lVert X(\hat w-w)\rVert^2.

For the four-point data, the alternative w=(1,1)w=(1,1) has squared error 3.0=2.7+0.33.0=2.7+0.3. The extra term measures the distance between its predictions and the fitted predictions.

With independent columns, the projection matrix H=X(X⊤X)−1X⊤H=X(X^\top X)^{-1}X^\top satisfies H2=HH^2=H and H⊤=HH^\top=H. Its trace is dd, counting the intercept if present. With an intercept, the residuals sum to zero because they are orthogonal to the column of ones. These identities concern the fitting data, not arbitrary future observations.

Gaussian noise and standard errors

The topic Maximum likelihood supplies a statistical interpretation. If y=Xw∗+εy=Xw_*+\varepsilon and the errors are independent N(0,σ2)\mathcal N(0,\sigma^2), minimizing squared error maximizes the likelihood. Gaussian noise is not required just to solve least squares.

For a fixed full-rank design, E[ε∣X]=0E[\varepsilon\mid X]=0 makes the coefficients unbiased. The additional condition Cov⁡(ε∣X)=σ2I\operatorname{Cov}(\varepsilon\mid X)=\sigma^2I gives

Cov⁡(w^∣X)=σ2(X⊤X)−1.\operatorname{Cov}(\hat w\mid X)=\sigma^2(X^\top X)^{-1}.

Gaussian errors additionally give an exactly Gaussian coefficient distribution. Unequal or correlated errors invalidate this covariance formula, even if the conditional mean remains zero.

With n>dn>d, estimate σ2\sigma^2 by RSS/(n−d)\mathrm{RSS}/(n-d). The standard error of a coefficient is the square root of the corresponding diagonal of σ^2(X⊤X)−1\hat\sigma^2(X^\top X)^{-1}. For our four points, σ^2=1.35\hat\sigma^2=1.35 and the slope standard error is 1.35⋅0.2≈0.520\sqrt{1.35\cdot0.2}\approx0.520. This is uncertainty under repeated noise draws and the stated model, not a guarantee of future accuracy.

Collinearity and conditioning

If two columns are nearly equal, their sum is well observed but their difference is not. Large opposite weights can almost cancel in predictions. A small change in targets can then move individual coefficients substantially while predictions on similar inputs barely change. Such coefficients do not identify separate causal effects.

With exact duplicates, weights are not unique. SVD can choose a minimum-norm solution; this is a convention, not information supplied by the data. Ridge will add an explicit preference in Regularization.

There is a separate numerical issue. For full column rank,

κ(X⊤X)=κ(X)2.\kappa(X^\top X)=\kappa(X)^2.

Forming normal equations therefore worsens conditioning. Use a QR/SVD solver on XX rather than explicitly computing an inverse. Scaling can help when units differ, but it cannot remove exact dependence. Neither a more accurate solver nor more training iterations create information about a missing direction.

R² and its traps

For a nonconstant target, R2=1−RSS/TSSR^2=1-\mathrm{RSS}/\mathrm{TSS}, where TSS=∑i(yi−yˉ)2\mathrm{TSS}=\sum_i(y_i-\bar y)^2 uses the mean on the evaluated sample. Negative R2R^2 means worse squared error than that constant. Unconstrained least squares fitted with an intercept on these same data has 0≤R2≤10\le R^2\le1. This guarantee does not extend to a validation sample or every other fitted model.

Our original synthetic fixture has 240 rows and eight features. Independent standard-normal draws define x1=z1x_1=z_1, x2=z1+0.08z2x_2=z_1+0.08z_2, xj=zjx_j=z_j for the remaining features, and

y=20+4x1+4x2−3x3+2x4+4ε.y=20+4x_1+4x_2-3x_3+2x_4+4\varepsilon.

The noise ε\varepsilon is independent standard normal. Four auxiliary features have no true effect. Seed 20261113 fixes the dataset. It contains no observations of people or equipment.

Least squares reaches training R2=0.828R^2=0.828 and mean five-fold validation R2=0.812R^2=0.812. On the same folds, standardized nearest neighbours reaches 0.6950.695 at the best tried k=9k=9. The generator deliberately favours an additive rule; this is not a universal model ranking. Folds are shuffled with seed 17 and preprocessing is fitted inside each training fold. Selecting kk on those folds still requires a separate test or nested evaluation for a final estimate.

Outliers and robust losses

Squared error chooses the conditional mean; absolute error chooses a conditional median. For a constant fitted to 1,2,4,8,161,2,4,8,16, these are 6.26.2 and 44. A large target has a growing pull under squared error.

Huber's loss is quadratic near zero and linear outside a threshold:

ρδ(r)={r2/2,∣r∣≤δ,δ(∣r∣−δ/2),∣r∣>δ.\rho_\delta(r)=\begin{cases}r^2/2,&|r|\le\delta,\\\delta(|r|-\delta/2),&|r|>\delta.\end{cases}

Its derivative with respect to the residual is capped at δ\delta in magnitude. But the weight gradient also multiplies this derivative by the feature vector. An extreme input can still have substantial influence. Robustness to unusual target values does not imply protection from high-leverage inputs.

Absolute and Huber objectives generally need numerical optimization. Their predictions estimate a different target or trade efficiency for robustness. Inspect residuals and the data-generating process before interpreting a better loss value as a better scientific explanation.

What changed and what comes next

We have a global prediction rule, a fitting equation and clear limits on uncertainty and validation. The closed form is useful for derivations, but forming X⊤XX^\top X costs O(nd2)O(nd^2) and solving the dense system costs O(d3)O(d^3). A very large feature space makes this route expensive.

The next topic, Gradient descent, reaches a fit through steps. It changes how we optimize, not what the training data can establish. The optional notebook reproduces the four-point geometry and the original synthetic comparison; it does not count toward mastery.

This lesson is derived from the reviewed note, which retains primary references for regression, coefficient uncertainty and robust loss. The synthetic data, refreshed calculations and new checks were prepared for the Fedor Pakhurov project with Codex assistance.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Least squares: projection and validationoptional

    Check normal equations and residual orthogonality, then compare training and validation on original synthetic data.

    ~20 min · easier on a computer · Least squares topic read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.