A02: Orthogonality, least squares, eigenvectors, and SVD
On this page
- A. Prerequisites and observable goals
- B. The central question: what is the best achievable approximation?
- C. Deriving projection rather than memorizing it
- D. Least squares is projection onto the column space
- E. Eigenvectors identify directions preserved by a square map
- F. Singular values separate rotations from stretching
- G. Independent practice
- H. Complete solutions: A02
- I. Retention and readiness
A. Prerequisites and observable goals#
A01: matrices, bases, rank, and linear maps. Derivatives from Calculus I help with the optimization interpretation but are not needed for the projection construction.
Project onto a subspace, derive least squares from residual orthogonality, compute a small eigendecomposition, recognize positive definiteness, and interpret singular values geometrically.
Level: Degree core with an introductory bridge to advanced numerical linear algebra.
B. The central question: what is the best achievable approximation?#
A system may have no exact solution. Measurements contain noise, and a simple model may not represent every observed outcome. Rather than inventing an exact solution, choose that minimizes a specified discrepancy. Ordinary least squares minimizes , the sum of squared coordinate residuals. This is a modeling decision: large residuals receive disproportionate weight, units matter, and outliers may dominate. It is not automatically the right loss for every application.
The dot product measures alignment in Euclidean coordinates. The norm measures length. Nonzero vectors are orthogonal when their dot product is zero. An orthonormal collection has unit-length, mutually orthogonal vectors. These properties simplify coordinates because the coefficient of along a unit vector is simply .
C. Deriving projection rather than memorizing it#
To approximate by a multiple of a nonzero vector , require the leftover to be perpendicular to :
The denominator is strictly positive because . This perpendicularity gives the closest point. For any other coefficient , the error is . The two pieces are perpendicular, so the squared norm is , no smaller than the projected error. The argument is the Pythagorean theorem, not merely a derivative calculation.
For and , , the projection is , and the residual is . Their dot product is zero. If the columns of form an orthonormal basis for a subspace, the projection is . Each coefficient comes from one dot product. The residual is perpendicular to every basis vector and therefore to the whole subspace.
Exact Euclidean coordinates: . The residual is not a vertical error to the diagonal line.
D. Least squares is projection onto the column space#
For to be the projection of , its residual must satisfy . Thus the normal equations are
When has independent columns, is invertible: for nonzero , . If columns are dependent, minimizers need not be unique, although the projected vector is unique. Explicitly forming the inverse is not the preferred numerical algorithm. A QR factorization , with orthonormal columns in and upper triangular , reduces the problem to . The lab uses modified Gram–Schmidt to illustrate this geometry. More robust libraries use methods such as Householder QR or SVD; the small lab is not a replacement for them. [LA]
Fit a line to . Then
Subtract the first normal equation from the second to get , hence and . Predictions are and residuals . Their sum is zero, and their dot product with is zero. Those two checks verify perpendicularity to both design columns. The line minimizes squared vertical response residuals at fixed , not arbitrary geometric distances in the plane.
E. Eigenvectors identify directions preserved by a square map#
An eigenvector is a nonzero vector satisfying . The scalar is its eigenvalue. The zero vector is excluded because it satisfies the equation for every and would identify no direction. Eigenvalues solve , but deriving the characteristic polynomial by hand is not the default stable algorithm for a large matrix.
For , vectors and have eigenvalues 3 and 1. Normalize them to form an orthogonal matrix ; then . In those coordinates, repeated application simply multiplies the two components by powers of 3 and 1. This explains why one direction dominates long-term growth. Symmetric real matrices admit an orthonormal eigenbasis; a general matrix may not, may have complex eigenvalues, or may lack enough independent eigenvectors.
A real symmetric matrix is positive definite when for every nonzero real . Its eigenvalues are then positive, and a quadratic energy curves upward in every direction. Positive diagonal entries alone do not establish this property. For a symmetric matrix, the first leading diagonal entry and determinant being positive are sufficient. In higher dimensions, use an appropriate criterion or factorization, not a guessed extension of a two-dimensional rule.
F. Singular values separate rotations from stretching#
For any real matrix, an SVD has the form , with orthogonal square and rectangular nonnegative diagonal . Read this right to left: change input coordinates, stretch or erase principal directions, then change output coordinates. The nonzero singular values are square roots of the positive eigenvalues of . They apply to rectangular maps and describe directional gains even when eigenvectors of itself are not appropriate.
For , the input direction is stretched by to output direction , while is erased. The rank is one. Keeping the largest singular directions gives a low-rank approximation; the truncated SVD has an optimality theorem for specified matrix norms, but it does not automatically preserve the features that a human application considers important. Numerical rank also requires a tolerance relative to scale and measurement uncertainty.
G. Independent practice#
F foundation C standard course work T transfer S optional stretch L runnable lab or project. Attempt the complete set before opening its solutions.
Project onto the line spanned by . Compute the residual, verify orthogonality, and give the squared distance to the line.
Reproduce the line-fit calculation above without looking at the solution. Verify both normal equations and compute the residual sum of squares. Explain why an exact fit is impossible.
For , derive both eigenvalues and a normalized eigenbasis. Use it to compute without three full matrix multiplications.
Give a symmetric matrix with positive diagonal entries that is not positive definite, and exhibit a direction with negative quadratic form. For , identify a null direction and both singular values.
Implement the full-column-rank least-squares interface in least_squares_lab.py using modified Gram–Schmidt QR and triangular back substitution. Reject incompatible shapes, nonfinite inputs, and a numerically dependent column according to the stated tolerance. Test the three-point line fit and verify is near zero. Explain what the tolerance does not guarantee.
Optional small hints
A02.03: decompose as one half of . A02.04: make the off-diagonal magnitude larger than the diagonal entries. A02.05: subtract the projection onto each previously computed orthonormal column.
H. Complete solutions: A02#
Compare the first step where your work differs. A corrected answer is not yet an independent success.
A02.01Show solution
The residual defines the error
and , so . The residual is . Its dot product with is , and the squared distance is . By the perpendicular decomposition argument, every other point on the line has at least this squared distance. The residual is a vector; the squared distance is a nonnegative scalar.
Back to A02.01A02.02Show solution
An overdetermined but solvable approximation
The normal equations yield , . Substitution gives and . The residual sum of squares is . An exact fit through the first two points would have intercept 1 and slope 1, predicting 3 at , not 2. Least squares therefore solves an approximation problem, not the inconsistent original equalities.
Back to A02.02A02.03Show solution
Use coordinates adapted to the map
, so eigenvalues are 3 and 1. Corresponding normalized vectors are , . They are orthonormal. Since , applying gives . Check directly once: and . The eigenbasis predicts the same first column.
Back to A02.03A02.04Show solution
Diagonal signs are not enough
Take and . Then and . For , the null direction is . Since has eigenvalues 2 and 0, the singular values are and 0. One input direction is retained and stretched, the other erased.
Back to A02.04A02.05Show solution
Reference implementation and numerical limits
"""A02.05: modified Gram-Schmidt QR for a small full-column-rank matrix."""
import math
def least_squares(a: list[list[float]], b: list[float],
tolerance: float = 1e-12) -> list[float]:
m = len(a)
n = len(a[0]) if m else 0
if not n or m < n or len(b) != m or any(len(row) != n for row in a):
raise ValueError("a must be rectangular, m >= n; b must have m entries")
if tolerance <= 0 or not math.isfinite(tolerance):
raise ValueError("positive finite tolerance required")
if any(not math.isfinite(v) for row in a for v in row) or any(
not math.isfinite(v) for v in b):
raise ValueError("finite data required")
q: list[list[float]] = []
r = [[0.0] * n for _ in range(n)]
for j in range(n):
v = [row[j] for row in a]
for i in range(j):
r[i][j] = math.fsum(q[i][k] * v[k] for k in range(m))
v = [v[k] - r[i][j] * q[i][k] for k in range(m)]
r[j][j] = math.sqrt(math.fsum(x * x for x in v))
if r[j][j] <= tolerance:
raise ValueError("numerically dependent columns at chosen tolerance")
q.append([x / r[j][j] for x in v])
y = [math.fsum(col[k] * b[k] for k in range(m)) for col in q]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - math.fsum(r[i][j] * x[j]
for j in range(i + 1, n))) / r[i][i]
return x
if __name__ == "__main__":
print(least_squares([[1., 0.], [1., 1.], [1., 2.]], [1., 2., 2.]))After each projection subtraction, the current column has had its component along an earlier removed. Normalizing the residual constructs the next basis vector and the corresponding entries of . Back substitution solves . Exact arithmetic would make the residual orthogonal to the entire column space; floating-point arithmetic makes this approximate. A small column norm triggers rejection because normalization would magnify error. The absolute tolerance is a deliberately simple classroom policy: rescaling the data can change its decision, and near-dependent columns may still be difficult. A production solver should use a scale-aware rank criterion and a robust factorization. The tests verify the known solution, residual orthogonality, shape rejection, and rank failure; they do not certify all ill-conditioned matrices.
Back to A02.05I. Retention and readiness#
Retrieve rank–nullity and the geometric meaning of a matrix column. Advance when you can derive a projection from perpendicularity, explain what least squares minimizes, and distinguish eigenvalues from singular values. Continue with numerical linear algebra and larger QR/SVD experiments before treating this introduction as advanced competence.