Mathematical Foundations

V.7 · Statistics

Where do the residuals go when a line fits?

Move actual observations, derive the least-squares line from their centered sums, and inspect predictions, signed residuals, RSS and nonidentifiable coefficients.

Fit actual observations; inspect every residual

Actual pairs: (-3, -1); (-1, 0); (0, 1); (1, 2); (3, 3). Least-squares slope = 0.7, intercept = 1; residual sum of squares = 0.2.

Select a pair, drag its handle or use arrow keys. Numeric x and y inputs edit the same observation. Shift makes a larger keyboard step.

Actual observations, exact fitted values and residuals
ixyPredictionResidual y − ŷ
1-3-1−1.10.1
2-100.3−0.3
30110
4121.70.3
5333.1−0.1

Actual pairs: (-3, -1); (-1, 0); (0, 1); (1, 2); (3, 3). Least-squares slope = 0.7, intercept = 1; residual sum of squares = 0.2.

Least-squares slope
0.7
Least-squares intercept
1
Residual sum of squares
0.2
Residual sum
0
Residual orthogonality to x
0
Observed linear correlation
0.989949

= exact finite-data/model quantity · ≈ binary64 approximation; empirical results describe this run

from −8 to 8, up to 2 decimal places

from −8 to 8, up to 2 decimal places

Least-squares slope = 0.7, intercept = 1; residual sum of squares = 0.2.

b=SxySxx=0.7,a=yˉ−bxˉ=1b=\frac{S_{xy}}{S_{xx}}=0.7,\quad a=\bar y-b\bar x=1
RSS⁡=∑i(yi−y^i)2=0.2\operatorname{RSS}=\sum_i(y_i-\hat y_i)^2=0.2

Read and center actual observations

Observed center = (0, 1).

μ=∑ipixi\mu=\sum_i p_i x_i

Move actual observations, derive the least-squares line from their centered sums, and inspect predictions, signed residuals, RSS and nonidentifiable coefficients.

Intuition

The observed y values need not lie on a line. A fitted prediction lives on the line at each observed x; the vertical gap is a signed residual. Least squares chooses a line that minimizes the total squared vertical gaps, not orthogonal distances to the line.

Definition

For y^i=a+bxi\hat y_i=a+bx_i, residuals are ri=yi−y^ir_i=y_i-\hat y_i and RSS⁡(a,b)=∑iri2\operatorname{RSS}(a,b)=\sum_i r_i^2. Simple regression here includes an intercept and uses equal observation weights. If Sxx=∑i(xi−xˉ)2>0S_{xx}=\sum_i(x_i-\bar x)^2>0, coefficients are unique. Correlation summarizes standardized linear association; RSS is an unstandardized fit criterion.

Mechanics

Select and move any observation using the same input paths. The plot shows the actual pairs, derived line and residual segments; the table lists exact predictions and signed residuals. Compare the canonical noisy dataset with a noiseless line, an outlier and a dataset with identical x coordinates.

Derivation

Setting the RSS derivatives to zero gives ∑iri=0\sum_i r_i=0 and ∑ixiri=0\sum_i x_i r_i=0. Solve them to obtain b=Sxy/Sxxb=S_{xy}/S_{xx} and a=yˉ−bxˉa=\bar y-b\bar x. In the earlier projection language, the design matrix has columns of ones and observed x values; fitted y is the projection onto their span, and residuals are orthogonal to both columns.

Worked examples

For x=[−3,−1,0,1,3], y=[−1,0,1,2,3], means are (0,1), Sxx=20S_{xx}=20 and Sxy=14S_{xy}=14. Thus b=7/10b=7/10 and a=1a=1. Residuals are [1/10,−3/10,0,3/10,−1/10][1/10,-3/10,0,3/10,-1/10], with RSS⁡=1/5\operatorname{RSS}=1/5. At x=3, prediction is 31/10 and the observed residual is −1/10.

Worked example: Fit actual observations; inspect every residual

Actual pairs: (-3, -1); (-1, 0); (0, 1); (1, 2); (3, 3). Least-squares slope = 0.7, intercept = 1; residual sum of squares = 0.2.

Select a pair, drag its handle or use arrow keys. Numeric x and y inputs edit the same observation. Shift makes a larger keyboard step.

Actual observations, exact fitted values and residuals
ixyPredictionResidual y − ŷ
1-3-1−1.10.1
2-100.3−0.3
30110
4121.70.3
5333.1−0.1

Actual pairs: (-3, -1); (-1, 0); (0, 1); (1, 2); (3, 3). Least-squares slope = 0.7, intercept = 1; residual sum of squares = 0.2.

Least-squares slope
0.7
Least-squares intercept
1
Residual sum of squares
0.2
Residual sum
0
Residual orthogonality to x
0
Observed linear correlation
0.989949

= exact finite-data/model quantity · ≈ binary64 approximation; empirical results describe this run

from −8 to 8, up to 2 decimal places

from −8 to 8, up to 2 decimal places

Least-squares slope = 0.7, intercept = 1; residual sum of squares = 0.2.

b=SxySxx=0.7,a=yˉ−bxˉ=1b=\frac{S_{xy}}{S_{xx}}=0.7,\quad a=\bar y-b\bar x=1
RSS⁡=∑i(yi−y^i)2=0.2\operatorname{RSS}=\sum_i(y_i-\hat y_i)^2=0.2

Read and center actual observations

Observed center = (0, 1).

μ=∑ipixi\mu=\sum_i p_i x_i

Inspect the actual mathematical steps and replay their immutable states.

Executable reference code

Run the exact mechanics and the NumPy companion. Both use literal assertions on the worked examples; simulations are never conditioned on a favorable coverage or fit outcome.

code/python/statistics_regression.py
"""Runnable regression reference, assumptions explicit."""
from fractions import Fraction as F
x=list(map(F,[-3,-1,0,1,3]));y=list(map(F,[-1,0,1,2,3]));n=len(x)
mx=sum(x)/n;my=sum(y)/n
xx=sum((a-mx)**2 for a in x);xy=sum((a-mx)*(b-my) for a,b in zip(x,y))
slope=xy/xx if xx else None
intercept=my-slope*mx if slope is not None else None
predicted=[intercept+slope*a for a in x] if slope is not None else [my]*n
residual=[b-p for b,p in zip(y,predicted)]
rss=sum(r*r for r in residual)
assert (slope,intercept,rss)==(F(7,10),F(1),F(1,5))
assert sum(residual)==0 and sum(a*r for a,r in zip(x,residual))==0
print(slope,intercept,rss)
code/python/statistics_regression_numpy.py
"""Runnable regression reference, assumptions explicit."""
import numpy as np
x=np.array([-3,-1,0,1,3],dtype=float);y=np.array([-1,0,1,2,3],dtype=float)
design=np.column_stack([np.ones(len(x)),x])
coefficients,_,rank,_=np.linalg.lstsq(design,y,rcond=None)
residual=y-design@coefficients
assert rank==2 and np.allclose(coefficients,[1,.7])
assert np.allclose(design.T@residual,0) and np.isclose(residual@residual,.2)
print(coefficients, residual@residual, 'rank:',rank)

Explore

Move the outlier and watch it influence slope, intercept and RSS. In the noiseless preset, RSS is zero. In the equal-x preset, determine which combination of a and b the data constrain. Reset and verify that residuals still sum to zero even though individual residuals do not.

Common mistakes and counterexamples

When all x values equal x₀, only a+b x₀ equals the mean y; slope and intercept are not individually identified. Fitted values at observed x and RSS remain meaningful, but a unique extrapolation line must not be invented. Low training RSS does not establish causation or guarantee reliable future predictions. Zero y variance makes correlation undefined even when a horizontal regression line is uniquely fitted.

Numerical considerations

Supported coordinates are bounded decimals represented exactly, so coefficients, predictions and residual identities use fractions. Drawing positions convert to binary64. Exact zero Sxx determines identifiability. Normal equations explain the geometry, but floating numerical software should normally use QR or SVD rather than explicitly invert the Gram matrix; the NumPy reference uses lstsq and exposes rank.

Engineering and ML connections

Least squares connects a statistical fit with the projection material from linear algebra. Prediction uncertainty requires assumptions about future noise and coefficient estimation; this descriptive fit does not manufacture a predictive interval. A useful model also needs validation beyond the training observations and a justified scope for extrapolation.

Exercises

Calculate from observed data and state the assumptions before interpreting a result. Corrective feedback identifies the corresponding misconception.

calculation

Canonical least squares

For canonical x=[-3,-1,0,1,3], y=[-1,0,1,2,3], give slope, intercept and RSS.

calculation

Prediction and residual

For fitted line ŷ=1+(7/10)x, observed point (3,3), give prediction and signed residual y−ŷ.

calculation

Projection checks

A unique least-squares line includes an intercept. Give Σrᵢ and Σxᵢrᵢ.

explanation

Nonidentifiable coefficients

All xᵢ=2 and y=[1,2,4]. What is determined?

Choose one answer

explanation

Fit versus causation

A small observed RSS means which claim is justified?

Choose one answer

Summary and checkpoints

Calculate coefficients from actual centered sums, inspect residuals and RSS, verify normal-equation identities and handle rank deficiency. Separate correlation, in-sample fit, prediction uncertainty and causal interpretation.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available