AI Wiki中文/EN

Linear regression

线性回归

Derive least squares as projection, distinguish unique predictions from identifiable coefficients, and build an exact one-feature baseline.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Fit a trend, then inspect what it missed

Consider three invented jobs whose sizes are 1, 2 and 3 units and whose durations are 2, 2 and 5 minutes. A constant prediction of three minutes has total squared error six. Ordinary least squares fits the line y^=1.5x\widehat y=1.5x, reducing that training error to 1.5. It predicts 1.5, 3 and 4.5 minutes, leaving residuals 0.5, −1 and 0.5.

The line captures a trend but does not pass through every observation. Its slope summarizes a fitted association in these data; it is not automatically the causal effect of changing job size. At size four the line predicts six minutes. Whether that extrapolation is useful requires evidence beyond the three points used to fit it.

Linear regression predicts a numerical outcome using a weighted combination of features, usually with an intercept. “Linear” refers to the parameters: b+w1x+w2x2b+w_1x+w_2x^2 is still linear regression in (b,w1,w2)(b,w_1,w_2), even though its graph is curved in x. The feature transformation must be fixed when solving this linear problem. D2L, Section 3.1.1 · MML, nonlinear features in Section 9.2.1

One trend, three residuals

024601234xDuration y
The blue line is the fit; the gray dashed line is the constant baseline y=3. Blue filled points are used for fitting; the orange hollow point is held out. Short dashed segments show residuals. All data are constructed for teaching.

The residual is orthogonal to every fitted direction

Let A be an n×dn\times d design matrix whose rows contain the chosen features, including a column of ones if an intercept is fitted. Let θ contain the d coefficients and y∈Rny\in\mathbb R^n the observations. Ordinary least squares minimizes

J(θ)=12∥y−Aθ∥22,∇J=A⊤(Aθ−y),∇2J=A⊤A.J(\theta)=\frac12\|y-A\theta\|_2^2,\qquad \nabla J=A^\top(A\theta-y),\qquad \nabla^2J=A^\top A.

The factor one half simplifies derivatives. Dividing the whole objective by n changes neither its minimizers nor predictions. Using column-vector gradients, the stationary equation is

A⊤Aθ^=A⊤y,A⊤r=0,r=y−Aθ^.A^\top A\widehat\theta=A^\top y,\qquad A^\top r=0,\qquad r=y-A\widehat\theta.

Thus the residual has zero inner product with every design column. Geometrically, Aθ^A\widehat\theta is the orthogonal projection of y onto the column space of A. This also proves global optimality: for any perturbation δ,

∥y−A(θ^+δ)∥2=∥r∥2+∥Aδ∥2,\|y-A(\widehat\theta+\delta)\|^2=\|r\|^2+\|A\delta\|^2,

because the cross term vanishes. No probability model or normal-noise assumption was used in this algebra. MML, equations 9.10–9.12

If A has full column rank, A⊤AA^\top A is positive definite and the coefficients are unique. The often-written inverse formula (A⊤A)−1A⊤y(A^\top A)^{-1}A^\top y is valid under that condition. Merely having n≥d is not sufficient: rows (1,2), (2,4), and (3,6) are distinct, yet the second column is twice the first. The Hessian is then only positive semidefinite.

Even without full column rank, a least-squares minimizer exists and its fitted vector is unique. The pseudoinverse gives one minimum-norm solution; adding any vector in the null space of A gives the same training fit. Coefficients and predictions at new feature rows need not be unique. A new row outside the span of the training rows can distinguish these coefficient vectors. See the pseudoinverse for that separate choice of solution.

For one scalar feature with an intercept, differentiating in b first gives b=yˉ−wxˉb=\bar y-w\bar x. Substitute this into the slope equation to obtain

w^=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2,b^=yˉ−w^xˉ.\widehat w=\frac{\sum_i(x_i-\bar x)(y_i-\bar y)}{\sum_i(x_i-\bar x)^2},\qquad \widehat b=\bar y-\widehat w\bar x.

The denominator must be positive. If every x is equal, the data identify only the prediction at that common x, not a unique intercept and slope. In the opening example, xˉ=2\bar x=2, yˉ=3\bar y=3, the denominator is two and the numerator is three.

A complete one-feature baseline

The standard-library program fits that one-feature model using exact fractions. It checks paired lengths and rejects the non-identifiable constant-feature case. This is an intentionally small closed-form baseline, not a general matrix solver. Residual orthogonality gives a more informative correctness check than comparing just one rounded coefficient.

from fractions import Fraction as F

def rational(value):
    if type(value) is not int and not isinstance(value,F):
        raise ValueError("integer or Fraction observations required")
    return F(value)

def fit_line(xs, ys):
    x,y = tuple(map(rational,xs)),tuple(map(rational,ys))
    if not x or len(x)!=len(y):
        raise ValueError("nonempty paired observations required")
    n = len(x)
    xbar,ybar = sum(x)/n,sum(y)/n
    scatter = sum((v-xbar)**2 for v in x)
    if scatter==0:
        raise ValueError("constant x: slope and intercept are not separately identifiable")
    cross = sum((a-xbar)*(b-ybar) for a,b in zip(x,y))
    slope = cross/scatter
    intercept = ybar-slope*xbar
    return intercept,slope

x,y = [1,2,3],[2,2,5]
b,w = fit_line(x,y)
fitted = [b+w*v for v in x]
residual = [a-f for a,f in zip(y,fitted)]
assert (b,w)==(0,F(3,2))
assert residual==[F(1,2),F(-1),F(1,2)]
assert sum(residual)==sum(v*r for v,r in zip(x,residual))==0
assert sum(r*r for r in residual)==F(3,2)
assert sum((F(v)-3)**2 for v in y)==6
assert b+w*4==6
# An original held-out toy observation, not evidence of real-world performance.
heldout_x,heldout_y = 4,5
print("held-out squared error:",(b+w*heldout_x-heldout_y)**2)

The routine makes a constant number of passes over n observations: O(n) rational operations and O(n) storage because it copies both vectors. Fraction numerators and denominators add their own bit costs. A streaming covariance algorithm can reduce auxiliary storage for floating-point data. Avoid the naive difference of two huge sums when observations share a large offset; centered or stable online calculations reduce cancellation, although they cannot recover information already lost in input rounding.

For a dense, full-column-rank matrix with n≥d, QR least squares typically costs O(nd²); SVD is useful for diagnosing rank and selecting minimum-norm solutions. Forming normal equations costs O(nd²+d³) for the Gram matrix and solve, but for full column rank κ2(A⊤A)=κ2(A)2\kappa_2(A^\top A)=\kappa_2(A)^2. Prefer a tested QR/SVD solver when conditioning matters, and solve systems rather than explicitly forming inverses. The inverse formula explains the mathematics; it need not dictate the numerical implementation.

A held-out toy point at x=4, y=5 gives squared error one for the fitted line. That result is reported separately from training error. A real project should fix its split before fitting preprocessing, choose model settings using training/validation data, and reserve final test data for evaluation. Compare with a training-derived constant baseline under the same metric and split.

Algebraic residuals do not prove a noise model

Residual sums are zero when an intercept is included because the constant vector is a design column. This does not prove that the unobserved errors have conditional mean zero. If the true model is y=Aθ0+εy=A\theta_0+\varepsilon, A has full column rank, and E[ε∣A]=0E[\varepsilon\mid A]=0, then

θ^=θ0+(A⊤A)−1A⊤ε,E[θ^∣A]=θ0.\widehat\theta=\theta_0+(A^\top A)^{-1}A^\top\varepsilon,\qquad E[\widehat\theta\mid A]=\theta_0.

With the additional condition Cov⁡(ε∣A)=σ2I\operatorname{Cov}(\varepsilon\mid A)=\sigma^2I, its conditional covariance is σ2(A⊤A)−1\sigma^2(A^\top A)^{-1}. Normality is unnecessary for these two moment statements. Independent Gaussian errors with common positive variance supply a likelihood interpretation of least squares and, with further specified variance handling, exact normal-model inference. They are extra modeling assumptions, not facts established by minimizing squared error. D2L, Section 3.1.3

Heteroskedastic or correlated errors require a different covariance calculation. Outliers can dominate squared error; robust losses change the estimation problem. Missing confounders, reverse causation, and selection can make a coefficient unsuitable for causal interpretation even when prediction is useful.

Adding columns enlarges the set of possible fitted vectors, so the minimum training SSE cannot increase. Test error can. A flexible polynomial can interpolate distinct training inputs and still extrapolate badly; repeated input values with conflicting targets cannot all be interpolated by a deterministic function. Neither low training error nor a large number of observations alone guarantees generalization.

Use the residual to check the fit

  1. For the opening three jobs, verify that residuals sum to zero and are orthogonal to x. Answer: 1/2−1+1/2=01/2-1+1/2=0 and 1(1/2)+2(−1)+3(1/2)=01(1/2)+2(-1)+3(1/2)=0.
  2. All training x values are 2. Why does the slope formula fail? Answer: centered x values are zero, so its denominator is zero. Many pairs (b,w)(b,w) give the same b+2wb+2w; more repetitions at x=2 do not identify their separate values.
  3. Is y=b+w1x+w2sin⁡xy=b+w_1x+w_2\sin x a linear regression model? Answer: yes, if the sine feature is fixed. The unknown coefficients enter linearly. Estimating an unknown frequency inside the sine would create a different, nonlinear parameter problem.
  4. Does adding a feature guarantee lower test error? Answer: no. It guarantees only that the optimized training SSE cannot increase, because the old fit remains available by setting the new coefficient to zero.

Keep a baseline that you can explain

Linear models provide a useful reference for tabular prediction, numerical baselines, and more complex feature representations. Their transparency comes from being able to state the features, objective, solver, and evaluation protocol; coefficient tables alone do not establish scientific explanations.

Ridge regression makes coefficient selection unique even with redundant penalized features, at the cost of bias and a tuning decision. Lasso introduces a different penalty that can select features. Weighted least squares, generalized least squares, robust regression, and generalized linear models change different parts of the setup; identify which assumption or loss you need to change before choosing the extension.

Make a prediction, then check

Do more observations than features and distinct data rows ensure full column rank?

Choose one answer

Learning objectives

  • Derive normal equations from residual orthogonality and distinguish unique coefficients, fitted values and new-point predictions.
  • Implement an exact one-feature baseline and distinguish least-squares algebra, statistical assumptions and held-out evaluation.

Prerequisites & connections

Explore related knowledge →

References

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. Dive into Deep Learning — Linear Regression
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.

  • Used multiple exact-rational datasets to check residual orthogonality and global objective-difference identities; enumerated independent ±1 noises to verify conditional unbiasedness, covariance and a heteroskedastic counterexample.
  • Checked large-integer translations, unit changes, constant features and invalid inputs; all three training points, baseline, fitted line and held-out point in the figure match the program.
  • Another agent independently reviewed sources and three equivalent coefficient vectors for a rank-deficient design: identical training fits but different predictions outside the row space. The parent merged existing and new prerequisites without dropping old dependencies.
  • The parent executed all 37 independent classical-method checks successfully; bilingual code, display equations, six main anchors and four answered exercises were individually compared.
  • After inspecting the desktop preview, added visible legend text for the blue fit and gray constant baseline; numerical values and coordinates are unchanged, and the component hash records the reviewed update.

Source locations checked:

  • Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · 2024-01-15 draft, PDF299–307 (printed293–301), especially 9.10–9.19 and feature construction. PDF300 visually checked. Corrected the overbroad full-rank/uniqueness aside: distinct rows and n>=d do not ensure full column rank. Used column gradients and the correct Hessian scaling for the explicitly chosen objective.
  • Dive into Deep Learning — Linear Regression · Sections3.1.1.1–3.1.1.3, equations3.1.2–3.1.8 and Section3.1.3 Gaussian likelihood: row-design model, intercept column, full-column-rank restriction and numerical versus analytic solution distinction. Actual online text read.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.