Foundations to FrontierPart IX: The graduate coreBezhig

G05: Numerical linear algebra and optimization

6 exercises, each with a complete solution. 1 figure. 1 code listing.

On this page
  1. Prerequisites and observable goals
  2. The central question: which problem is hard, and which algorithm is fragile?
  3. Least squares is geometry with a residual
  4. Orthogonal transformations preserve distances
  5. A Householder step, derived
  6. What the reference does and does not promise
  7. Gradient descent on a quadratic
  8. Constraints and first-order conditions
  9. Independent practice
  10. Smallest useful hints
  11. Complete solutions: G05
  12. Readiness and continuation

Prerequisites and observable goals#

Before

foundation A01–A06, derivatives, gradients, and matrix multiplication.

After

Solve a least-squares problem with an orthogonal transformation, distinguish conditioning from stability, and choose a justified step size for a quadratic objective.

The central question: which problem is hard, and which algorithm is fragile?#

A poorly conditioned problem changes its answer substantially when its data changes slightly. An unstable algorithm can introduce unnecessary error even on a well-conditioned problem. These are not synonyms. Report the norm, perturbation model, and object whose error is measured before calling a calculation “accurate.”

For an invertible matrix AA, the normwise condition number in the Euclidean norm is κ2(A)=∥A∥2∥A−1∥2=σmax⁡/σmin⁡\kappa_2(A)=\|A\|_2\|A^{-1}\|_2=\sigma_{\max}/\sigma_{\min}. A small singular value means some input direction produces a small output: recovering its coefficient from noisy observations is difficult. Adding more decimal digits to printed output does not solve that loss of information.

Least squares is geometry with a residual#

For A∈Rm×nA\in\R^{m\times n} and b∈Rmb\in\R^m, minimize

F(x)=12∥Ax−b∥22.F(x)=\frac12\|Ax-b\|_2^2.

When AA has full column rank, the minimizer is unique. Differentiation gives ∇F(x)=AT(Ax−b)\nabla F(x)=A^T(Ax-b); at the minimizer, the residual r=Ax−br=Ax-b is orthogonal to every column of AA:

ATr=0,ATAx=ATb.A^Tr=0,\qquad A^TAx=A^Tb.

These normal equations characterize the optimum, but explicitly forming them is not always a good numerical algorithm. Their condition number satisfies κ2(ATA)=κ2(A)2\kappa_2(A^TA)=\kappa_2(A)^2 under full column rank, potentially magnifying numerical difficulties.

Worked example: fit a line a+bta+bt to (t,y)=(0,1),(1,2),(2,2)(t,y)=(0,1),(1,2),(2,2). Then

ATA=(3335),ATy=(56).A^TA=\begin{pmatrix}3&3\\3&5\end{pmatrix},\quad A^Ty=\binom56.

The equations 3a+3b=53a+3b=5 and 3a+5b=63a+5b=6 give b=1/2b=1/2, then a=7/6a=7/6. Predictions are (7/6,5/3,13/6)(7/6,5/3,13/6), so r=(1/6,−1/3,1/6)r=(1/6,-1/3,1/6). Check ∑iri=0\sum_i r_i=0 and ∑itiri=0\sum_i t_ir_i=0. The squared residual norm is 1/61/6, hence the half-squared objective is 1/121/12. These checks make the geometry visible.

Orthogonal transformations preserve distances#

An orthogonal matrix QQ satisfies QTQ=IQ^TQ=I, so ∥QTv∥2=∥v∥2\|Q^Tv\|_2=\|v\|_2. A thin QR factorization of full-column-rank AA writes A=Q1RA=Q_1R with Q1Q_1 having orthonormal columns and RR upper triangular. Completing to an orthogonal basis gives

∥Ax−b∥22=∥Rx−Q1Tb∥22+∥Q2Tb∥22.\|Ax-b\|_2^2=\|Rx-Q_1^Tb\|_2^2+\|Q_2^Tb\|_2^2.

Only the first term depends on xx. Solve the triangular system Rx=Q1TbRx=Q_1^Tb by back substitution; the leftover component is the irreducible residual. The algorithm avoids explicitly squaring the condition number by forming ATAA^TA.

A Householder step, derived#

Given a nonzero column segment zz, we want a reflection that maps it to a multiple of the first coordinate vector e1e_1. Choose α=−sign⁡(z1)∥z∥2\alpha=-\operatorname{sign}(z_1)\|z\|_2 (choose positive sign for a zero z1z_1), set v=z−αe1v=z-\alpha e_1, and define

H=I−2vvTvTv.H=I-2\frac{vv^T}{v^Tv}.

Since P=vvT/(vTv)P=vv^T/(v^Tv) is an orthogonal projector with P2=PP^2=P, HTH=(I−2P)2=IH^TH=(I-2P)^2=I. One can check Hz=αe1Hz=\alpha e_1. The sign choice avoids subtracting nearly equal positive quantities when constructing the first component of vv.

For z=(3,4)Tz=(3,4)^T, choose α=−5\alpha=-5 and v=(8,4)Tv=(8,4)^T. Then

H=(−.6−.8−.8.6),Hz=(−50).H=\begin{pmatrix}-.6&-.8\\-.8&.6\end{pmatrix},\qquad Hz=\binom{-5}{0}.

The reflection changes orientation but not length. Apply it to the active rows of each remaining matrix column and to the matching target segment. Repeat down the diagonal. The lab stores and applies each reflector directly rather than constructing a dense HH each time.

What the reference does and does not promise#

The implementation globally scales AA and bb by the largest absolute matrix entry, computes Householder steps with math.hypot, and rejects a sufficiently small remaining diagonal segment using a documented relative threshold. This is an educational full-rank solver, not a rank-revealing pivoted QR or SVD library. A tolerance-based rank decision depends on scaling and column order. Very ill-conditioned or extreme dynamic-range cases require stronger tools, condition estimates, and careful residual/backward-error analysis.

A small residual is not always a small coefficient error: with nearly dependent columns, many widely different coefficients predict almost the same vector. Conversely, a nonzero residual can be unavoidable for noisy or inconsistent observations, even when the computed minimizer is excellent. To check a result, report both residual size and sensitivity, not one scalar relabeled as universal accuracy.

Gradient descent on a quadratic#

Let f(x)=12xTHx−gTxf(x)=\frac12x^THx-g^Tx with symmetric positive-definite HH. The optimum solves Hx∗=gHx_*=g. Gradient descent uses

xk+1=xk−η(Hxk−g),ek+1=(I−ηH)ek,x_{k+1}=x_k-\eta(Hx_k-g),\qquad e_{k+1}=(I-\eta H)e_k,

where ek=xk−x∗e_k=x_k-x_*. In an orthonormal eigenbasis of HH, each error component is multiplied by 1−ηλi1-\eta\lambda_i. All shrink in magnitude when

0<η<2λmax⁡(H).0<\eta<\frac{2}{\lambda_{\max}(H)}.

At the endpoint, the largest-eigenvalue component can oscillate without decay. A tiny step is stable but can be slow, especially when λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min} is large. The formula derives from this quadratic model; do not apply it to an arbitrary neural-network loss without establishing relevant smoothness and curvature assumptions.

For H=diag⁡(1,9)H=\diag(1,9) and g=0g=0, choosing η=.1\eta=.1 yields factors .9,.1.9,.1. Starting (1,1)(1,1) gives (.9,.1)(.9,.1) and objective (.81+9(.01))/2=.45(.81+9(.01))/2=.45, down from 5. Choosing η=.3\eta=.3 yields factors .7,−1.7.7,-1.7; the second component grows while changing sign. A decreasing loss in one tested step does not prove global convergence on a different objective.

Step size against curvature. Gradient descent on f=12(x2+9y2)f=\tfrac12(x^2+9y^2), whose curvatures are 11 and 99, from one starting point. With η=0.1\eta=0.1 (blue) the steep direction is multiplied by 0.10.1 at each step and the shallow one by 0.90.9. With η=0.2\eta=0.2 (orange), near the limit 2/92/9, the steep direction is multiplied by −0.8-0.8: the iterate overshoots the valley floor and changes sides at every step. At η=0.3\eta=0.3 that factor is −1.7-1.7 and the iteration diverges.

Constraints and first-order conditions#

For differentiable convex ff, a zero gradient is a global minimum on all of Rn\R^n. With constraints, zero gradient need not hold at the constrained optimum. For min⁡x(x−2)2\min_x (x-2)^2 subject to x≤1x\le1, the optimum is 1, whose derivative is −2-2. Using g(x)=x−1≤0g(x)=x-1\le0, the Lagrangian is L=(x−2)2+λ(x−1)\mathcal L=(x-2)^2+\lambda(x-1). At the optimum, stationarity gives −2+λ=0-2+\lambda=0, so λ=2≥0\lambda=2\ge0 and complementary slackness λg(x)=0\lambda g(x)=0 holds. General KKT necessity needs a suitable constraint qualification; sufficiency in convex settings needs the appropriate convexity and feasible conditions. This example does not establish KKT for every nonconvex program. [G-CVX]

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.

G05.01CSolution

Derive the line-fit coefficients for the three observations above. Verify residual orthogonality and the half-squared loss.

G05.02CSolution

Construct the Householder reflector for z=(3,4)z=(3,4) using the stable sign choice. Verify both HTH=IH^TH=I and Hz=(−5,0)THz=(-5,0)^T.

G05.03TSolution

For A=diag⁡(1,10−6)A=\diag(1,10^{-6}) and b=(1,10−6)Tb=(1,10^{-6})^T, solve Ax=bAx=b. Change the second component of bb by 10−610^{-6} and compare relative data and solution perturbations.

G05.04CSolution

For H=diag⁡(2,8)H=\diag(2,8), derive the interval of constant positive learning rates that converges for every initial error. Compute one update from (1,1)(1,1) with g=0,η=.2g=0,\eta=.2.

G05.05TSolution

Solve min⁡(x−2)2\min (x-2)^2 subject to x≤1x\le1 and verify the multiplier conditions. Explain why setting the objective derivative to zero alone gives an infeasible answer.

G05.06LSolution

Implement least_squares in starters/numerics.py with Householder reflections and the documented finite-input, shape, and rank-threshold checks. Do not form ATAA^TA. Test exact full-rank systems, an inconsistent fit, rank-deficient columns, unchanged inputs, and scaled versions of the same problem.

Smallest useful hints#

For .02, write v=(8,4)v=(8,4) and compute its outer product before division. For .03, solve each diagonal equation separately. For .06, transform the target using exactly the same row reflection as the matrix.

Complete solutions: G05#

Compare the first step where your work differs. A corrected answer is not yet an independent success.

G05.01Show solution

Solve and independently check

From 3a+3b=53a+3b=5 and 3a+5b=63a+5b=6, subtract to obtain 2b=12b=1, so b=1/2b=1/2 and a=7/6a=7/6. The residual vector is (1/6,−1/3,1/6)(1/6,-1/3,1/6). Its inner products with columns (1,1,1)(1,1,1) and (0,1,2)(0,1,2) are zero. Its squared norm is 1/36+1/9+1/36=1/61/36+1/9+1/36=1/6, and F=1/12F=1/12. Full column rank ensures uniqueness. These equations verify this instance; they do not recommend normal equations as the robust default implementation.

Back to G05.01
G05.02Show solution

A norm-preserving elimination step

Here vTv=80v^Tv=80 and 2vvT/80=(1.6.8.8.4)2vv^T/80=\begin{pmatrix}1.6&.8\\.8&.4\end{pmatrix}. Subtracting from identity gives the displayed HH. Dot products of its columns are 1, 1, and 0, proving orthogonality. Multiplication gives (−1.8−3.2,−2.4+2.4)=(−5,0)(-1.8-3.2,-2.4+2.4)=(-5,0). The vector norm remains five. Choosing the opposite sign would still define a reflection in exact arithmetic, but the stable sign is important when the vector is already nearly aligned with the first coordinate.

Back to G05.02
G05.03Show solution

Small data changes in a sensitive direction

Originally x=(1,1)x=(1,1). The perturbed right side is (1,2⋅10−6)(1,2\cdot10^{-6}), giving x′=(1,2)x'=(1,2). The relative data perturbation is 10−6/1+10−12≈10−610^{-6}/\sqrt{1+10^{-12}}\approx10^{-6}, while the relative solution perturbation is 1/2≈.70711/\sqrt2\approx.7071. The matrix condition number is 10610^6. The large response is a property of solving this system, not evidence that the trivial diagonal solver introduced an unnecessary instability.

Back to G05.03
G05.04Show solution

Every eigendirection must contract

The factors are 1−2η1-2\eta and 1−8η1-8\eta. Require both magnitudes below one, giving 0<η<10<\eta<1 and 0<η<1/40<\eta<1/4; their intersection is (0,1/4)(0,1/4). At .2.2, the update is (.6,−.6)(.6,-.6). The second sign flip is not itself divergence because its magnitude factor is .6. At .25.25, the second factor is −1-1, so convergence from every starting error fails.

Back to G05.04
G05.05Show solution

The boundary changes stationarity

The unconstrained minimizer x=2x=2 violates x≤1x\le1. The objective decreases as xx approaches 2 from the left, so the feasible optimum is x=1x=1 with value 1. Set g(x)=x−1g(x)=x-1, λ=2\lambda=2. Feasibility, nonnegative multiplier, stationarity 2(x−2)+λ=02(x-2)+\lambda=0, and complementary slackness all hold. Convexity makes these conditions sufficient here; more general necessity claims require further assumptions.

Back to G05.05
G05.06Show solution

Complete reference solver

The reflection formula is applied in place to private copies, not caller-owned data. Back substitution starts at the last triangular equation, subtracts already solved upper-diagonal contributions, and divides by the diagonal. The tests include 50 seeded exact systems and invariance under global scales 10−10010^{-100} and 1010010^{100} for the simple fit. These finite cases do not certify all ill-conditioned inputs.

graduate_code/solutions/numerics.pyPython
"""G05: educational Householder least squares for bounded full-rank matrices."""
import math


def least_squares(A, b, rtol=1e-12):
    m, n = len(A), len(A[0]) if A else 0
    if not 1 <= n <= 64 or not n <= m <= 10000 or len(b) != m:
        raise ValueError("require m >= n, 1..64 columns, <=10000 rows")
    if any(len(row) != n for row in A):
        raise ValueError("ragged matrix")
    if not math.isfinite(rtol) or not 0 < rtol < 1:
        raise ValueError("relative rank threshold must lie in (0,1)")
    if any(not math.isfinite(x) for row in A for x in row) or any(not math.isfinite(x) for x in b):
        raise ValueError("finite matrix and target required")
    scale = max(abs(x) for row in A for x in row)
    if scale == 0:
        raise ValueError("rank-deficient zero matrix")
    R = [[x/scale for x in row] for row in A]
    target = [x/scale for x in b]
    if any(not math.isfinite(x) for x in target):
        raise ValueError("target exceeds supported dynamic range")
    for j in range(n):
        z = [R[i][j] for i in range(j,m)]
        norm = math.hypot(*z)
        if norm <= rtol:
            raise ValueError("rank deficiency at stated relative threshold")
        alpha = -math.copysign(norm,z[0])
        v = list(z)
        v[0] -= alpha
        vnorm = math.hypot(*v)
        v = [x/vnorm for x in v]
        for k in range(j,n):
            projection = 2*math.fsum(v[i-j]*R[i][k] for i in range(j,m))
            for i in range(j,m):
                R[i][k] -= projection*v[i-j]
        projection = 2*math.fsum(v[i-j]*target[i] for i in range(j,m))
        for i in range(j,m):
            target[i] -= projection*v[i-j]
        R[j][j] = alpha
        for i in range(j+1,m):
            R[i][j] = 0.
    x = [0.]*n
    for j in range(n-1,-1,-1):
        remainder = math.fsum(R[j][k]*x[k] for k in range(j+1,n))
        x[j] = (target[j]-remainder)/R[j][j]
    if not all(math.isfinite(value) for value in x):
        raise ValueError("nonfinite coefficients")
    return x


if __name__ == "__main__":
    print(least_squares([[1,0],[1,1],[1,2]],[1,2,2]))
Back to G05.06

Readiness and continuation#

Explain why an inconsistent system has a best approximation, why ATr=0A^Tr=0 is geometric, and why a small residual need not mean stable coefficients. Continue with pivoted QR, SVD-based rank determination, backward stability proofs, preconditioning, iterative Krylov solvers, and constrained convex optimization. The optional reference gives deeper convex analysis; only its public book page was used as a continuation pointer here. [G-CVX]