Course contents 03 / 16

03 / 16 · Linear Algebra

Inner products, norms and orthogonality

Lengths and angles for vectors in any dimension: inner products and norms, the Cauchy–Schwarz inequality, projection onto a subspace as the closest point, Gram–Schmidt and QR, orthogonal matrices and cosine similarity.

On this page 12

No combination of the columns (1,0,1)(1, 0, 1) and (0,1,1)(0, 1, 1) equals b=(1,2,6)b = (1, 2, 6), as the previous note found. Which combination comes closest? And how similar are two word embeddings, each a vector of 768 numbers? Both questions need lengths and angles, and a vector space has neither: addition and scaling say nothing about how long a vector is or whether two vectors are perpendicular.

In the plane, lengths and angles come with the picture. Pythagoras gives the length of u=(u1,u2)u = (u_1, u_2),

∥u∥=u12+u22,\lVert u\rVert = \sqrt{u_1^2 + u_2^2} ,

and the law of cosines in the triangle with sides uu, vv and u−vu - v relates the angle θ\theta between uu and vv to the coordinates. Expanding the same squared length in two ways,

∥u−v∥2=∥u∥2+∥v∥2−2∥u∥ ∥v∥cos⁡θ,∥u−v∥2=∑iui2+∑ivi2−2∑iuivi,\begin{aligned} \lVert u - v\rVert^2 &= \lVert u\rVert^2 + \lVert v\rVert^2 - 2\lVert u\rVert\,\lVert v\rVert \cos\theta , \\ \lVert u - v\rVert^2 &= \sum_i u_i^2 + \sum_i v_i^2 - 2\sum_i u_i v_i , \end{aligned}

and comparing the two gives

u1v1+u2v2=∥u∥ ∥v∥cos⁡θ.u_1 v_1 + u_2 v_2 = \lVert u\rVert\, \lVert v\rVert \cos\theta .

For u=(3,4)u = (3, 4) and v=(4,3)v = (4, 3) the left side is 24 and both lengths are 5, so cos⁡θ=0.96\cos\theta = 0.96 and θ≈16.3°\theta \approx 16.3°. In R768\mathbb R^{768} there is no picture to measure. The way out is the one the first note took for vectors: take the algebraic properties of this product as the definition, and derive the geometry from them.

Inner products#

An inner product on a vector space VV assigns a number ⟨u,v⟩\langle u, v\rangle to every pair of vectors such that, for all u,v,wu, v, w and numbers a,ba, b:

  • it is symmetric: ⟨u,v⟩=⟨v,u⟩\langle u, v\rangle = \langle v, u\rangle;
  • it is linear in the first argument: ⟨au+bw,v⟩=a⟨u,v⟩+b⟨w,v⟩\langle au + bw, v\rangle = a\langle u, v\rangle + b\langle w, v\rangle, and so, by symmetry, in the second;
  • it is positive definite: ⟨v,v⟩>0\langle v, v\rangle \gt 0 for every v≠0v \ne 0.

It defines a length, the norm ∥v∥=⟨v,v⟩\lVert v\rVert = \sqrt{\langle v, v\rangle}, and a distance ∥u−v∥\lVert u - v\rVert. Four inner products appear in this course:

⟨u,v⟩=u⊤v=∑iuivi,⟨u,v⟩M=u⊤Mv,⟨A,B⟩=tr⁡(A⊤B)=∑i,jaijbij,⟨f,g⟩=∫01f(t) g(t) dt.\begin{aligned} \langle u, v\rangle &= u^\top v = \sum_i u_i v_i , \\ \langle u, v\rangle_M &= u^\top M v , \\ \langle A, B\rangle &= \operatorname{tr}(A^\top B) = \sum_{i,j} a_{ij} b_{ij} , \\ \langle f, g\rangle &= \int_0^1 f(t)\, g(t)\, dt . \end{aligned}

The first, the dot product of Rn\mathbb R^n, is the default from now on. The second needs a symmetric matrix MM with v⊤Mv>0v^\top M v \gt 0 for every v≠0v \ne 0; with M=Σ−1M = \Sigma^{-1} for a covariance matrix Σ\Sigma, its norm is the Mahalanobis distance of the multivariate Gaussian. The third, the trace inner product of matrices, multiplies entries in matching positions, since tr⁡(A⊤B)=∑j(A⊤B)jj=∑j∑iaijbij\operatorname{tr}(A^\top B) = \sum_j (A^\top B)_{jj} = \sum_j \sum_i a_{ij} b_{ij}; tr⁡\operatorname{tr}, the trace, is the sum of the diagonal entries, and ⟨A,I⟩=tr⁡A\langle A, I\rangle = \operatorname{tr} A. The fourth acts on continuous functions on [0,1][0, 1], and it is positive definite because a continuous f≠0f \ne 0 is nonzero on a whole interval, so ∫01f2 dt>0\int_0^1 f^2\, dt \gt 0; the constant 1 and the function tt have ⟨1,t⟩=1/2\langle 1, t\rangle = 1/2.

Two vectors are orthogonal, u⊥vu \perp v, when ⟨u,v⟩=0\langle u, v\rangle = 0. Expanding by linearity gives Pythagoras in any inner product space:

∥u+v∥2=∥u∥2+2⟨u,v⟩+∥v∥2=∥u∥2+∥v∥2if u⊥v.\begin{aligned} \lVert u + v\rVert^2 &= \lVert u\rVert^2 + 2\langle u, v\rangle + \lVert v\rVert^2 \\ &= \lVert u\rVert^2 + \lVert v\rVert^2 \quad \text{if } u \perp v . \end{aligned}

Norms#

A length can be defined without an inner product. A norm is any function ∥⋅∥\lVert\cdot\rVert with ∥v∥>0\lVert v\rVert \gt 0 for v≠0v \ne 0, ∥av∥=∣a∣ ∥v∥\lVert a v\rVert = \lvert a\rvert\, \lVert v\rVert, and the triangle inequality ∥u+v∥≤∥u∥+∥v∥\lVert u + v\rVert \le \lVert u\rVert + \lVert v\rVert. Three norms on Rn\mathbb R^n are used constantly, and a fourth on matrices:

∥v∥1=∑i∣vi∣,∥v∥2=∑ivi2,∥v∥∞=max⁡i∣vi∣,∥A∥F=∑i,jaij2=tr⁡(A⊤A).\begin{aligned} \lVert v\rVert_1 &= \sum_i \lvert v_i\rvert, \\ \lVert v\rVert_2 &= \sqrt{\textstyle\sum_i v_i^2}, \\ \lVert v\rVert_\infty &= \max_i \lvert v_i\rvert, \\ \lVert A\rVert_F &= \sqrt{\textstyle\sum_{i,j} a_{ij}^2} = \sqrt{\operatorname{tr}(A^\top A)} . \end{aligned}

For v=(3,−4)v = (3, -4) they give ∥v∥1=7\lVert v\rVert_1 = 7, ∥v∥2=5\lVert v\rVert_2 = 5 and ∥v∥∞=4\lVert v\rVert_\infty = 4. The Frobenius norm is the ℓ2\ell_2 norm of the matrix read as one long vector, and the norm of the trace inner product; for

A=(1234)A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}

it is 30≈5.477\sqrt{30} \approx 5.477. The ℓ1\ell_1, ℓ2\ell_2 and ℓ∞\ell_\infty norms belong to one family, the ℓp\ell_p norms for p≥1p \ge 1:

∥v∥p=(∑i∣vi∣p)1/p.\lVert v\rVert_p = \Big(\sum_i \lvert v_i\rvert^p\Big)^{1/p} .

Each of them satisfies the triangle inequality. For ℓ1\ell_1 and ℓ∞\ell_\infty it follows entry by entry from ∣ui+vi∣≤∣ui∣+∣vi∣\lvert u_i + v_i\rvert \le \lvert u_i\rvert + \lvert v_i\rvert. For ℓ2\ell_2 and the Frobenius norm the next section derives it from Cauchy–Schwarz. For general p≥1p \ge 1 it is Minkowski’s inequality, which follows from the convexity of the unit ball.

Derivation: Minkowski’s inequality from a convex ball

The function s↦sps \mapsto s^p is convex and nondecreasing for s≥0s \ge 0, its second derivative p(p−1)sp−2p(p-1)s^{p-2} being nonnegative for s>0s \gt 0, and t↦∣t∣t \mapsto \lvert t\rvert is convex. So ∣t∣p\lvert t\rvert^p is convex by the composition rule, and so is the sum f(x)=∑i∣xi∣pf(x) = \sum_i \lvert x_i\rvert^p. Its ball B={x:f(x)≤1}B = \{x : f(x) \le 1\} is convex: for x,y∈Bx, y \in B, f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y)≤1f(\theta x + (1 - \theta) y) \le \theta f(x) + (1 - \theta) f(y) \le 1. For u,v≠0u, v \ne 0 put θ=∥u∥p/(∥u∥p+∥v∥p)\theta = \lVert u\rVert_p / (\lVert u\rVert_p + \lVert v\rVert_p):

u+v∥u∥p+∥v∥p=θ u∥u∥p+(1−θ) v∥v∥p.\frac{u + v}{\lVert u\rVert_p + \lVert v\rVert_p} = \theta\, \frac{u}{\lVert u\rVert_p} + (1 - \theta)\, \frac{v}{\lVert v\rVert_p} .

The right side mixes two points of BB, so it lies in BB and has norm at most 1. Multiplying by ∥u∥p+∥v∥p\lVert u\rVert_p + \lVert v\rVert_p gives ∥u+v∥p≤∥u∥p+∥v∥p\lVert u + v\rVert_p \le \lVert u\rVert_p + \lVert v\rVert_p.

The shape of a norm is the shape of its unit ball, the set of vectors of norm at most 1:

Figure

Unit balls of the ℓ₁, ℓ₂ and ℓ∞ norms in the plane

A diamond, a disc and a square: the unit balls of three normsThe diamond with corners on the axes is the unit ball of the ℓ₁ norm; the disc is the ball of the ℓ₂ norm; the square with sides parallel to the axes is the ball of the ℓ∞ norm. The point x = (0.6, 0.8) lies on the circle, outside the diamond and inside the square.x = (0.6, 0.8)‖x‖₁ ≤ 1‖x‖₂ ≤ 1‖x‖∞ ≤ 1‖x‖₁ = 1.4‖x‖₂ = 1‖x‖∞ = 0.8
The unit balls of three norms: the ℓ₁ diamond, the ℓ₂ disc and the ℓ∞ square, nested as ‖x‖∞ ≤ ‖x‖₂ ≤ ‖x‖₁. The point x = (0.6, 0.8) lies on the circle, outside the diamond (‖x‖₁ = 1.4) and inside the square (‖x‖∞ = 0.8).

The balls are nested, because ∥v∥∞≤∥v∥2≤∥v∥1\lVert v\rVert_\infty \le \lVert v\rVert_2 \le \lVert v\rVert_1 for every vv: the largest vi2v_i^2 is at most the sum of all of them, and (∑i∣vi∣)2\big(\sum_i \lvert v_i\rvert\big)^2 is ∑ivi2\sum_i v_i^2 plus nonnegative cross terms. In the other direction ∥v∥1≤n ∥v∥2\lVert v\rVert_1 \le \sqrt n\, \lVert v\rVert_2, as the next section shows, and ∥v∥2≤n ∥v∥∞\lVert v\rVert_2 \le \sqrt n\, \lVert v\rVert_\infty, since each of the nn terms of ∑ivi2\sum_i v_i^2 is at most ∥v∥∞2\lVert v\rVert_\infty^2. So these norms are equivalent up to constants, but the constants grow with nn. The shapes also matter for what a penalty prefers. The corners of the ℓ1\ell_1 ball sit on the axes, which is why the lasso, which constrains ∥w∥1\lVert w\rVert_1, produces weights that are exactly zero (the constrained form).

Of these norms, only ℓ2\ell_2 comes from an inner product, and on matrices the Frobenius norm does. Adding the expansions of the two squares shows that a norm from an inner product satisfies the parallelogram law:

∥u+v∥2+∥u−v∥2=2∥u∥2+2∥v∥2.\lVert u + v\rVert^2 + \lVert u - v\rVert^2 = 2\lVert u\rVert^2 + 2\lVert v\rVert^2 .

For u=e1u = e_1 and v=e2v = e_2 the ℓ1\ell_1 norm gives 22+22=82^2 + 2^2 = 8 on the left and 2+2=42 + 2 = 4 on the right, and the ℓ∞\ell_\infty norm gives 12+12=21^2 + 1^2 = 2 against 44, so neither has an inner product behind it. Without one there is no notion of angle, and none of the projections below.

The Cauchy–Schwarz inequality#

An angle in any inner product space would be defined by

cos⁡θ=⟨u,v⟩∥u∥ ∥v∥,\cos\theta = \frac{\langle u, v\rangle}{\lVert u\rVert\, \lVert v\rVert} ,

which makes sense only if the ratio lies between −1-1 and 11. It always does: the Cauchy–Schwarz inequality says that

∣⟨u,v⟩∣≤∥u∥ ∥v∥,\lvert\langle u, v\rangle\rvert \le \lVert u\rVert\, \lVert v\rVert ,

with equality exactly when one of uu, vv is a multiple of the other.

Why? Split uu into a part along vv and a part orthogonal to it (Axler, 2024, 6.13–6.14). If v=0v = 0 both sides are zero. Otherwise put t=⟨u,v⟩/∥v∥2t = \langle u, v\rangle / \lVert v\rVert^2 and w=u−tvw = u - tv. Then ⟨w,v⟩=⟨u,v⟩−t∥v∥2=0\langle w, v\rangle = \langle u, v\rangle - t\lVert v\rVert^2 = 0, so u=tv+wu = tv + w with w⊥vw \perp v, and

∥u∥2=t2∥v∥2+∥w∥2Pythagoras≥t2∥v∥2=⟨u,v⟩2∥v∥2.\begin{aligned} \lVert u\rVert^2 &= t^2 \lVert v\rVert^2 + \lVert w\rVert^2 && \text{Pythagoras} \\ &\ge t^2 \lVert v\rVert^2 \\ &= \frac{\langle u, v\rangle^2}{\lVert v\rVert^2} . \end{aligned}

Multiplying by ∥v∥2\lVert v\rVert^2 and taking square roots gives the inequality. Equality holds exactly when w=0w = 0, that is, when u=tvu = tv. The part tvtv is the projection of uu onto the line of vv, the subject of a section below; the inequality says that a projection is never longer than the vector.

For u=(1,2,2)u = (1, 2, 2) and v=(2,0,1)v = (2, 0, 1): ⟨u,v⟩=4\langle u, v\rangle = 4, ∥u∥=3\lVert u\rVert = 3 and ∥v∥=5≈2.236\lVert v\rVert = \sqrt 5 \approx 2.236, so 4≤6.7084 \le 6.708, cos⁡θ=0.596\cos\theta = 0.596 and θ≈53.4°\theta \approx 53.4°. Over 100,000100{,}000 random pairs in R5\mathbb R^5 the largest ratio in the Code section is 0.99790.9979, never above 1.

The triangle inequality for the norm of an inner product follows in one step:

∥u+v∥2=∥u∥2+2⟨u,v⟩+∥v∥2≤∥u∥2+2∥u∥ ∥v∥+∥v∥2Cauchy–Schwarz=(∥u∥+∥v∥)2.\begin{aligned} \lVert u + v\rVert^2 &= \lVert u\rVert^2 + 2\langle u, v\rangle + \lVert v\rVert^2 \\ &\le \lVert u\rVert^2 + 2\lVert u\rVert\, \lVert v\rVert + \lVert v\rVert^2 && \text{Cauchy–Schwarz} \\ &= \big(\lVert u\rVert + \lVert v\rVert\big)^2 . \end{aligned}

So does the bound between norms used above, by Cauchy–Schwarz for the vectors (1,…,1)(1, \dots, 1) and (∣v1∣,…,∣vn∣)(\lvert v_1\rvert, \dots, \lvert v_n\rvert):

∥v∥1=∑i1⋅∣vi∣≤n ∥v∥2.\lVert v\rVert_1 = \sum_i 1 \cdot \lvert v_i\rvert \le \sqrt n\, \lVert v\rVert_2 .

In probability the same inequality is why a correlation lies between −1-1 and 11. Apply it to ⟨X,Y⟩=E[XY]\langle X, Y\rangle = \mathbb E[XY] for the centred variables X−EXX - \mathbb E X and Y−EYY - \mathbb E Y with positive variances; the proof above used only ∥w∥2≥0\lVert w\rVert^2 \ge 0 and ∥v∥>0\lVert v\rVert \gt 0. It gives ∣Cov⁡(X,Y)∣≤σXσY\lvert\operatorname{Cov}(X, Y)\rvert \le \sigma_X \sigma_Y.

Cosine similarity in embeddings#

Embedding models compare words, sentences and images by the cosine of the angle between their vectors:

cos⁡(u,v)=⟨u,v⟩∥u∥ ∥v∥∈[−1,1].\cos(u, v) = \frac{\langle u, v\rangle}{\lVert u\rVert\, \lVert v\rVert} \in [-1, 1] .

The word-embedding note uses it to find neighbours, and semantic search ranks passages by it. It ignores lengths, which in embeddings often reflect frequency rather than meaning. For unit vectors, cosine and distance carry the same information:

∥u−v∥2=∥u∥2−2⟨u,v⟩+∥v∥2=2−2cos⁡(u,v)∥u∥=∥v∥=1.\begin{aligned} \lVert u - v\rVert^2 &= \lVert u\rVert^2 - 2\langle u, v\rangle + \lVert v\rVert^2 \\ &= 2 - 2\cos(u, v) && \lVert u\rVert = \lVert v\rVert = 1 . \end{aligned}

The nearest neighbours by cosine are therefore the nearest by Euclidean distance after every vector is normalized, which is why retrieval systems normalize once and then use fast distance search. Without normalization the two rankings differ. In the Code section, 1000 random vectors in R50\mathbb R^{50} with lengths scaled by a random log-normal factor (standard deviation 0.5 on the log scale) are searched with 100 random queries. The nearest neighbour by raw Euclidean distance is the nearest by cosine for 25 of the 100 queries, and after normalization for all 100.

Attention compares queries and keys by the raw dot product instead of the cosine, so there lengths do matter (why a dot product).

In high dimensions unrelated vectors are almost orthogonal. For two independent random directions in Rd\mathbb R^d, uniform on the unit sphere, the cosine has mean 0 and variance exactly 1/d1/d. Rotate both so that the first becomes e1e_1: an orthogonal matrix, as shown below, keeps inner products, and the second direction stays uniform, so the cosine is its first coordinate v1v_1. Flipping the sign of v1v_1 keeps the distribution, so E[v1]=0\mathbb E[v_1] = 0. All dd coordinates have the same distribution and v12+⋯+vd2=1v_1^2 + \dots + v_d^2 = 1, so E[v12]=1/d\mathbb E[v_1^2] = 1/d. For d=768d = 768 the standard deviation is 1/768=0.0361/\sqrt{768} = 0.036, so a cosine of 0.20.2, more than five standard deviations, is far from chance, even though it looks small.

Projection onto a line#

Which multiple of aa is closest to bb? The foot of the perpendicular: the error e=b−x^ae = b - \hat x a must be orthogonal to aa, and that single condition fixes x^\hat x:

a⊤(b−x^a)=0a⊤b−x^ a⊤a=0x^=a⊤ba⊤a.\begin{aligned} a^\top (b - \hat x a) &= 0 \\ a^\top b - \hat x\, a^\top a &= 0 \\ \hat x &= \frac{a^\top b}{a^\top a} . \end{aligned}

The projection is p=x^ap = \hat x a. Since a⊤ba^\top b is a number, it can be moved, and p=Pbp = Pb with the projection matrix

P=aa⊤a⊤a.P = \frac{a a^\top}{a^\top a} .

Doubling bb doubles pp; doubling aa does not change pp, because only the line matters (Strang, 2011, lecture 15). It is the closest point of the line: any other point tata has b−ta=e+(x^−t) ab - ta = e + (\hat x - t)\,a with e⊥ae \perp a, so by Pythagoras

∥b−ta∥2=∥e∥2+(x^−t)2∥a∥2≥∥e∥2.\lVert b - ta\rVert^2 = \lVert e\rVert^2 + (\hat x - t)^2 \lVert a\rVert^2 \ge \lVert e\rVert^2 .

For a=(2,1)a = (2, 1) and b=(3,4)b = (3, 4): a⊤b=10a^\top b = 10 and a⊤a=5a^\top a = 5, so x^=2\hat x = 2, p=(4,2)p = (4, 2) and e=(−1,2)e = (-1, 2). The error is perpendicular, a⊤e=−2+2=0a^\top e = -2 + 2 = 0, and ∥b∥2=25=20+5=∥p∥2+∥e∥2\lVert b\rVert^2 = 25 = 20 + 5 = \lVert p\rVert^2 + \lVert e\rVert^2. The projection matrix and its action are

P=15(4221),Pb=15(12+86+4)=(42).\begin{aligned} P &= \frac15 \begin{pmatrix} 4 & 2 \\ 2 & 1 \end{pmatrix}, \\ Pb &= \frac15 \begin{pmatrix} 12 + 8 \\ 6 + 4 \end{pmatrix} = \begin{pmatrix} 4 \\ 2 \end{pmatrix} . \end{aligned}

Projection onto a subspace#

Let the subspace be the column space of A∈Rm×nA \in \mathbb R^{m \times n}, with independent columns a1,…,ana_1, \dots, a_n. A point of it is Ax^A\hat x, and the error e=b−Ax^e = b - A\hat x must now be orthogonal to every column, aj⊤e=0a_j^\top e = 0, which is A⊤e=0A^\top e = 0 written as one vector equation:

A⊤(b−Ax^)=0A⊤A x^=A⊤bx^=(A⊤A)−1A⊤b.\begin{aligned} A^\top (b - A\hat x) &= 0 \\ A^\top A\, \hat x &= A^\top b \\ \hat x &= (A^\top A)^{-1} A^\top b . \end{aligned}

The square system in the second line is the normal equations. Its matrix A⊤AA^\top A is invertible because the columns are independent: if A⊤Az=0A^\top A z = 0, then z⊤A⊤Az=∥Az∥2=0z^\top A^\top A z = \lVert Az\rVert^2 = 0, so Az=0Az = 0 and z=0z = 0. The projection is p=Ax^=Pbp = A\hat x = Pb, with

P=A (A⊤A)−1A⊤.P = A\,(A^\top A)^{-1} A^\top .

It is tempting to simplify (A⊤A)−1(A^\top A)^{-1} to A−1(A⊤)−1A^{-1}(A^\top)^{-1}, but a rectangular AA has no inverse. When AA is square and invertible, the simplification is allowed and gives P=IP = I: the column space is the whole space and already contains bb (Strang, 2011, lecture 15). The point pp is the closest one by the same Pythagoras argument as for a line: for any yy, b−Ay=e+A(x^−y)b - Ay = e + A(\hat x - y) with ee orthogonal to A(x^−y)A(\hat x - y), so

∥b−Ay∥2=∥e∥2+∥A(x^−y)∥2.\lVert b - Ay\rVert^2 = \lVert e\rVert^2 + \lVert A(\hat x - y)\rVert^2 .

Two properties characterize the projection matrix. It is idempotent: projecting twice changes nothing,

P2=A(A⊤A)−1(A⊤A)(A⊤A)−1A⊤=P.P^2 = A(A^\top A)^{-1}(A^\top A)(A^\top A)^{-1}A^\top = P .

And it is symmetric, P⊤=PP^\top = P, because (A⊤A)−1(A^\top A)^{-1} is: the inverse of a symmetric SS is symmetric, (S−1)⊤=(S⊤)−1=S−1(S^{-1})^\top = (S^\top)^{-1} = S^{-1}, by the transpose rule. Its trace is nn, the dimension of the subspace, because tr⁡(XY)=∑i,jxijyji=tr⁡(YX)\operatorname{tr}(XY) = \sum_{i,j} x_{ij} y_{ji} = \operatorname{tr}(YX):

tr⁡P=tr⁡((A⊤A)−1A⊤A)=tr⁡In=n.\begin{aligned} \operatorname{tr} P &= \operatorname{tr}\big((A^\top A)^{-1} A^\top A\big) \\ &= \operatorname{tr} I_n = n . \end{aligned}

The error e=(I−P)be = (I - P)b lies in the left null space ker⁡A⊤\ker A^\top of the previous note, since A⊤P=A⊤A^\top P = A^\top. And I−PI - P is the projection onto it: it is symmetric and idempotent, and it fixes every y∈ker⁡A⊤y \in \ker A^\top, because Py=0Py = 0. So every bb splits as Pb+(I−P)bPb + (I - P)b into a part in col⁡(A)\operatorname{col}(A) and a part orthogonal to it. The split is unique: if two splits give p1−p2=e2−e1p_1 - p_2 = e_2 - e_1, that vector is orthogonal to itself and so zero.

Return to the opening: the plane spanned by a1=(1,0,1)a_1 = (1, 0, 1) and a2=(0,1,1)a_2 = (0, 1, 1), and b=(1,2,6)b = (1, 2, 6). The normal equations are

A⊤A=(2112),A⊤b=(78),x^=13(2−1−12)(78)=(23).\begin{aligned} A^\top A &= \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}, \\ A^\top b &= \begin{pmatrix} 7 \\ 8 \end{pmatrix}, \\ \hat x &= \frac13 \begin{pmatrix} 2 & -1 \\ -1 & 2 \end{pmatrix} \begin{pmatrix} 7 \\ 8 \end{pmatrix} = \begin{pmatrix} 2 \\ 3 \end{pmatrix} . \end{aligned}

So p=2a1+3a2=(2,3,5)p = 2a_1 + 3a_2 = (2, 3, 5) and e=(−1,−1,1)e = (-1, -1, 1), with a1⊤e=0a_1^\top e = 0 and a2⊤e=0a_2^\top e = 0. The distance from bb to the plane is ∥e∥=3\lVert e\rVert = \sqrt 3. The projection matrix has trace 2:

P=13(2−11−121112).P = \frac13 \begin{pmatrix} 2 & -1 & 1 \\ -1 & 2 & 1 \\ 1 & 1 & 2 \end{pmatrix} .
Figure

Orthogonal projection onto a line and onto a plane

Projection of a vector onto a line and onto a planeLeft: the line through a = (2, 1), the point b = (3, 4), its projection p = (4, 2) onto the line and the perpendicular e = (−1, 2). Right: the plane spanned by a₁ = (1, 0, 1) and a₂ = (0, 1, 1), drawn in an oblique view; the point b = (1, 2, 6) above it, its projection p = (2, 3, 5) and the perpendicular e = (−1, −1, 1) with a right angle.onto a lineonto a planea = (2, 1)b = (3, 4)p = 2a = (4, 2)e = (−1, 2)span(a)col(A)a₁a₂b = (1, 2, 6)p = (2, 3, 5)e ⊥ col(A)Projection of a vector onto a line and onto a planeLeft: the line through a = (2, 1), the point b = (3, 4), its projection p = (4, 2) onto the line and the perpendicular e = (−1, 2). Right: the plane spanned by a₁ = (1, 0, 1) and a₂ = (0, 1, 1), drawn in an oblique view; the point b = (1, 2, 6) above it, its projection p = (2, 3, 5) and the perpendicular e = (−1, −1, 1) with a right angle.onto a lineonto a planea = (2, 1)b = (3, 4)p = 2a = (4, 2)e = (−1, 2)span(a)col(A)a₁a₂b = (1, 2, 6)p = (2, 3, 5)e ⊥ col(A)
Left: b = (3, 4) projected onto the line through a = (2, 1) gives p = (4, 2), with the error e = (−1, 2) perpendicular to a. Right: b = (1, 2, 6) projected onto the plane of a₁ = (1, 0, 1) and a₂ = (0, 1, 1) gives p = (2, 3, 5) and e = (−1, −1, 1). Oblique view, not to scale.

Least squares as a projection#

When Ax=bAx = b has no solution, the least-squares solution minimizes ∥Ax−b∥\lVert Ax - b\rVert, the distance from bb to the point AxAx of the column space. By the previous section the minimizer is the projection: Ax^=PbA\hat x = Pb, and x^\hat x solves the normal equations. The calculus derivation in the least-squares note and the geometric one here give the same equations. The geometry section of that note draws the projection for a regression with three observations, calls PP the hat matrix, and reads its diagonal as the leverage of each point. In the opening example the best combination is x^=(2,3)\hat x = (2, 3), and no combination comes closer to bb than 3\sqrt 3.

The normal equations are the right description and often the wrong computation: forming A⊤AA^\top A squares the condition number of the problem, as the least-squares note shows with polynomial features. The QR factorization below avoids forming it.

Orthonormal bases#

Vectors q1,…,qnq_1, \dots, q_n are orthonormal if they are mutually orthogonal and of unit length: qi⊤qj=1q_i^\top q_j = 1 for i=ji = j and 00 otherwise. As the columns of a matrix QQ, this is Q⊤Q=IQ^\top Q = I. Orthonormal vectors are automatically independent: if ∑jcjqj=0\sum_j c_j q_j = 0, the inner product with qiq_i leaves ci=0c_i = 0.

In an orthonormal basis, coordinates need no linear system. If x=∑jcjqjx = \sum_j c_j q_j, the inner product with qiq_i removes every term but one:

ci=qi⊤x,x=∑i(qi⊤x) qi.\begin{aligned} c_i &= q_i^\top x, \\ x &= \sum_i (q_i^\top x)\, q_i . \end{aligned}

For orthonormal q1,…,qnq_1, \dots, q_n spanning a subspace of Rm\mathbb R^m, the projection onto it is p=QQ⊤bp = QQ^\top b, the formula A(A⊤A)−1A⊤A(A^\top A)^{-1}A^\top with A=QA = Q and Q⊤Q=IQ^\top Q = I. With q1=(0.8,0.6)q_1 = (0.8, 0.6) and q2=(−0.6,0.8)q_2 = (-0.6, 0.8), the vector x=(2,4)x = (2, 4) has coordinates q1⊤x=4q_1^\top x = 4 and q2⊤x=2q_2^\top x = 2, and indeed 4q1+2q2=(2,4)4q_1 + 2q_2 = (2, 4).

Gram–Schmidt and the QR factorization#

How do we get an orthonormal basis of a given subspace? Elimination made a matrix triangular; the Gram–Schmidt process makes it orthonormal (Strang, 2011, lecture 17). It turns independent vectors a1,…,ana_1, \dots, a_n into orthonormal q1,…,qnq_1, \dots, q_n with the same span at every stage: take the vectors one at a time, remove from each its projections onto the qq‘s already built, and normalize what remains:

vj=aj−∑i<j(qi⊤aj) qi,qj=vj∥vj∥.\begin{aligned} v_j &= a_j - \sum_{i \lt j} (q_i^\top a_j)\, q_i, \\ q_j &= \frac{v_j}{\lVert v_j\rVert} . \end{aligned}

The remainder vjv_j is orthogonal to every earlier qkq_k, since qk⊤qi=0q_k^\top q_i = 0 for i≠ki \ne k leaves one term of the sum:

qk⊤vj=qk⊤aj−∑i<j(qi⊤aj) qk⊤qi=qk⊤aj−qk⊤aj=0.\begin{aligned} q_k^\top v_j &= q_k^\top a_j - \sum_{i \lt j} (q_i^\top a_j)\, q_k^\top q_i \\ &= q_k^\top a_j - q_k^\top a_j = 0 . \end{aligned}

It is nonzero, because aja_j is not in the span of a1,…,aj−1a_1, \dots, a_{j-1}, which is the span of q1,…,qj−1q_1, \dots, q_{j-1}: each qiq_i is a combination of aia_i and earlier qq‘s, and each aia_i is a combination of q1,…,qiq_1, \dots, q_i, as the next display shows, so the two spans grow together.

Record the coefficients as rij=qi⊤ajr_{ij} = q_i^\top a_j for i<ji \lt j and rjj=∥vj∥r_{jj} = \lVert v_j\rVert. Solving the definition of vjv_j for aja_j writes each column of AA as a combination of the first jj columns of QQ:

aj=vj+∑i<j(qi⊤aj) qi=rjj qj+∑i<jrij qi.\begin{aligned} a_j &= v_j + \sum_{i \lt j} (q_i^\top a_j)\, q_i \\ &= r_{jj}\, q_j + \sum_{i \lt j} r_{ij}\, q_i . \end{aligned}

The coefficients of column jj, (r1j,…,rjj,0,…,0)(r_{1j}, \dots, r_{jj}, 0, \dots, 0), have zeros below position jj. Collected as the columns of an upper triangular RR with a positive diagonal, they give the QR factorization

A=QR,A = QR ,

where Q⊤Q=IQ^\top Q = I.

For a1=(4,3)a_1 = (4, 3) and a2=(2,4)a_2 = (2, 4), the figure below:

  1. r11=∥a1∥=5r_{11} = \lVert a_1\rVert = 5 and q1=(0.8,0.6)q_1 = (0.8, 0.6).
  2. r12=q1⊤a2=4r_{12} = q_1^\top a_2 = 4, so the component of a2a_2 along q1q_1 is 4q1=(3.2,2.4)4q_1 = (3.2, 2.4).
  3. v2=a2−4q1=(−1.2,1.6)v_2 = a_2 - 4q_1 = (-1.2, 1.6), and q1⊤v2=−0.96+0.96=0q_1^\top v_2 = -0.96 + 0.96 = 0.
  4. r22=∥v2∥=2r_{22} = \lVert v_2\rVert = 2 and q2=(−0.6,0.8)q_2 = (-0.6, 0.8).

So

(4234)=(0.8−0.60.60.8)(5402).\begin{pmatrix} 4 & 2 \\ 3 & 4 \end{pmatrix} = \begin{pmatrix} 0.8 & -0.6 \\ 0.6 & 0.8 \end{pmatrix} \begin{pmatrix} 5 & 4 \\ 0 & 2 \end{pmatrix} .

The second column of RR, (4,2)(4, 2), is the coordinate vector of a2a_2 in the basis q1,q2q_1, q_2 found in the previous section.

Figure

Gram–Schmidt on two vectors in the plane

The steps of Gram–SchmidtThe vectors a₁ = (4, 3) and a₂ = (2, 4). The unit vector q₁ along a₁; the foot of the perpendicular from a₂ to the line of a₁ at 4q₁ = (3.2, 2.4); the difference v₂ = (−1.2, 1.6), perpendicular to q₁; the unit vector q₂ = (−0.6, 0.8). On the right, the formulas of each step and the matrix R = (5 4; 0 2).a₁a₂1a₁ = (4, 3), a₂ = (2, 4)q₁2r₁₁ = ‖a₁‖ = 5, q₁ = (0.8, 0.6)4q₁3r₁₂ = q₁ · a₂ = 4v₂4v₂ = a₂ − 4q₁ = (−1.2, 1.6)q₂5r₂₂ = ‖v₂‖ = 2, q₂ = (−0.6, 0.8)R = (5 4; 0 2), A = QRThe steps of Gram–SchmidtThe vectors a₁ = (4, 3) and a₂ = (2, 4). The unit vector q₁ along a₁; the foot of the perpendicular from a₂ to the line of a₁ at 4q₁ = (3.2, 2.4); the difference v₂ = (−1.2, 1.6), perpendicular to q₁; the unit vector q₂ = (−0.6, 0.8). On the right, the formulas of each step and the matrix R = (5 4; 0 2).a₁a₂1a₁ = (4, 3), a₂ = (2, 4)q₁2r₁₁ = ‖a₁‖ = 5, q₁ = (0.8, 0.6)4q₁3r₁₂ = q₁ · a₂ = 4v₂4v₂ = a₂ − 4q₁ = (−1.2, 1.6)q₂5r₂₂ = ‖v₂‖ = 2, q₂ = (−0.6, 0.8)R = (5 4; 0 2), A = QR
a₁ = (4, 3) and a₂ = (2, 4). Step 2 normalizes a₁ to q₁. Steps 3–4 subtract from a₂ its projection 4q₁, leaving v₂ = (−1.2, 1.6), perpendicular to q₁; step 5 normalizes it to q₂. The coefficients 5, 4 and 2 form R. Press ▶ to step through.

Least squares through QR#

With A=QRA = QR the normal equations lose QQ, because Q⊤Q=IQ^\top Q = I, and then R⊤R^\top, which is invertible because RR is: back substitution solves Rx=cRx = c for every cc, dividing by the positive rjjr_{jj}, and (R⊤)−1=(R−1)⊤(R^\top)^{-1} = (R^{-1})^\top:

A⊤A x^=A⊤bR⊤Q⊤QR x^=R⊤Q⊤bR⊤R x^=R⊤Q⊤bR x^=Q⊤b.\begin{aligned} A^\top A\, \hat x &= A^\top b \\ R^\top Q^\top Q R\, \hat x &= R^\top Q^\top b \\ R^\top R\, \hat x &= R^\top Q^\top b \\ R\, \hat x &= Q^\top b . \end{aligned}

The last system is triangular and is solved by back substitution; A⊤AA^\top A is never formed. For the opening example, Gram–Schmidt gives q1=(1,0,1)/2q_1 = (1, 0, 1)/\sqrt 2 and

v2=(0,1,1)−12(1,0,1)=(−12,1,12),q2=v2∥v2∥=(−1,2,1)6,\begin{aligned} v_2 &= (0, 1, 1) - \tfrac12 (1, 0, 1) = \big(-\tfrac12, 1, \tfrac12\big) , \\ q_2 &= \frac{v_2}{\lVert v_2\rVert} = \frac{(-1, 2, 1)}{\sqrt 6} , \end{aligned}

since ∥v2∥2=3/2\lVert v_2\rVert^2 = 3/2. The triangular system is

(21/203/2)x^=(7/29/6).\begin{pmatrix} \sqrt 2 & 1/\sqrt 2 \\ 0 & \sqrt{3/2} \end{pmatrix} \hat x = \begin{pmatrix} 7/\sqrt 2 \\ 9/\sqrt 6 \end{pmatrix} .

Its last row gives x^2=3\hat x_2 = 3, and then the first, multiplied by 2\sqrt 2, reads 2x^1+3=72\hat x_1 + 3 = 7, so x^1=2\hat x_1 = 2, as before.

Orthogonal matrices#

A square matrix QQ with orthonormal columns is orthogonal: Q⊤Q=IQ^\top Q = I, so Q−1=Q⊤Q^{-1} = Q^\top, a one-sided inverse of a square matrix being the inverse, and also QQ⊤=IQQ^\top = I, which says the rows are orthonormal too. An orthogonal matrix changes coordinates and keeps every inner product, hence every length, distance and angle:

⟨Qx,Qy⟩=(Qx)⊤(Qy)=x⊤Q⊤Q y=x⊤y.\begin{aligned} \langle Qx, Qy\rangle &= (Qx)^\top (Qy) \\ &= x^\top Q^\top Q\, y \\ &= x^\top y . \end{aligned}

The norm is the case y=xy = x: ∥Qx∥=∥x∥\lVert Qx\rVert = \lVert x\rVert. Products of orthogonal matrices are orthogonal, since (Q1Q2)⊤Q1Q2=Q2⊤Q2=I(Q_1 Q_2)^\top Q_1 Q_2 = Q_2^\top Q_2 = I. In numerical work this is their main virtue: multiplying by QQ does not amplify errors in xx: an error δ\delta becomes QδQ\delta, of the same length (Oseledets, 2024, lecture 2).

Rotations, reflections and permutations are orthogonal. The rotation by θ\theta has the columns (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta) and (−sin⁡θ,cos⁡θ)(-\sin\theta, \cos\theta), unit vectors with zero inner product; a permutation matrix has distinct standard basis vectors as columns; and the reflection below has H⊤H=IH^\top H = I. The rotation by 30°30° moves x=(4,3)x = (4, 3) and y=(2,4)y = (2, 4) but keeps ∥x∥=5\lVert x\rVert = 5 and x⊤y=20x^\top y = 20. A Householder reflection reflects in the hyperplane orthogonal to a vector vv:

H=I−2 vv⊤v⊤v.H = I - \frac{2\, vv^\top}{v^\top v} .

It is symmetric, and, since v⊤vv^\top v is a number,

H⊤H=H2=I−4 vv⊤v⊤v+4 v (v⊤v) v⊤(v⊤v)2=I.\begin{aligned} H^\top H = H^2 &= I - \frac{4\, vv^\top}{v^\top v} + \frac{4\, v\,(v^\top v)\,v^\top}{(v^\top v)^2} \\ &= I . \end{aligned}

With y=∥x∥e1y = \lVert x\rVert e_1, a vector as long as xx, and v=x−y≠0v = x - y \ne 0, it sends xx to yy; the second line uses ∥y∥=∥x∥\lVert y\rVert = \lVert x\rVert:

v⊤v=∥x∥2−2y⊤x+∥y∥2=2(∥x∥2−y⊤x)=2 v⊤x,Hx=x−2 v⊤xv⊤v v=x−v=y.\begin{aligned} v^\top v &= \lVert x\rVert^2 - 2y^\top x + \lVert y\rVert^2 \\ &= 2\big(\lVert x\rVert^2 - y^\top x\big) = 2\, v^\top x , \\ Hx &= x - \frac{2\, v^\top x}{v^\top v}\, v = x - v = y . \end{aligned}

For x=(4,3)x = (4, 3), v=(−1,3)v = (-1, 3) and v⊤v=10v^\top v = 10:

H=I−210(1−3−39)=(0.80.60.6−0.8),H(43)=(50).\begin{aligned} H &= I - \frac{2}{10} \begin{pmatrix} 1 & -3 \\ -3 & 9 \end{pmatrix} = \begin{pmatrix} 0.8 & 0.6 \\ 0.6 & -0.8 \end{pmatrix}, \\ H \begin{pmatrix} 4 \\ 3 \end{pmatrix} &= \begin{pmatrix} 5 \\ 0 \end{pmatrix} . \end{aligned}

Householder QR applies one such reflection per column to clear everything below the diagonal, Hn⋯H1A=RH_n \cdots H_1 A = R, and since each HiH_i is its own inverse, A=QRA = QR with Q=H1⋯HnQ = H_1 \cdots H_n. Givens rotations, which act on two coordinates at a time, do the same one entry at a time and suit sparse matrices.

PCA rotates centred data into the orthonormal basis of its principal directions, an orthogonal change of coordinates that keeps all distances (dimensionality reduction). Orthogonal weight matrices keep the scale of a signal through any number of linear layers, which motivates orthogonal initialization (Saxe, McClelland and Ganguli, 2014) and the orthogonal regularization of BigGAN.

The Code section multiplies 50 random 100×100100 \times 100 matrices WW with independent Gaussian entries of mean 0 and variance 1/n=1/1001/n = 1/100. Their average effect on the squared length of a fixed xx is exactly 1, because the cross terms wijwikw_{ij} w_{ik} with j≠kj \ne k have mean zero:

E∥Wx∥2=∑iE[(∑jwijxj)2]=∑i∑j1n xj2=∥x∥2.\begin{aligned} \mathbb E \lVert Wx\rVert^2 &= \sum_i \mathbb E\Big[\Big(\sum_j w_{ij} x_j\Big)^2\Big] \\ &= \sum_i \sum_j \tfrac1n\, x_j^2 = \lVert x\rVert^2 . \end{aligned}

Yet the product stretches some direction by a factor of 6.9 and shrinks another by a factor below 10−1610^{-16}, too small for double precision to resolve: that direction of the input is lost. With orthogonal matrices every direction keeps its length exactly. The normalization note studies the same multiplication of scales with nonlinearities in between.

Where it breaks#

Gram–Schmidt is exact in exact arithmetic and fragile in floating point. Classical Gram–Schmidt projects the original aja_j; when the columns are nearly dependent, vjv_j is a small difference of large vectors, and rounding errors in it are no longer orthogonal to the earlier qq‘s. Modified Gram–Schmidt subtracts the projections one at a time from the running remainder. It is the same in exact arithmetic and much better in floating point. Library routines (numpy.linalg.qr, LAPACK) use Householder reflections instead.

Take the polynomial features 1,t,…,t111, t, \dots, t^{11} on 50 points of [0,1][0, 1], a 50×1250 \times 12 matrix with condition number about 10810^8, and measure how far the computed QQ is from orthonormal:

Method∥Q⊤Q−I∥F\lVert Q^\top Q - I\rVert_F
classical Gram–Schmidt22
modified Gram–Schmidt3⋅10−93 \cdot 10^{-9}
Householder QR2⋅10−152 \cdot 10^{-15}

Classical Gram–Schmidt loses orthogonality completely. The modified version loses about κu=108⋅10−16\kappa u = 10^8 \cdot 10^{-16}, the condition number κ\kappa times the rounding unit uu. Both rates are proved theorems: the loss of orthogonality grows like κ u\kappa\, u for modified Gram–Schmidt (Björck, 1967) and like κ2u\kappa^2 u for the classical one, as long as κ2u\kappa^2 u stays below 1 (Giraud et al., 2005); here κ2u≈1\kappa^2 u \approx 1, and nothing is left. Householder stays at rounding level. Why algorithms that agree in exact arithmetic differ this much is the subject of the conditioning note.

The other formulas have limits of their own. With dependent columns A⊤AA^\top A is singular; the projection still exists, and the SVD note computes it with the pseudoinverse. And the Euclidean inner product is a choice: distances and angles change when features are rescaled, so features in different units need scaling first, or a weighted inner product such as the Mahalanobis one.

What you should remember#

  • An inner product is symmetric, linear and positive definite; it gives lengths, distances, angles and Pythagoras.
  • Cauchy–Schwarz, ∣⟨u,v⟩∣≤∥u∥ ∥v∥\lvert\langle u, v\rangle\rvert \le \lVert u\rVert\, \lVert v\rVert: a projection is never longer than the vector.
  • For unit vectors, ∥u−v∥2=2−2cos⁡(u,v)\lVert u - v\rVert^2 = 2 - 2\cos(u, v); random directions in Rd\mathbb R^d have cosines of about 1/d1/\sqrt d.
  • Projection: the error is orthogonal to the subspace, A⊤Ax^=A⊤bA^\top A\hat x = A^\top b, P=A(A⊤A)−1A⊤P = A(A^\top A)^{-1}A^\top with P2=P=P⊤P^2 = P = P^\top.
  • Gram–Schmidt gives A=QRA = QR, and least squares becomes Rx^=Q⊤bR\hat x = Q^\top b; in practice, Householder QR.
  • Orthogonal matrices keep lengths and angles: Q−1=Q⊤Q^{-1} = Q^\top.

Code#

The examples of the note: norms, the parallelogram law, Cauchy–Schwarz, cosine against distance, the two projections, Gram–Schmidt and QR, the loss of orthogonality, orthogonal matrices and fifty layers of random matrices. Seeds are fixed; exact numbers can differ across platforms and library versions, especially for the orthogonality errors and the smallest stretch factor, and Householder QR may return columns of QQ with the opposite sign. The script runs in a few seconds.

import numpy as np

rng = np.random.default_rng(0)
norm = np.linalg.norm

# norms of v = (3, -4), of x = (0.6, 0.8), and the Frobenius norm of a matrix
v = np.array([3., -4])
print(norm(v, 1), norm(v), norm(v, np.inf))                   # 7.0 5.0 4.0
x0 = np.array([0.6, 0.8])
print(round(norm(x0, 1), 6), round(norm(x0), 6), round(norm(x0, np.inf), 6))   # 1.4 1.0 0.8: outside, on, inside the unit balls
A = np.array([[1., 2], [3, 4]])
print(round(norm(A, 'fro'), 3), round(np.sqrt(np.trace(A.T @ A)), 3))   # 5.477 5.477

# the parallelogram law holds for the 2-norm and fails for the 1-norm
e1, e2 = np.eye(2)
for p in (2, 1):
    print(p, round(norm(e1 + e2, p) ** 2 + norm(e1 - e2, p) ** 2, 6), 2 * (norm(e1, p) ** 2 + norm(e2, p) ** 2))
# 2 4.0 4.0 | 1 8.0 4.0

# Cauchy-Schwarz and the angle between u = (1, 2, 2) and w = (2, 0, 1)
u, w = np.array([1., 2, 2]), np.array([2., 0, 1])
c = u @ w / (norm(u) * norm(w))
print(u @ w, norm(u), round(norm(w), 3), round(c, 3), round(np.degrees(np.arccos(c)), 1))   # 4.0 3.0 2.236 0.596 53.4
X, Y = rng.normal(size=(2, 100_000, 5))
print(round((np.abs((X * Y).sum(1)) / (norm(X, axis=1) * norm(Y, axis=1))).max(), 4))      # 0.9979: never above 1

# cosine similarity: for unit vectors, squared distance = 2 - 2 cos, so the neighbours agree
E = rng.normal(size=(1000, 50)) * rng.lognormal(0, 0.5, size=(1000, 1))   # vectors of varying length
q = rng.normal(size=(100, 50))
cos = (q @ E.T) / (norm(q, axis=1)[:, None] * norm(E, axis=1))
dist = norm(q[:, None, :] - E[None], axis=2)
En = E / norm(E, axis=1, keepdims=True); qn = q / norm(q, axis=1, keepdims=True)
dist_n = norm(qn[:, None, :] - En[None], axis=2)
print((cos.argmax(1) == dist.argmin(1)).mean(), (cos.argmax(1) == dist_n.argmin(1)).mean(),
      np.allclose(dist_n ** 2, 2 - 2 * cos))
# 0.25 1.0 True: raw distances pick other neighbours; after normalizing they agree with cosine
U1, V1 = rng.normal(size=(2, 20_000, 768))
c768 = (U1 * V1).sum(1) / (norm(U1, axis=1) * norm(V1, axis=1))
print(round(c768.std(), 4), round(1 / np.sqrt(768), 4))      # 0.0361 0.0361: random directions are nearly orthogonal

# projection onto the line through a = (2, 1)
a, b = np.array([2., 1]), np.array([3., 4])
p = (a @ b) / (a @ a) * a
Pa = np.outer(a, a) / (a @ a)
print((a @ b) / (a @ a), p, b - p, a @ (b - p), b @ b, p @ p + (b - p) @ (b - p), (5 * Pa).tolist())
# 2.0 [4. 2.] [-1.  2.] 0.0 25.0 25.0 [[4.0, 2.0], [2.0, 1.0]]
print(np.allclose(np.outer(2 * a, 2 * a) / ((2 * a) @ (2 * a)), Pa))   # True: doubling a leaves P unchanged

# projection onto the plane spanned by (1, 0, 1) and (0, 1, 1)
A2 = np.column_stack([[1., 0, 1], [0, 1, 1]]); b2 = np.array([1., 2, 6])
xh = np.linalg.solve(A2.T @ A2, A2.T @ b2)
P = A2 @ np.linalg.inv(A2.T @ A2) @ A2.T
print(xh, A2 @ xh, b2 - A2 @ xh, A2.T @ (b2 - A2 @ xh))         # [2. 3.] [2. 3. 5.] [-1. -1.  1.] [0. 0.]
print((3 * P).round(6).tolist(), np.allclose(P @ P, P), np.allclose(P, P.T), round(np.trace(P), 6))
# [[2.0, -1.0, 1.0], [-1.0, 2.0, 1.0], [1.0, 1.0, 2.0]] True True 2.0

# Gram-Schmidt, by hand on a1 = (4, 3), a2 = (2, 4)
def gram_schmidt(A, modified=False):
    m, n = A.shape; Q = np.zeros((m, n)); R = np.zeros((n, n))
    for j in range(n):
        vj = A[:, j].copy()
        for i in range(j):
            R[i, j] = Q[:, i] @ (vj if modified else A[:, j])   # classical: project a_j; modified: the running v_j
            vj -= R[i, j] * Q[:, i]
        R[j, j] = norm(vj); Q[:, j] = vj / R[j, j]
    return Q, R
Q, R = gram_schmidt(np.array([[4., 2], [3, 4]]))
print(Q.round(6).tolist(), R.round(6).tolist())    # [[0.8, -0.6], [0.6, 0.8]] [[5.0, 4.0], [0.0, 2.0]]
print((Q.T @ [2, 4]).round(6), ((Q.T @ Q).round(6) + 0).tolist())   # [4. 2.] [[1.0, 0.0], [0.0, 1.0]]: coordinates of a2 = column 2 of R

# QR of the 3 x 2 matrix, and least squares through R x = Q^T b
Q3, R3 = gram_schmidt(A2)
print(R3.round(4).tolist(), (Q3 * np.sqrt(6)).round(4)[:, 1], np.linalg.solve(R3, Q3.T @ b2), Q3 @ Q3.T @ b2)
# [[1.4142, 0.7071], [0.0, 1.2247]] [-1.  2.  1.] [2. 3.] [2. 3. 5.]
Qn, Rn = np.linalg.qr(A2)                          # Householder (LAPACK); columns may differ in sign
print(np.allclose(np.abs(Rn), np.abs(R3)), np.allclose(Qn @ Rn, A2))   # True True

# loss of orthogonality: classical and modified Gram-Schmidt against Householder QR
V = np.vander(np.linspace(0, 1, 50), 12, increasing=True)            # polynomial features 1, t, ..., t^11
print(f'{np.linalg.cond(V):.0e}', *[f'{norm(Qx.T @ Qx - np.eye(12)):.0e}' for Qx in
      (gram_schmidt(V)[0], gram_schmidt(V, modified=True)[0], np.linalg.qr(V)[0])])
# 1e+08 2e+00 3e-09 2e-15   (cond(V); orthogonality error of classical GS, modified GS, Householder)

# orthogonal matrices: a rotation and a Householder reflection preserve lengths and inner products
t = np.radians(30); Rot = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])
x, y = np.array([4., 3]), np.array([2., 4])
print(np.allclose(Rot.T @ Rot, np.eye(2)), round(norm(Rot @ x), 6), round((Rot @ x) @ (Rot @ y), 6), x @ y)   # True 5.0 20.0 20.0
h = x - norm(x) * e1                                 # reflect (4, 3) onto the first axis
H = np.eye(2) - 2 * np.outer(h, h) / (h @ h)
print(H.round(6).tolist(), (H @ x).round(6) + 0, np.allclose(H @ H, np.eye(2)), round(np.linalg.det(H), 6))
# [[0.8, 0.6], [0.6, -0.8]] [5. 0.] True -1.0

# fifty linear layers of width 100: Gaussian weights (variance 1/n) against orthogonal weights;
# the largest and smallest stretch factors of the product (its largest and smallest singular values)
n, L = 100, 50
G, O = np.eye(n), np.eye(n)
for _ in range(L):
    G = rng.normal(size=(n, n)) / np.sqrt(n) @ G
    O = np.linalg.qr(rng.normal(size=(n, n)))[0] @ O
sG, sO = np.linalg.svd(G, compute_uv=False), np.linalg.svd(O, compute_uv=False)
print(f'{sG[0]:.1f} {sG[-1]:.0e} {sO[0]:.6f} {sO[-1]:.6f}')   # 6.9 2e-20 1.000000 1.000000
# (the smallest Gaussian value is below the rounding level of double precision: only its smallness is meaningful)

Next#

Orthogonal matrices keep every length; a general matrix stretches some directions and shrinks others, as the ellipse of the first note showed. The next note measures this in two ways: the determinant, the factor by which a matrix scales volume and the test for invertibility, and the eigenvectors, the directions that a matrix only stretches. The symmetric matrices that follow combine both with this note: their eigenvectors are orthonormal.

References#