Mathematical Foundations

II.18 · Linear Algebra

What is the closest answer when no exact answer exists?

Move three observations and watch a fitted line, residual segments and squared error update. Then build an orthogonal basis and inspect projection onto the column space, including dependent and zero-vector failures.

Find the closest reachable data vector

Move the data; minimize vertical squared residuals

Unique least-squares minimizer: x = (4/3, 1). The minimum residual is nonzero: (−1/3, 2/3, −1/3); minimizing it does not solve every equation. Aᵀ(b − Ax) = 0 exactly.

Column-space/design matrix
[1, −1; 1, 0; 1, 1]
Independent columns
2
One minimizing coefficient vector
(4/3, 1)
Projection of the data onto col(A)
(1/3, 4/3, 7/3)
Residual b − Ax
(−1/3, 2/3, −1/3)
Minimum squared error
2/30.666667…
Exact residual orthogonality
(0, 0)

Exact values use =; numerical companions use ≈. Rank and zero decisions are exact.

Unique least-squares minimizer: x = (4/3, 1). The minimum residual is nonzero: (−1/3, 2/3, −1/3); minimizing it does not solve every equation. Aᵀ(b − Ax) = 0 exactly.

A=[1−11011],b=[022]A=\begin{bmatrix}1&-1\\1&0\\1&1\end{bmatrix},\quad b=\begin{bmatrix}0\\2\\2\end{bmatrix}
b=[134373]+[−1323−13]\mathbf b=\begin{bmatrix}\frac{1}{3}\\\frac{4}{3}\\\frac{7}{3}\end{bmatrix}+\begin{bmatrix}-\frac{1}{3}\\\frac{2}{3}\\-\frac{1}{3}\end{bmatrix}
AT(Ax−b)=0,ATA=[3002]A^T(A\mathbf x-b)=0,\quad A^TA=\begin{bmatrix}3&0\\0&2\end{bmatrix}
min⁡x∥Ax−b∥2=23\min_x\|A\mathbf x-b\|^2=\frac{2}{3}

The column-space question

Which linear combination of the columns lies closest to the data vector? Each row is one equation.

A=[1−11011],b=[022]A=\begin{bmatrix}1&-1\\1&0\\1&1\end{bmatrix},\quad b=\begin{bmatrix}0\\2\\2\end{bmatrix}

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

Manipulate the input and inspect the geometry, exact classification and replayable mathematical derivation.

Move the middle data point away from the line. The fitted line balances the three vertical errors instead of passing through every observation. Choose Same x: nonunique minimizers to separate a unique projected data vector from nonunique coefficients. Then switch to Orthogonalize two directions and replay the projection-subtraction trace.

Intuition: split a vector into reachable and unreachable parts

Projecting onto one direction separates a parallel component from a perpendicular residual. A subspace works the same way: find a vector inside the subspace whose leftover is perpendicular to every direction in that subspace.

For a system Ax=bAx=b, the reachable vectors form the column space of AA. If bb lies outside it, no coefficient vector can solve every equation. Least squares chooses the closest reachable vector. The residual records precisely what the transformation cannot match.

Definition

Vectors are orthogonal when their dot product is zero. An orthogonal basis consists of independent, pairwise perpendicular nonzero vectors. An orthonormal basis additionally gives each vector norm one. If q1,…,qrq_1,\ldots,q_r are orthonormal, the projection onto their span is

p=∑j=1r(qjTb)qj,r=b−p.p=\sum_{j=1}^r(q_j^Tb)q_j,\qquad r=b-p.

Least squares minimizes ∥Ax−b∥2\|Ax-b\|^2. The minimizer is unique when AA has full column rank. With deficient rank, all minimizers are x0+zx_0+z for z∈ker⁡Az\in\ker A, but their projected output Ax0Ax_0 is unique.

Mechanics: observations and column-space geometry

The data explorer uses A=[1 t]A=[\mathbf 1\ \mathbf t], where each row is (1,ti)(1,t_i), and bb contains the observed heights. The coefficient vector is (intercept, slope). Dragging any point changes that canonical system. Its vertical residual segment is an entry of b−Axb-Ax; the inspector lists the full exact residual vector and its squared norm.

The point plot is in observation coordinates (t,y)(t,y). The three-entry data vector and its projection live in R3\R^3 and are shown as exact components, not projected deceptively into that same plane. The direction explorer instead demonstrates two-dimensional Gram–Schmidt and subspace projection directly. Keyboard and numeric inputs provide the same controls.

Derivation: Gram–Schmidt exposes projection mechanics

Begin with u1=a1u_1=a_1. Remove the components of each later column along earlier nonzero orthogonal directions:

uk=ak−∑j<kakTujujTujuj.u_k=a_k-\sum_{j<k}\frac{a_k^Tu_j}{u_j^Tu_j}u_j.

A zero residual means the column was dependent; an original zero vector also cannot be normalized. The lesson records those failures and continues with surviving independent directions. Dividing by ∥uj∥\|u_j\| then gives an orthonormal basis qjq_j. In the exact model we project using the unnormalized orthogonal directions, avoiding unnecessary irrational arithmetic:

p=∑jbTujujTujuj.p=\sum_j\frac{b^Tu_j}{u_j^Tu_j}u_j.

The exact dot products certify orthogonality; normalized unit-vector drawings are approximate companions. No zero direction is ever divided by its norm.

Derivation: normal equations and optimality

Suppose p=Ax0p=Ax_0 and r=b−pr=b-p is perpendicular to the column space. For any coefficient change hh, AhAh belongs to that space. Pythagoras gives

∥A(x0+h)−b∥2=∥Ah−r∥2=∥Ah∥2+∥r∥2.\|A(x_0+h)-b\|^2=\|Ah-r\|^2=\|Ah\|^2+\|r\|^2.

Therefore no change can improve the error. Equality occurs precisely when Ah=0Ah=0, explaining nonunique minimizers through the null space.

The orthogonality condition is AT(b−Ax0)=0A^T(b-Ax_0)=0, equivalently

AT(Ax0−b)=0,ATAx0=ATb.A^T(Ax_0-b)=0,\qquad A^TAx_0=A^Tb.

These are the normal equations. They are a mathematical characterization of a minimum, not a promise that every original equation has been solved.

Worked examples

For observations (−1,0),(0,2),(1,2)(-1,0),(0,2),(1,2), the two columns (1,1,1)(1,1,1) and (−1,0,1)(-1,0,1) are orthogonal. Projection coefficients are c=4/3c=4/3 and m=1m=1. The fitted heights are (1/3,4/3,7/3)(1/3,4/3,7/3) and the residual is (−1/3,2/3,−1/3)(-1/3,2/3,-1/3). Its dot product with each column is zero, and its squared norm is 2/32/3.

Replay the worked derivation

The column-space question

Which linear combination of the columns lies closest to the data vector? Each row is one equation.

A=[1−11011],b=[022]A=\begin{bmatrix}1&-1\\1&0\\1&1\end{bmatrix},\quad b=\begin{bmatrix}0\\2\\2\end{bmatrix}
Replay orthogonalization, exact data projection and the normal-equation condition.

For columns (1,1)(1,1) and (1,0)(1,0), Gram–Schmidt gives u1=(1,1)u_1=(1,1) and u2=(1/2,−1/2)u_2=(1/2,-1/2). Their dot product is zero; normalizing gives (1,1)/2(1,1)/\sqrt2 and (1,−1)/2(1,-1)/\sqrt2. For (1,1)(1,1) and (2,2)(2,2), the second residual is zero, so only one basis direction survives. The failure is dependence, not a second unit vector pointing somewhere arbitrary.

If every observation has ti=1t_i=1, the line coefficients only appear through c+mc+m. The closest fitted height is the mean 4/34/3, so every pair satisfying c+m=4/3c+m=4/3 minimizes the error. The inspector chooses one particular pair and displays the null direction (−1,1)(-1,1).

Executable reference code

The Fraction reference projects onto exact orthogonal directions. NumPy uses lstsq, explicitly computes residuals and cross-checks a QR projection. An empty NumPy residuals array is not proof of zero error; it can occur in rank-deficient or non-overdetermined systems.

code/python/least_squares.py
"""Exact Gram–Schmidt projection onto a column space."""
from fractions import Fraction as F

def project(columns,b):
    dot=lambda u,v: sum(x*y for x,y in zip(u,v))
    basis=[]
    for col in columns:
        u=list(map(F,col))
        for q in basis:
            gain=dot(u,q)/dot(q,q)
            u=[x-gain*y for x,y in zip(u,q)]
        if not any(u):
            continue  # Dependent or zero vector: do not normalize it.
        basis.append(u)
    p=[F(0)]*len(b)
    for u in basis:
        gain=dot(b,u)/dot(u,u)
        p=[x+gain*y for x,y in zip(p,u)]
    residual=[F(x)-y for x,y in zip(b,p)]
    assert all(dot(residual,c)==0 for c in columns)
    return p,residual,basis

p,r,basis=project([[1,1,1],[-1,0,1]],[0,2,2])
assert p==[F(1,3),F(4,3),F(7,3)]
assert r==[F(-1,3),F(2,3),F(-1,3)]
assert sum(x*x for x in r)==F(2,3)
assert len(project([[1,1],[2,2]],[0,2])[2])==1
code/python/least_squares_numpy.py
import numpy as np
A=np.array([[1.,-1.],[1.,0.],[1.,1.]])
b=np.array([0.,2.,2.])
x, reported_residuals, rank, singular_values=np.linalg.lstsq(A,b,rcond=None)
r=b-A@x
assert np.allclose(x,[4/3,1]) and np.allclose(A.T@r,0)
assert np.isclose(r@r,2/3)
# Compute the residual directly: reported_residuals can be empty for deficient systems.
Q,R=np.linalg.qr(A,mode='reduced')
assert np.allclose(Q@(Q.T@b),A@x)
# QR/SVD avoid forming A.T@A, which squares the 2-norm condition number.

Explore

Move a point to make all observations exactly collinear and compare zero error with the noisy case. Make all horizontal coordinates equal. Restore independent columns with a small separation and inspect sensitivity. In the direction mode, compare independent, dependent and zero-vector cases; predict which projection remains when one basis direction disappears.

Common mistakes

A residual can be nonzero while being orthogonal to every column. Least squares minimizes the sum of squared residuals, not their signed sum. The segments in the fit are vertical prediction errors, not shortest distances to the drawn line. Nonunique coefficients do not imply multiple closest projected data vectors. Orthonormality requires both perpendicularity and unit length.

Numerical considerations

This small educational domain uses exact rational Gram–Schmidt and exact projection, so zero and rank classifications do not depend on an epsilon. Normalized companion vectors and rendered segments use binary64. In numerical software, classical Gram–Schmidt can lose orthogonality; modified Gram–Schmidt or Householder QR are preferable depending on the problem.

The live sensitivity cue appears when the second column’s relative orthogonal remainder is below 0.050.05; it describes nearly parallel columns and never changes exact rank.

Forming ATAA^TA squares the 2-norm condition number for full-column-rank AA. That can amplify roundoff even though the normal equations are mathematically correct. QR and SVD methods usually provide a safer practical route. Numerical rank tolerances must reflect scale and uncertainty and can legitimately differ from the exact rank of entered rationals.

Engineering and ML connections

Linear regression projects targets onto features. Redundant feature columns produce unidentifiable parameter directions but still define a closest predicted target vector. Orthogonal features simplify coefficient calculations. SVD extends this picture by organizing the input and output directions by strength and explaining a minimum-norm pseudoinverse solution.

Exercises

calculation

Fit three observations

Fit y = c + mx to points (−1, 0), (0, 2), (1, 2). Give c and m.

calculation

Measure squared residuals

For this fit the residual is (−1/3, 2/3, −1/3). Find its squared norm.

calculation

Remove a projection

Gram–Schmidt starts with u₁ = (1, 1), a₂ = (1, 0). Find u₂ = a₂ − projᵤ₁(a₂).

prediction

Certify a minimum

What geometric statement does Aᵀ(Ax − b) = 0 express?

Choose one answer

prediction

Choose numerical software

Why often use QR/SVD instead of explicitly forming AᵀA?

Choose one answer

Summary and checkpoints

Build an orthogonal basis without normalizing zero residuals, decompose bb into projection plus perpendicular residual, derive the normal equations, and distinguish unique outputs from unique coefficients. Explain why practical QR/SVD can be safer than forming a Gram matrix.

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