Define operator, Frobenius and Schatten norms, express them through singular values and use the condition number to bound the sensitivity of Ax = b. Connect norms to Lipschitz constants in networks, leaving detailed numerical error analysis to Module 09.
After this lesson you can
Compute ℓ1, ℓ2 and ℓ∞ operator norms, and the Frobenius and nuclear norms, and relate them to singular values.
Prove that the spectral norm is σ₁ and that ‖A‖₂ ≤ ‖A‖_F ≤ √r‖A‖₂.
Derive a relative perturbation bound for Ax = b in terms of κ(A).
Estimate digits lost when solving a system from its condition number.
Bound the Lipschitz constant of a linear network and apply spectral normalization.
First question. A network layer is x↦Wx. If someone changes its input by δx (sensor noise, rounding error, an adversarial attack), output changes by Wδx. How much can that change grow in the worst case? And if you stack fifty layers, how much does it grow by the end?
Second question. Solve the system
[1111.0001]x=[22.0001],
whose solution is x=(1,1). Now change the second component of b in the fourth decimal place, from 2.0001 to 2.0002. The new solution is x=(0,2): a relative change 5×10−5 in data produced a 100% relative change in the answer. No algorithm is to blame; this is how the problem behaves. How can we foresee this and how many digits of a computed solution can we trust?
Both questions ask the same thing: how much a matrix can amplify a perturbation. The answer has two pieces. First is a way to measure matrix size that respects its action on vectors: matrix norms, especially the operator norm. Second is the ratio of maximum to minimum stretch, the condition number, which says how many digits are lost when solving a system. With the previous lesson’s SVD, both can be read directly from singular values.
By the end you will be able to:
Calculate and bound ∥A∥1,∥A∥2,∥A∥∞, the Frobenius norm and the nuclear norm, and know which to use.
Predict, before running anything, how many correct digits a system’s solution will have in float64, float32 or bfloat16.
Bound a network’s Lipschitz constant and control it with spectral normalization, as in GAN discriminators.
Matrix norms
Matrices m×n form a vector space of dimension mn, so a matrix norm is, to begin with, a vector norm on Rm×n: a function ∥⋅∥ with
∥A∥≥0, and ∥A∥=0 only if A=0;
∥cA∥=∣c∣∥A∥ for every scalar c;
∥A+B∥≤∥A∥+∥B∥.
What distinguishes a matrix from a long vector is that matrices multiply. A norm useful for analysis must work well with products. A family of norms (one for each size) is submultiplicative if
∥AB∥≤∥A∥∥B∥
whenever the product is defined. This property bounds the effect of a chain of layers or a power Ak by multiplying bounds for each factor.
Not every norm has it. The maximum entry magnitude ∥A∥max=maxij∣aij∣ is a norm on Rm×n, but with J=[1111] we have J2=2J and
J2max=2>1=∥J∥max2.
Entry sizes do not reveal what happens under multiplication, because they ignore how contributions from each row and column add. The norms that matter here are built around matrices as maps, not tables of numbers.
The operator norm: maximum stretch
The most natural idea is to measure a matrix by what it does: how much it can stretch a vector at most.
The two expressions coincide because scaling x does not change the quotient. The maximum exists (not merely a supremum) for a concrete reason: unit sphere {x:∥x∥α=1} is closed and bounded in Rn, hence compact, a property relying on completeness of the real numbers, and x↦∥Ax∥β is continuous. By the Weierstrass theorem, it attains its maximum. There is therefore a unit vector x⋆ with ∥Ax⋆∥=∥A∥: the worst case exists and can be found.
Geometrically, ∥A∥p is the smallest t such that the image of unit ball Bp fits in ball tBp. If the ball is a diamond, its image is a parallelogram and the maximum lies at a vertex; if a circle, its image is an ellipse and the maximum is its major semiaxis.
InteractiveThe operator norm as maximum stretch
Choose the norm (ℓ1, ℓ2 or ℓ∞) and drag columns a1,a2 of A. The blue region is the unit ball's image and the magenta curve the smallest ∥A∥pBp ball containing it; contact point Ax⋆ marks the worst case. Move point x around the boundary and inspect the lower curve: for ℓ1 maxima always occur at vertices ±ej and for ℓ∞ at corners (±1,±1). Try the 45° rotation: its spectral norm is 1, but norms ℓ1 and ℓ∞ equal 2.
Before computing anything, the properties making the operator norm an analysis tool:
Proof
(1) If ∥A∥=0, then Ax=0 for every x and A=0. Homogeneity follows from ∥cAx∥=∣c∣∥Ax∥. For the triangle inequality, for each unit x, ∥(A+B)x∥≤∥Ax∥+∥Bx∥≤∥A∥+∥B∥, and take the maximum over x.
(2) For x=0, quotient ∥Ax∥/∥x∥ is at most its maximum. If ∥Ax∥≤C∥x∥ for every x, evaluating at x⋆ gives ∥A∥≤C.
(3) Apply (2) twice: ∥ABx∥≤∥A∥∥Bx∥≤∥A∥∥B∥∥x∥; by (2), ∥AB∥≤∥A∥∥B∥.
(4) ∥Ix∥/∥x∥=1 for every x.
(5) If Ax=λx with real x=0, then ∣λ∣∥x∥=∥Ax∥≤∥A∥∥x∥. If λ is complex, x=y+iz is too and the vector norm is defined only on Rn. For p=1,2,∞ use the same formula on Cn, giving the same induced norm. For an arbitrary norm, apply Ak: since Aky and Akz are real and imaginary parts of λkx, and c=mint∈[0,2π](Re(eitx)+Im(eitx))>0 by continuity and compactness, ∣λ∣kc≤Aky+Akz≤∥A∥k(∥y∥+∥z∥) holds for all k. Taking kth roots and letting k→∞ gives ∣λ∣≤∥A∥.
∎
Property (2) has an interpretation used at the lesson’s end: since ∥Ax−Ay∥=∥A(x−y)∥≤∥A∥∥x−y∥, the operator norm is exactly the Lipschitz constant of map x↦Ax.
Three computable norms
For almost every choice of p, computing ∥A∥p is difficult: arbitrary-precision approximation is NP-hard for every rational p other than 1, 2 and ∞ (Hendrickx and Olshevsky, 2010). The three cases used in practice are precisely those with formulas.
Proof
ℓ1. Write Ax=∑jxjaj. By the triangle inequality,
The bound is achieved at x=ej⋆, where j⋆ is the column with largest sum: ∥Aej⋆∥1=∥aj⋆∥1. Geometrically, ℓ1 ball is the convex hull of ±ej, its image is the convex hull of ±aj, and a norm (which is convex) attains its maximum over a polyhedron at a vertex.
ℓ∞. For each row i, ∣(Ax)i∣=∑jaijxj≤∑j∣aij∣∣xj∣≤∥x∥∞∑j∣aij∣. Taking the maximum over i, ∥Ax∥∞≤(maxi∑j∣aij∣)∥x∥∞. To attain it, choose row i⋆ of largest sum and xj=signo(ai⋆j) (with signo(0)=1): then ∥x∥∞=1 and (Ax)i⋆=∑j∣ai⋆j∣. This is the cube corner that “copies the signs” of the row.
ℓ2. This is the guided exercise below, based on the Rayleigh quotient of symmetric matrix A⊤A.
∎
ProofThe spectral norm is the largest singular value
Prove: For every A∈Rm×n, ∥A∥2=max∥x∥2=1∥Ax∥2=σ1(A).
0
Let A∈Rm×n be arbitrary, with singular values σ1≥σ2≥⋯≥0. Use the Rayleigh quotient of a symmetric matrix.
Step 1 of 3. What quantity is convenient to maximize instead of the norm?
Two immediate consequences. If A is symmetric, its singular values are ∣λi∣ and ∥A∥2=maxi∣λi∣: spectral norm equals spectral radius. If Q is orthogonal, ∥Q∥2=1, because it preserves lengths.
Combining the three gives a useful bound costing O(mn) to compute:
∥A∥2≤∥A∥1∥A∥∞.
The one-line proof is ∥A∥22=λ1(A⊤A)≤A⊤A1≤A⊤1∥A∥1=∥A∥∞∥A∥1, using that an eigenvalue is bounded by any operator norm and submultiplicativity.
The Frobenius norm
Another natural way to measure a matrix is to forget it is a map and treat it as a vector in Rmn.
This norm appears in loss functions (squared reconstruction error X−X^F2), weight decay (λ∑ℓW(ℓ)F2), and gradients with respect to a matrix. Three properties connect it to the foregoing.
Read it from singular values. The trace is invariant under cyclic permutation, so with A=UΣV⊤,
∥A∥F2=tr(VΣ⊤U⊤UΣV⊤)=tr(Σ⊤ΣV⊤V)=i∑σi2.
Spectral norm is the largest singular value; Frobenius norm is the Euclidean length of the entire vector of singular values.
It is not an operator norm. Every induced norm satisfies ∥I∥=1, while ∥In∥F=n. Yet it is submultiplicative, and in fact a sharper result holds: if bj are columns of B,
and since ∥A∥2≤∥A∥F (shown now), ∥AB∥F≤∥A∥F∥B∥F.
It is bounded by the spectral norm.
Proof
With nonzero singular values σ1≥⋯≥σr>0, σ12≤∑i=1rσi2≤rσ12. Take square roots. The first inequality is equality if and only if σ2=⋯=σr=0, i.e. r≤1; the second if and only if σi=σ1 for all i≤r.
∎
Ratio ∥A∥F2/∥A∥22=∑iσi2/σ12 lies between 1 and r and is called stable rank: it counts how many directions have stretch comparable to the maximum. Unlike rank it does not jump under tiny perturbations. You will revisit it with effective rank in the next lesson.
Schatten norms and unitary invariance
Spectral norm is the maximum singular value and Frobenius norm their Euclidean norm. The obvious generalization takes any ℓp norm of vector σ=(σ1,…,σmin(m,n)).
Since a vector’s ℓp norms decrease with p, ∥A∥2≤∥A∥F≤∥A∥∗. Since σ has at most r nonzero entries, Cauchy–Schwarz gives ∥A∥∗≤r∥A∥F.
All Schatten norms share a feature: they do not see bases. If U and V are orthogonal, UAV has the same singular values as A (compose the SVDs), so
∥UAV∥Sp=∥A∥Sp.
A norm with this property is unitarily invariant. Norms ∥⋅∥1, ∥⋅∥∞ and maximum entry magnitude are not: they measure the matrix in the canonical basis and change when it rotates. A theorem of von Neumann (1937) says the converse also holds: every unitarily invariant norm is a symmetric absolute function of singular values (a “symmetric gauge function”), so the family is exactly “vector norms applied to σ”.
InteractiveNorms that do not see rotations
The matrix is A=R(φ)diag(σ1,σ2)R(θ)⊤, with R a rotation. Fix σ1,σ2 and press ‘Rotate input’: the three solid curves (spectral, Frobenius, nuclear) are flat, while ∥A∥1, ∥A∥∞ and maximum entry magnitude oscillate. In the singular-value plane, the ℓ∞, ℓ2 and ℓ1 balls through (σ1,σ2) show the ordering of the three norms by size. Move σ2 to 0 and see them coincide.
Unitary invariance explains why these norms appear in problems “without a preferred basis”. Later examples include the Eckart–Young theorem (the best rank-k approximation is truncated SVD for every unitarily invariant norm), the steepest descent direction in spectral norm used by Muon, and network generalization bounds in terms of Schatten norms of weights.
Nuclear norm: the convex substitute for rank
It is not obvious that ∥⋅∥Sp satisfies the triangle inequality: singular values of a matrix sum are not the sums of singular values. For the nuclear norm a clean proof by duality also explains its role in optimization.
Proof
Write the compact SVD A=∑i=1rσiuivi⊤. For each B with ∥B∥2≤1,
by Cauchy–Schwarz and compatibility. Equality is attained at B=∑iuivi⊤=UrVr⊤, whose nonzero singular values all equal 1 and hence spectral norm is 1: then ui⊤Bvi=1 for each i.
∎
A maximum of linear functions is convex and subadditive, so the triangle inequality for ∥⋅∥∗ follows immediately: tr(B⊤(A1+A2))≤∥A1∥∗+∥A2∥∗ for each admissible B. This is the same structure as the vector dual norm: nuclear and spectral are dual to each other, like ℓ1 and ℓ∞. Generally Sp and Sq are dual when 1/p+1/q=1.
Why does this matter? Rank is linear algebra’s most useful and least tractable function: minimizing rank subject to linear constraints is NP-hard in general. But on the unit spectral ball {A:∥A∥2≤1}, the largest convex function below rank (its convex envelope) is exactly the nuclear norm. Scalar intuition is the same as lasso: on [−1,1], the function “0 if x=0, 1 otherwise” has convex envelope ∣x∣; for a diagonal matrix, rank counts nonzero entries and its envelope sums their absolute values. Nuclear norm is ℓ1 of the singular values and produces low-rank solutions for the same reason ℓ1 produces sparse vectors. Recht, Fazel and Parrilo (2010) proved conditions under which nuclear-norm minimization exactly recovers the minimum-rank solution; this underlies matrix completion and robust PCA.
The condition number
Return to the starting system. To measure how A amplifies relative errors when solving Ax=b, its size alone is insufficient: compare how much it stretches with how much it shrinks.
The name comes from Alan Turing, who in “Rounding-off errors in matrix processes” (1948) defined two “condition numbers” (using Frobenius norm and maximum entry magnitude) to measure how ill-conditioned a system is, meaning how much it amplifies data and rounding errors in elimination methods.
Properties that follow directly:
κ(A)≥1, because 1=∥I∥=AA−1≤∥A∥A−1.
κ(cA)=κ(A) for c=0: a measure of shape, not size.
κ2(Q)=1 for orthogonal Q, and κ2(QA)=κ2(AQ)=κ2(A).
κ2(A⊤A)=κ2(A)2, because singular values of A⊤A are σi2. This is why normal equations lose twice as many digits.
In the opening system, κ2≈4.0×104: relative error 5×10−5 in b multiplied by 4×104 gives relative error of order 1 in x. That is exactly what happened.
Two-dimensional geometry is clear. Each equation in a 2×2 system is a line and the solution is their intersection. If lines are nearly parallel, moving one slightly moves the intersection far along them. With rows of A normalized to length 1 and acute angle γ∈(0,π/2] between the lines (the angle between lines equals the angle between their normals), for example a~1=(sin2γ,cos2γ) and a~2=(−sin2γ,cos2γ), we have
AA⊤=[1cosγcosγ1],
with eigenvalues 1±cosγ (eigenvectors (1,1) and (1,−1)). Since cosγ≥0, the largest is 1+cosγ, so σ1,2=1±cosγ and
κ2(A)=1−cosγ1+cosγ=cot2γ.
InteractiveNearly parallel lines
Blue and red lines are the equations; their intersection is solution x. Drag perturbation δb around the data disk: the lines shift (dashed) and intersection moves to x+δx. The magenta cloud is all possible solutions: the disk's image under A−1, an ellipse κ times longer than wide. Close angle γ and watch κ=cot(γ/2) grow. Press ‘Worst case’: relative error amplification reaches exactly κ.
Perturbation bounds
The interactive suggests a theorem: relative solution error is at most κ times relative data error. Construct it.
ProofThe right-hand-side perturbation bound
Prove: If A is invertible, Ax=b=0 and A(x+δx)=b+δb, then ∥x∥∥δx∥≤κ(A)∥b∥∥δb∥ for any operator norm.
0
Fix a vector norm and its induced operator norm.
Step 1 of 4. What equation does δx satisfy?
Errors are not confined to b. Coefficients of A are also measurements, or numbers rounded when stored in memory. The full theorem covers both sources.
Proof
(1) Expand (A+δA)(x+δx)=b and subtract Ax=b to get Aδx=−δA(x+δx). Solve for δx=−A−1δA(x+δx) and take norms: ∥δx∥≤A−1∥δA∥∥x+δx∥. Multiply and divide by ∥A∥.
(2) First, a lemma. If ∥F∥<1, then I+F is invertible and (I+F)−1≤1/(1−∥F∥). Indeed, for every y, ∥(I+F)y∥≥∥y∥−∥Fy∥≥(1−∥F∥)∥y∥: the kernel is trivial (hence it is invertible) and, writing z=(I+F)y, we have (I+F)−1z≤∥z∥/(1−∥F∥).
Now write A+δA=A(I+F) with F=A−1δA, which satisfies ∥F∥≤A−1∥δA∥=η<1. By the lemma, A+δA is invertible and (A+δA)−1≤A−1/(1−η). Subtracting Ax=b from the perturbed equation gives (A+δA)δx=δb−δAx, hence
∥δx∥≤1−ηA−1(∥δb∥+∥δA∥∥x∥).
Divide by ∥x∥ and use ∥δb∥/∥x∥≤∥A∥∥δb∥/∥b∥ (from ∥b∥≤∥A∥∥x∥). Factoring out ∥A∥A−1=κ(A) gives the bound.
∎
Note the role of assumption η<1. If relative matrix perturbation reaches 1/κ, it can make the matrix singular, and no bound is then possible. This is not a proof artifact: it is the next theorem.
Distance to singularity
Proof
If A+δA is singular, there is a unit x with (A+δA)x=0, i.e. Ax=−δAx. Then σn≤∥Ax∥2=∥δAx∥2≤∥δA∥2, because σn is the minimum stretch. Conversely, δA=−σnunvn⊤ has norm σn and (A+δA)vn=σnun−σnun=0.
∎
The result holds for any operator norm with 1/κ(A) (Gastinel–Kahan theorem), and is the best interpretation of condition number: 1/κ is the relative distance of A to the set of singular matrices. A matrix with κ=1012 is one relative perturbation 10−12 away from having no inverse. In float64, merely storing the matrix introduces relative errors 10−16, so that matrix is invertible with little margin. With κ=1017 it is already indistinguishable from a singular matrix. The rank-k version is Eckart–Young, in the next lesson.
How many digits are lost
Perturbation bounds become a practical rule when combined with a good algorithm’s guarantee. Computers store floating-point numbers with unit roundoffu: u=2−53≈1.1×10−16 in float64 (about 16 digits), u=2−24≈6.0×10−8 in float32 (about 7), and u=2−8≈3.9×10−3 in bfloat16 (2 or 3 digits).
An algorithm such as Gaussian elimination with partial pivoting (np.linalg.solve’s LU factorization) is in practice backward stable (backward stable): computed solution x^ exactly solves a nearby system (A+δA)x^=b, with ∥δA∥/∥A∥ of order u (up to a moderate factor depending on n). The perturbation theorem translates that backward error into forward error:
∥x∥∥x^−x∥≲κ(A)u.
Taking logarithms: about log10κ(A) digits are lost from the −log10u available. With κ=1010 in float64 about 6 correct digits remain; in float32, none. In bfloat16, the precision used to train large models, a matrix with κ=103 already gives solutions with no reliable digit, which is why systems are not solved in bfloat16 (though matrices are multiplied at that precision).
The classic test bed is Hilbert matrices, hij=1/(i+j−1), whose condition number grows roughly as e3.5n: κ2(H8)≈1.5×1010 and κ2(H12)≈1.7×1016.
InteractiveDigits lost
float64 (double)
float32 (single)
prediction −log10u−log10κ
Computed solution (exact is (1,1,…,1); correct digits are bold). First 6 components:
Rule of thumb: about log10κ digits are lost from the ≈16 of float64 or ≈7 of float32. Theory gives a bound: points lie on or slightly above the line.
Each point is a system with exact solution (1,…,1) solved by Gaussian elimination with pivoting in float64 (blue) and float32 (orange, emulated by rounding each operation). The horizontal axis is log10κ and the vertical axis correct result digits. Points fall on line −log10u−log10κ (or somewhat above it: theory is a bound) until none remain. Move the slider to see the computed solution with correct digits in bold. Switch to ‘Normal equations’: slope doubles because κ(A⊤A)=κ(A)2.
The same number governs optimization speed. To minimize quadratic 21x⊤Hx−b⊤x with positive-definite H, gradient descent with optimal step reduces error in H norm by factor (κ−1)/(κ+1) each iteration, with κ=κ2(H): with κ=100 it takes on the order of κ iterations to gain one decimal digit. This is the optimization module’s condition number of a function.
Norms and conditioning from scratch
All lesson norms fit in a few lines. Spectral norm alone needs an iterative algorithm: power iteration applied to A⊤A, without ever forming that product.
[ ]Norms from scratchBrowser
import numpy as np
def norm1(A):
"""Norma de operador l1: máxima suma de valores absolutos por columna."""
return np.abs(A).sum(axis=0).max()
def norm_inf(A):
"""Norma de operador l-infinito: máxima suma por fila."""
return np.abs(A).sum(axis=1).max()
def norm_fro(A):
return np.sqrt((A * A).sum())
def norm2_power(A, iters=100, seed=0):
"""sigma_1 por iteración de potencia sobre A^T A, sin formar A^T A."""
v = np.random.default_rng(seed).standard_normal(A.shape[1])
for _ in range(iters):
v = A.T @ (A @ v)
v /= np.linalg.norm(v)
return np.linalg.norm(A @ v)
A = np.array([[1., -2., 3.],
[-4., 5., -6.]])
s = np.linalg.svd(A, compute_uv=False)
print("valores singulares:", s)
print(f"||A||_1 = {norm1(A):.6f} numpy: {np.linalg.norm(A, 1):.6f}")
print(f"||A||_inf = {norm_inf(A):.6f} numpy: {np.linalg.norm(A, np.inf):.6f}")
print(f"||A||_F = {norm_fro(A):.6f} numpy: {np.linalg.norm(A, 'fro'):.6f} sqrt(sum s^2): {np.sqrt((s**2).sum()):.6f}")
print(f"||A||_2 = {norm2_power(A):.6f} numpy: {np.linalg.norm(A, 2):.6f} sigma_1: {s[0]:.6f}")
print(f"||A||_* = {s.sum():.6f} numpy: {np.linalg.norm(A, 'nuc'):.6f}")
print(f"cota barata sqrt(||A||_1 ||A||_inf) = {np.sqrt(norm1(A) * norm_inf(A)):.6f}")
print(f"np.linalg.norm(A) sin ord = {np.linalg.norm(A):.6f} (es Frobenius, no la espectral)")
The perturbation bound is not pessimistic in the worst case: it is attained exactly. Construct b and δb attaining it with singular vectors and compare with random perturbations.
[ ]Worst case of the perturbation boundBrowser
def cond2(A):
s = np.linalg.svd(A, compute_uv=False)
return s[0] / s[-1]
rng = np.random.default_rng(1)
n = 6
U, _ = np.linalg.qr(rng.standard_normal((n, n)))
V, _ = np.linalg.qr(rng.standard_normal((n, n)))
s = np.logspace(0, -4, n) # sigma_1 = 1, sigma_n = 1e-4
A = U @ np.diag(s) @ V.T
print(f"kappa_2(A) = {cond2(A):.4e} numpy: {np.linalg.cond(A):.4e}")
def amplificacion(b, db):
x = np.linalg.solve(A, b)
dx = np.linalg.solve(A, db) # A dx = db por linealidad
return (np.linalg.norm(dx) / np.linalg.norm(x)) / (np.linalg.norm(db) / np.linalg.norm(b))
eps = 1e-8
print(f"peor caso (b = u_1, db = eps u_n): {amplificacion(U[:, 0], eps * U[:, -1]):.4e}")
print(f"mejor caso (b = u_n, db = eps u_1): {amplificacion(U[:, -1], eps * U[:, 0]):.4e}")
r = [amplificacion(rng.standard_normal(n), eps * rng.standard_normal(n)) for _ in range(2000)]
print(f"b y db aleatorios: mediana {np.median(r):.3e}, máximo {np.max(r):.3e}")
The worst case gives κ=104 and the best 1/κ. With random directions typical amplification is order 1 and the maximum across 2000 trials is two orders below κ: the worst case requires b and δb aligned with particular singular directions. But algorithm rounding errors are not random in that sense, and the digit rule describes practical behavior well, as the next cell shows with Hilbert matrices. Their condition number is computed without appreciable error using the exact inverse, whose entries are integers.
[ ]Digits lost with Hilbert matricesBrowser
from math import comb
def hilbert(n):
i = np.arange(n)
return 1.0 / (i[:, None] + i[None, :] + 1)
def hilbert_inv_exacta(n):
"""Inversa exacta de H_n (entradas enteras), por su fórmula cerrada con binomiales."""
return [[(-1) ** (i + j) * (i + j - 1) * comb(n + i - 1, n - j) * comb(n + j - 1, n - i)
* comb(i + j - 2, i - 1) ** 2 for j in range(1, n + 1)] for i in range(1, n + 1)]
def digitos(x):
err = np.max(np.abs(x.astype(float) - 1))
return max(0.0, -np.log10(max(err, 1e-17)))
print(" n log10(k) pred64 real64 pred32 real32")
for n in range(2, 14):
H = hilbert(n)
Hinv = np.array(hilbert_inv_exacta(n), dtype=float)
kappa = np.linalg.eigvalsh(H)[-1] * np.linalg.eigvalsh(Hinv)[-1] # sigma_1(H) * sigma_1(H^-1)
b = H @ np.ones(n)
x64 = np.linalg.solve(H, b)
x32 = np.linalg.solve(H.astype(np.float32), b.astype(np.float32))
lk = np.log10(kappa)
print(f"{n:2d} {lk:7.2f} {max(0, 15.95 - lk):6.2f} {digitos(x64):6.2f} {max(0, 7.22 - lk):6.2f} {digitos(x32):6.2f}")
Finally, the squaring in normal equations. Fitting a degree-9 polynomial to 50 points in [0,1] is a least-squares problem with an ill-conditioned Vandermonde matrix.
[ ]Normal equations: squaring the condition numberBrowser
t = np.linspace(0, 1, 50)
A = np.vander(t, 10, increasing=True)
x_true = np.ones(10)
b = A @ x_true
print(f"kappa(A) = {np.linalg.cond(A):.2e}, kappa(A^T A) = {np.linalg.cond(A.T @ A):.2e}")
x_ne = np.linalg.solve(A.T @ A, A.T @ b)
x_ls = np.linalg.lstsq(A, b, rcond=None)[0]
for nombre, x in [("ecuaciones normales", x_ne), ("lstsq (SVD)", x_ls)]:
err = np.linalg.norm(x - x_true) / np.linalg.norm(x_true)
print(f"{nombre:20s} error relativo {err:.1e} -> unas {-np.log10(err):.0f} cifras")
With κ(A)≈3.6×106, normal equations work with κ(A⊤A)≈1013 and get about 4 digits right; lstsq, which does not form A⊤A, gets about 10, as 16−6.6 predicts.
The professional version
Quantity
NumPy / SciPy
Note
∥A∥1,∥A∥∞
np.linalg.norm(A, 1), np.linalg.norm(A, np.inf)
O(mn)
∥A∥F
np.linalg.norm(A, 'fro') or np.linalg.norm(A)
by default, a matrix gives Frobenius
∥A∥2=σ1
np.linalg.norm(A, 2)
computes full SVD: O(mnmin(m,n))
σmin
np.linalg.norm(A, -2)
also with SVD
∥A∥∗
np.linalg.norm(A, 'nuc')
sum of singular values
κp(A)
np.linalg.cond(A, p)
with p=None or 2, σ1/σn by SVD
inexpensive estimate of κ1
scipy.linalg.lapack.dgecon after LU
extra O(n2); used by scipy.linalg.solve
estimate of σ1
scipy.sparse.linalg.svds(A, k=1) or power iteration
for large or sparse matrices
Two practical details. First, scipy.linalg.solve estimates reciprocal condition number using its existing LU and emits a LinAlgWarning when it is below machine precision: if you see it, the answer has no reliable digits. Second, np.linalg.cond computes singular values in floating point, so it cannot reliably return values much larger than 1/u≈1016: with H14 you will get a number of order 1017 or 1018 instead of true 1.9×1019 because σn is lost in rounding noise of σ1.
Lipschitz constants of layers and networks
Return to the first question. An L-layer network is
f(x)=WLϕ(WL−1⋯ϕ(W1x+b1)⋯+bL−1)+bL,
with activation ϕ applied componentwise. If ϕ is 1-Lipschitz as a function from R to R (ReLU and tanh are; sigmoid, with constant 1/4, also satisfies what follows), it is also 1-Lipschitz as a map from Rd to Rd under Euclidean norm, because ∑i(ϕ(ai)−ϕ(bi))2≤∑i(ai−bi)2. Biases do not affect differences. A composition’s Lipschitz constant is at most the product of its constants. Therefore
Lip(f)≤ℓ=1∏L∥Wℓ∥2.
This bound, computed layer by layer by Szegedy et al. (2013) to explain adversarial examples, has a direct interpretation: if Lip(f)≤K, no input perturbation of norm ε can move output by more than Kε. It underlies Lipschitz-based robustness certificates.
For a linear network (without ϕ), the exact constant is known: ∥WL⋯W1∥2, the product’s largest singular value; submultiplicativity says it cannot exceed the product of norms. The question is how far apart they are.
InteractiveLipschitz constant of a layer stack
Amplification ∥Wℓ⋯W1x∥2/∥x∥2 after ℓ layers (d=16, log scale)
bound Π‖Wᵢ‖₂
worst direction (σ₁ of product)
random directions (median and range)
Matrices
bound ∏i≤12∥Wi∥21276
worst direction σ1(WL⋯W1)1.962
typical random direction (median)0.581
bound looseness (bound / worst)650.4
mean ∥Wi∥2 per layer1.819
With Gaussian matrices ∥Wi∥2≈1.85c (at d=16; tending to 2c as d grows), but a typical direction stretches only ≈c. The bound exceeds the actual worst direction by a factor 650 and grows exponentially with depth.
A linear network with L layers of size 16×16. Red dashed curve is bound ∏i≤ℓ∥Wi∥2; magenta is actual worst-direction amplification σ1(Wℓ⋯W1); blue and its band show 64 random directions. With Gaussian matrices the bound separates exponentially from reality. Switch to ‘Orthogonal’: all three curves coincide. Enable spectral normalization: the bound is fixed at 1, but actual amplification decreases with depth.
What the interactive explains:
Gaussian. With entries N(0,c2/d), a fixed direction has root-mean-square stretch c (because E∥Wx∥2=c2∥x∥2), but the worst stretches ∥W∥2≈2c when d is large (at d=16, about 1.85c; see probability module extreme singular values of random matrices). The bound multiplies every layer’s worst case as if aligned, but they are not: a layer’s output singular vector need not match the next layer’s input singular vector. While the bound grows as (1.85c)L, the product’s actual worst direction barely grows with L when c=1: slack is exponential in depth (around 650 times with 12 layers in the interactive’s initial state).
Orthogonal. Every singular value is c, every direction is worst, and the bound is exact. This motivates orthogonal initialization: signals and gradients neither explode nor vanish with depth, the same question governed by recurrence-matrix singular values in recurrent networks.
Spectral normalization. Dividing each layer by its spectral norm guarantees Lip(f)≤1 without further calculation. The price is that the actual network is often considerably more contractive.
Spectral normalization
Spectral normalization by Miyato et al. (2018) replaces each weight matrix with W/σ^(W) at every GAN discriminator training step. Computing σ1 by SVD each step would be expensive; the trick is that weights change little between steps, so one power iteration per step suffices, reusing previous u as the starting point. Iteration converges over training without extra cost.
[ ]Spectral normalization with persistent power iterationBrowser
class SpectralNorm:
"""W / sigma_hat(W), con sigma_hat estimado por UNA iteración de potencia por llamada (Miyato et al., 2018)."""
def __init__(self, shape, seed=0):
u = np.random.default_rng(seed).standard_normal(shape[0])
self.u = u / np.linalg.norm(u) # se conserva entre llamadas
def __call__(self, W, n_iter=1):
u = self.u
for _ in range(n_iter):
v = W.T @ u
v /= np.linalg.norm(v)
u = W @ v
u /= np.linalg.norm(u)
self.u = u
sigma = u @ W @ v # u^T W v
return W / sigma, sigma
# W cambia poco a poco, como durante el entrenamiento
rng = np.random.default_rng(0)
d = 32
W = rng.standard_normal((d, d)) / np.sqrt(d)
sn = SpectralNorm(W.shape)
for paso in range(1, 61):
W = W + 0.01 * rng.standard_normal((d, d)) / np.sqrt(d)
W_sn, sigma_hat = sn(W)
if paso in (1, 2, 5, 10, 20, 40, 60):
print(f"paso {paso:2d}: sigma_hat = {sigma_hat:.5f} sigma real = {np.linalg.norm(W, 2):.5f}"
f" ||W_sn||_2 = {np.linalg.norm(W_sn, 2):.4f}")
Since u⊤Wv≤σ1 for unit vectors, the estimate always undershoots and ∥Wsn∥2 starts somewhat above 1. After a few dozen steps the difference is order 10−3 or less. Now check that normalized layers make a small network 1-Lipschitz with ReLU too, and how much slack it has.
[ ]A network with normalized layers is 1-LipschitzBrowser
L, d = 4, 32
rng = np.random.default_rng(1)
Ws = [rng.standard_normal((d, d)) / np.sqrt(d) for _ in range(L)]
normalizadores = [SpectralNorm(W.shape, seed=i) for i, W in enumerate(Ws)]
for _ in range(30): # 30 llamadas: la iteración persistente converge
Wn = [sn(W)[0] for sn, W in zip(normalizadores, Ws)]
def red(x, mats):
for M in mats[:-1]:
x = np.maximum(M @ x, 0.0) # ReLU, 1-Lipschitz
return mats[-1] @ x
def producto(mats):
P = np.eye(d)
for M in mats:
P = M @ P
return P
X = rng.standard_normal((2000, d))
dX = 1e-3 * rng.standard_normal((2000, d))
for nombre, mats in [("sin normalizar", Ws), ("normalizada", Wn)]:
cota = np.prod([np.linalg.norm(M, 2) for M in mats])
lineal = np.linalg.norm(producto(mats), 2)
cocientes = [np.linalg.norm(red(x + dx, mats) - red(x, mats)) / np.linalg.norm(dx) for x, dx in zip(X, dX)]
print(f"{nombre:15s} cota {cota:7.4f} | Lipschitz de la red lineal {lineal:6.4f} | "
f"máximo observado con ReLU {max(cocientes):6.4f}")
In PyTorch the same idea is packaged as a layer parametrization, including persistent power iteration:
import torchfrom torch import nnfrom torch.nn.utils.parametrizations import spectral_normcapa = spectral_norm(nn.Linear(256, 256)) # en cada forward en modo train: una iteración de potenciay = capa(torch.randn(8, 256))print(torch.linalg.matrix_norm(capa.weight, ord=2)) # aproximadamente 1
Common mistakes
Exercises
NumericCondition of a diagonal matrix
Calculate κ2(A) for A=diag(100,1,0.01).
NumericFrobenius versus spectral
Calculate ∥A∥F for A=[1221].
NumericNorm by rows
Calculate ∥A∥∞ for A=[2−3−6114].
NumericThe motivating system in infinity norm
Calculate κ∞(A)=∥A∥∞A−1∞ for the motivating matrix A=[1111.0001].
NumericThe nuclear norm
Calculate ∥A∥∗ for A=[3405].
NumericThe nearest singular matrix
What is the smallest spectral norm ∥δA∥2 of a perturbation making A=[3405] singular?
QuizUnitarily invariant norms
Which norms satisfy ∥UAV∥=∥A∥ for all orthogonal matrices U, V?
More than one answer may be correct.
QuizTrustworthy digits
You solve Ax=b using np.linalg.solve in float64 and κ2(A)≈1010. How many correct digits are expected in x^?
QuizLeast squares with normal equations
A least-squares problem has κ2(A)=106. In float64, how many digits are expected with normal equations and a QR- or SVD-based method (when residual is small)?
QuizWhich is closer to singular?
Which matrix is closer to singular in relative terms (smallest ∥δA∥2/∥A∥2 making it singular)?
QuizLipschitz constant of a ReLU network
A network f(x)=W3ReLU(W2ReLU(W1x)) has ∥W1∥2=2, ∥W2∥2=0.5 and ∥W3∥2=3. What can you say about its Euclidean Lipschitz constant?
CodeSpectral norm and condition by power iteration
Implement spectral_norm_power(A, iters), estimating ∥A∥2=σ1 by power iteration on A⊤A (without forming the product or computing an SVD), and cond2_estimate(A, iters), estimating κ2(A)=σ1/σn for an invertible square matrix. For σn use 1/σn=A−12 and iterate with A−1 by solving systems with np.linalg.solve, without forming the inverse.
import numpy as np
def spectral_norm_power(A, iters=200):
"""Estimación de ||A||_2 por iteración de potencia sobre A^T A."""
# tu código
return 0.0
def cond2_estimate(A, iters=200):
"""Estimación de kappa_2(A) = sigma_1 / sigma_n para A cuadrada invertible."""
# tu código
return 1.0
Shift+Enter to run
NumericLipschitz with orthogonal layers
A linear network has 10 layers Wℓ=1.1Qℓ with orthogonal Qℓ of size 64×64. What is its exact Euclidean Lipschitz constant?
Summary
Key idea
A matrix is measured by how much it can stretch: operator norm ∥A∥ is maximum stretch and its Lipschitz constant, and condition number κ=∥A∥A−1, the maximum-to-minimum ratio, is the factor amplifying relative errors when solving Ax=b.
Three norms with formulas: ∥A∥1 is maximum column sum, ∥A∥∞ maximum row sum and ∥A∥2=σ1 the maximum Rayleigh quotient of A⊤A. Operator norms are submultiplicative and bound spectral radius.
Schatten norms: spectral, Frobenius and nuclear are ℓ∞, ℓ2 and ℓ1 norms of the singular-value vector, so rotations do not change them. ∥A∥2≤∥A∥F≤r∥A∥2, and nuclear norm, dual to spectral, is the convex substitute for rank.
Conditioning: ∥δx∥/∥x∥≤κ∥δb∥/∥b∥ with equality for b∥u1, δb∥un; 1/κ2 is relative distance to the nearest singular matrix. Determinant measures none of this.
Digit rule: a backward-stable algorithm loses about log10κ of float64’s ≈16 digits (7 for float32, 2 or 3 for bfloat16), and normal equations lose twice as many because κ(A⊤A)=κ2.
Networks: Lip(f)≤∏ℓ∥Wℓ∥2 with 1-Lipschitz activations. The bound is exact with orthogonal layers and very pessimistic with Gaussian weights; spectral normalization fixes it at 1 with one power iteration per step.