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.
Vectors, spaces and linear maps · Matrices and linear systems
On this page 12
No combination of the columns and equals , 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 ,
and the law of cosines in the triangle with sides , and relates the angle between and to the coordinates. Expanding the same squared length in two ways,
and comparing the two gives
For and the left side is 24 and both lengths are 5, so and . In 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 assigns a number to every pair of vectors such that, for all and numbers :
- it is symmetric: ;
- it is linear in the first argument: , and so, by symmetry, in the second;
- it is positive definite: for every .
It defines a length, the norm , and a distance . Four inner products appear in this course:
The first, the dot product of , is the default from now on. The second needs a symmetric matrix with for every ; with for a covariance matrix , its norm is the Mahalanobis distance of the multivariate Gaussian. The third, the trace inner product of matrices, multiplies entries in matching positions, since ; , the trace, is the sum of the diagonal entries, and . The fourth acts on continuous functions on , and it is positive definite because a continuous is nonzero on a whole interval, so ; the constant 1 and the function have .
Two vectors are orthogonal, , when . Expanding by linearity gives Pythagoras in any inner product space:
Norms#
A length can be defined without an inner product. A norm is any function with for , , and the triangle inequality . Three norms on are used constantly, and a fourth on matrices:
For they give , and . The Frobenius norm is the norm of the matrix read as one long vector, and the norm of the trace inner product; for
it is . The , and norms belong to one family, the norms for :
Each of them satisfies the triangle inequality. For and it follows entry by entry from . For and the Frobenius norm the next section derives it from Cauchy–Schwarz. For general it is Minkowski’s inequality, which follows from the convexity of the unit ball.
Derivation: Minkowski’s inequality from a convex ball
The function is convex and nondecreasing for , its second derivative being nonnegative for , and is convex. So is convex by the composition rule, and so is the sum . Its ball is convex: for , . For put :
The right side mixes two points of , so it lies in and has norm at most 1. Multiplying by gives .
The shape of a norm is the shape of its unit ball, the set of vectors of norm at most 1:
Unit balls of the ℓ₁, ℓ₂ and ℓ∞ norms in the plane
The balls are nested, because for every : the largest is at most the sum of all of them, and is plus nonnegative cross terms. In the other direction , as the next section shows, and , since each of the terms of is at most . So these norms are equivalent up to constants, but the constants grow with . The shapes also matter for what a penalty prefers. The corners of the ball sit on the axes, which is why the lasso, which constrains , produces weights that are exactly zero (the constrained form).
Of these norms, only 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:
For and the norm gives on the left and on the right, and the norm gives against , 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
which makes sense only if the ratio lies between and . It always does: the Cauchy–Schwarz inequality says that
with equality exactly when one of , is a multiple of the other.
Why? Split into a part along and a part orthogonal to it (Axler, 2024, 6.13–6.14). If both sides are zero. Otherwise put and . Then , so with , and
Multiplying by and taking square roots gives the inequality. Equality holds exactly when , that is, when . The part is the projection of onto the line of , the subject of a section below; the inequality says that a projection is never longer than the vector.
For and : , and , so , and . Over random pairs in the largest ratio in the Code section is , never above 1.
The triangle inequality for the norm of an inner product follows in one step:
So does the bound between norms used above, by Cauchy–Schwarz for the vectors and :
In probability the same inequality is why a correlation lies between and . Apply it to for the centred variables and with positive variances; the proof above used only and . It gives .
Cosine similarity in embeddings#
Embedding models compare words, sentences and images by the cosine of the angle between their vectors:
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:
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 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 , uniform on the unit sphere, the cosine has mean 0 and variance exactly . Rotate both so that the first becomes : an orthogonal matrix, as shown below, keeps inner products, and the second direction stays uniform, so the cosine is its first coordinate . Flipping the sign of keeps the distribution, so . All coordinates have the same distribution and , so . For the standard deviation is , so a cosine of , more than five standard deviations, is far from chance, even though it looks small.
Projection onto a line#
Which multiple of is closest to ? The foot of the perpendicular: the error must be orthogonal to , and that single condition fixes :
The projection is . Since is a number, it can be moved, and with the projection matrix
Doubling doubles ; doubling does not change , because only the line matters (Strang, 2011, lecture 15). It is the closest point of the line: any other point has with , so by Pythagoras
For and : and , so , and . The error is perpendicular, , and . The projection matrix and its action are
Projection onto a subspace#
Let the subspace be the column space of , with independent columns . A point of it is , and the error must now be orthogonal to every column, , which is written as one vector equation:
The square system in the second line is the normal equations. Its matrix is invertible because the columns are independent: if , then , so and . The projection is , with
It is tempting to simplify to , but a rectangular has no inverse. When is square and invertible, the simplification is allowed and gives : the column space is the whole space and already contains (Strang, 2011, lecture 15). The point is the closest one by the same Pythagoras argument as for a line: for any , with orthogonal to , so
Two properties characterize the projection matrix. It is idempotent: projecting twice changes nothing,
And it is symmetric, , because is: the inverse of a symmetric is symmetric, , by the transpose rule. Its trace is , the dimension of the subspace, because :
The error lies in the left null space of the previous note, since . And is the projection onto it: it is symmetric and idempotent, and it fixes every , because . So every splits as into a part in and a part orthogonal to it. The split is unique: if two splits give , that vector is orthogonal to itself and so zero.
Return to the opening: the plane spanned by and , and . The normal equations are
So and , with and . The distance from to the plane is . The projection matrix has trace 2:
Orthogonal projection onto a line and onto a plane
Least squares as a projection#
When has no solution, the least-squares solution minimizes , the distance from to the point of the column space. By the previous section the minimizer is the projection: , and 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 the hat matrix, and reads its diagonal as the leverage of each point. In the opening example the best combination is , and no combination comes closer to than .
The normal equations are the right description and often the wrong computation: forming 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 are orthonormal if they are mutually orthogonal and of unit length: for and otherwise. As the columns of a matrix , this is . Orthonormal vectors are automatically independent: if , the inner product with leaves .
In an orthonormal basis, coordinates need no linear system. If , the inner product with removes every term but one:
For orthonormal spanning a subspace of , the projection onto it is , the formula with and . With and , the vector has coordinates and , and indeed .
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 into orthonormal with the same span at every stage: take the vectors one at a time, remove from each its projections onto the ‘s already built, and normalize what remains:
The remainder is orthogonal to every earlier , since for leaves one term of the sum:
It is nonzero, because is not in the span of , which is the span of : each is a combination of and earlier ‘s, and each is a combination of , as the next display shows, so the two spans grow together.
Record the coefficients as for and . Solving the definition of for writes each column of as a combination of the first columns of :
The coefficients of column , , have zeros below position . Collected as the columns of an upper triangular with a positive diagonal, they give the QR factorization
where .
For and , the figure below:
- and .
- , so the component of along is .
- , and .
- and .
So
The second column of , , is the coordinate vector of in the basis found in the previous section.
Gram–Schmidt on two vectors in the plane
Least squares through QR#
With the normal equations lose , because , and then , which is invertible because is: back substitution solves for every , dividing by the positive , and :
The last system is triangular and is solved by back substitution; is never formed. For the opening example, Gram–Schmidt gives and
since . The triangular system is
Its last row gives , and then the first, multiplied by , reads , so , as before.
Orthogonal matrices#
A square matrix with orthonormal columns is orthogonal: , so , a one-sided inverse of a square matrix being the inverse, and also , which says the rows are orthonormal too. An orthogonal matrix changes coordinates and keeps every inner product, hence every length, distance and angle:
The norm is the case : . Products of orthogonal matrices are orthogonal, since . In numerical work this is their main virtue: multiplying by does not amplify errors in : an error becomes , of the same length (Oseledets, 2024, lecture 2).
Rotations, reflections and permutations are orthogonal. The rotation by has the columns and , unit vectors with zero inner product; a permutation matrix has distinct standard basis vectors as columns; and the reflection below has . The rotation by moves and but keeps and . A Householder reflection reflects in the hyperplane orthogonal to a vector :
It is symmetric, and, since is a number,
With , a vector as long as , and , it sends to ; the second line uses :
For , and :
Householder QR applies one such reflection per column to clear everything below the diagonal, , and since each is its own inverse, with . 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 matrices with independent Gaussian entries of mean 0 and variance . Their average effect on the squared length of a fixed is exactly 1, because the cross terms with have mean zero:
Yet the product stretches some direction by a factor of 6.9 and shrinks another by a factor below , 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 ; when the columns are nearly dependent, is a small difference of large vectors, and rounding errors in it are no longer orthogonal to the earlier ‘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 on 50 points of , a matrix with condition number about , and measure how far the computed is from orthonormal:
| Method | |
|---|---|
| classical Gram–Schmidt | |
| modified Gram–Schmidt | |
| Householder QR |
Classical Gram–Schmidt loses orthogonality completely. The modified version loses about , the condition number times the rounding unit . Both rates are proved theorems: the loss of orthogonality grows like for modified Gram–Schmidt (Björck, 1967) and like for the classical one, as long as stays below 1 (Giraud et al., 2005); here , 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 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, : a projection is never longer than the vector.
- For unit vectors, ; random directions in have cosines of about .
- Projection: the error is orthogonal to the subspace, , with .
- Gram–Schmidt gives , and least squares becomes ; in practice, Householder QR.
- Orthogonal matrices keep lengths and angles: .
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 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#
- S. Axler. Linear Algebra Done Right, 4th ed. Springer, 2024 (open access). Section 6A (inner products and norms; 6.13, an orthogonal decomposition, and 6.14, the Cauchy–Schwarz inequality), section 6B (orthonormal bases, Gram–Schmidt).
- G. Strang. 18.06SC Linear Algebra, MIT OpenCourseWare, 2011. Lecture summaries: projections onto subspaces (lecture 15) and orthogonal matrices and Gram–Schmidt (lecture 17).
- I. Oseledets. Numerical Linear Algebra, course notebooks, 2024. Lecture 2 (matrix norms, scalar products, unitary matrices, Householder reflections and Givens rotations).
- A. M. Saxe, J. L. McClelland, S. Ganguli. Exact solutions to the nonlinear dynamics of learning in deep linear neural networks. ICLR, 2014.
- Å. Björck. Solving linear least squares problems by Gram–Schmidt orthogonalization. BIT 7, 1–21, 1967.
- L. Giraud, J. Langou, M. Rozložník, J. van den Eshof. Rounding error analysis of the classical Gram–Schmidt orthogonalization process. Numerische Mathematik 101, 87–100, 2005.