import numpy as np
rng = np.random.default_rng(3)
def range_finder(A, ell):
"""Orthonormal basis Q for range(A Omega)."""
Omega = rng.standard_normal((A.shape[1], ell))
Q, _ = np.linalg.qr(A @ Omega)
return Q
def randomized_svd(A, k, p=10):
"""Rank-k randomized SVD with oversampling p."""
Q = range_finder(A, k + p)
U_tilde, s, Vt = np.linalg.svd(Q.T @ A, full_matrices=False)
return (Q @ U_tilde)[:, :k], s[:k], Vt[:k]
def projection_error(A, ell):
"""Relative error ||A - QQ^T A||_F / ||A||_F for one draw of Omega with ell columns."""
Q = range_finder(A, ell)
return np.linalg.norm(A - Q @ (Q.T @ A)) / np.linalg.norm(A)
def matrix_with_singular_values(m, n, sigma):
"""A random m x n matrix (m >= n) whose singular values are exactly sigma."""
U, _ = np.linalg.qr(rng.standard_normal((m, n)))
V, _ = np.linalg.qr(rng.standard_normal((n, n)))
return (U * sigma) @ V.TThe Randomized SVD in Practice
Math 123: Mathematical Aspects of Data Analysis — Fall 2026
This page runs the randomized SVD from the lecture notes on matrices with prescribed singular values, where we know the optimal error exactly. We start with a picture in three dimensions, then check the exactly low rank theorem, see why we oversample, check the average error bound of Halko, Martinsson, and Tropp, and finally time the algorithm against the full SVD. For matrices whose singular values decay slowly, see the power iterations example.
The algorithm
The range finder implements stage A, and the randomized SVD adds stage B. The helper projection_error measures the quality of one draw of stage A, relative to the size of \(\bfA\).
Figure style
import plotly.graph_objects as go
from plotly.subplots import make_subplots
INK = "#7c7c78"
GRID = "rgba(128, 128, 128, 0.28)"
BLUE, ORANGE, TEAL = "#2a78d6", "#eb6834", "#27a9a0"
CONFIG = dict(displayModeBar=False, responsive=True)
def style(fig, height=460, title=None, showlegend=None):
"""Apply the shared layout to a plot with axes."""
fig.update_layout(
template="simple_white",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font=dict(color=INK, size=13),
title=dict(text=title, x=0, xanchor="left", font=dict(size=15)),
margin=dict(l=60, r=30, t=60 if title else 40, b=50),
height=height,
showlegend=showlegend,
hovermode="closest",
)
fig.update_xaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)
fig.update_yaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)
return figThe geometry of one sketch
In three dimensions we can see stage A. Take \(\bfU=\bfI\), so that \(\bfu_1,\bfu_2,\bfu_3\) are the coordinate axes, and a random orthogonal \(\bfV\), so that \(\bfA=\Sigma\bfV^\top\). By rotation invariance, a sample is \(\bfA\bfomega=(\sigma_1g_1,\sigma_2g_2,\sigma_3g_3)\) with \(g_1,g_2,g_3\) independent \(N(0,1)\). We compare two matrices with target rank \(k=2\):
- exactly rank 2, with \(\sigma=(3,1,0)\), so \(\operatorname{range}(\bfA)\) is the horizontal plane \(\operatorname{span}(\bfu_1,\bfu_2)\);
- nearly rank 2, with \(\sigma=(3,1,0.3)\), so there is a small tail \(\sigma_3g_3\bfu_3\) in every sample.
For each, we draw \(400\) samples \(\bfA\bfomega\), and use two of them as a sketch with \(\ell=2\).
V, _ = np.linalg.qr(rng.standard_normal((3, 3)))
Omega = rng.standard_normal((3, 400))
spectra_3d = {"exactly rank 2, σ = (3, 1, 0)": [3, 1, 0], "nearly rank 2, σ = (3, 1, 0.3)": [3, 1, 0.3]}
def tilt(Y):
"""Angle in degrees between the plane spanned by the two columns of Y and the horizontal plane."""
normal = np.cross(Y[:, 0], Y[:, 1])
return np.degrees(np.arccos(abs(normal[2]) / np.linalg.norm(normal)))
for name, sigma in spectra_3d.items():
A = np.diag(sigma) @ V.T
tilts = [tilt(A @ rng.standard_normal((3, 2))) for _ in range(2000)]
print(f"{name}: median tilt {np.median(tilts):.1f}°, 90th percentile {np.percentile(tilts, 90):.1f}°")exactly rank 2, σ = (3, 1, 0): median tilt 0.0°, 90th percentile 0.0°
nearly rank 2, σ = (3, 1, 0.3): median tilt 19.4°, 90th percentile 65.7°
Plot the samples and planes
def square(e1, e2, a, b, color, name, showlegend):
"""A flat square with half-widths a and b along the orthonormal vectors e1 and e2."""
corners = np.array([s * a * e1 + t * b * e2 for s, t in [(-1, -1), (1, -1), (1, 1), (-1, 1)]])
return go.Mesh3d(x=corners[:, 0], y=corners[:, 1], z=corners[:, 2], i=[0, 0], j=[1, 2], k=[2, 3],
color=color, opacity=0.3, name=name, showlegend=showlegend, hoverinfo="skip")
fig = make_subplots(rows=1, cols=2, specs=[[{"type": "scene"}, {"type": "scene"}]],
horizontal_spacing=0.02, subplot_titles=list(spectra_3d))
e1, e2, e3 = np.eye(3)
for col, sigma in enumerate(spectra_3d.values(), start=1):
A = np.diag(sigma) @ V.T
cloud = A @ Omega
Y = cloud[:, :2]
# an orthonormal basis of the sampled plane, with its first vector as close to u_1 as possible
Q, _ = np.linalg.qr(Y)
w1 = Q @ (Q.T @ e1)
w1 /= np.linalg.norm(w1)
w2 = np.cross(np.cross(Y[:, 0], Y[:, 1]), w1)
w2 /= np.linalg.norm(w2)
first = col == 1
fig.add_trace(go.Scatter3d(x=cloud[0], y=cloud[1], z=cloud[2], mode="markers", name="samples Aω",
marker=dict(size=2.5, color=INK, opacity=0.55), showlegend=first,
hovertemplate="(%{x:.2f}, %{y:.2f}, %{z:.2f})<extra></extra>"),
row=1, col=col)
fig.add_trace(square(e1, e2, 8, 4, INK, "target plane span(u₁, u₂)", first), row=1, col=col)
fig.add_trace(square(w1, w2, 8, 4, ORANGE, "plane spanned by two samples", first), row=1, col=col)
for i in range(2):
fig.add_trace(go.Scatter3d(x=[0, Y[0, i]], y=[0, Y[1, i]], z=[0, Y[2, i]], mode="lines+markers",
line=dict(color=ORANGE, width=7), marker=dict(size=[0, 5], color=ORANGE),
name="two samples", showlegend=first and i == 0, legendgroup="samples",
hovertemplate="(%{x:.2f}, %{y:.2f}, %{z:.2f})<extra></extra>"),
row=1, col=col)
axis = dict(backgroundcolor="rgba(0,0,0,0)", gridcolor=GRID, zerolinecolor=GRID, color=INK, showspikes=False)
fig.update_scenes(xaxis=dict(axis, title="u₁", range=[-9, 9]), yaxis=dict(axis, title="u₂", range=[-4.5, 4.5]),
zaxis=dict(axis, title="u₃", range=[-4.5, 4.5]), aspectmode="manual",
aspectratio=dict(x=2, y=1, z=1), camera=dict(eye=dict(x=0.9, y=-2.0, z=0.7)))
fig.update_layout(paper_bgcolor="rgba(0,0,0,0)", font=dict(color=INK, size=13), height=520,
margin=dict(l=0, r=0, t=40, b=0), legend=dict(orientation="h", x=0.5, xanchor="center", y=0))
fig.show(config=CONFIG)Both clouds are stretched along \(\bfu_1\), because the coefficient of \(\bfu_1\) is three times larger on average than that of \(\bfu_2\): a sample is weighted by the singular values. On the left, every sample lies in \(\operatorname{range}(\bfA)\), and any two of them span it, as the exactly low rank theorem promises. On the right, the tail \(\sigma_3g_3\bfu_3\) lifts each sample off the plane, and with only \(\ell=k\) samples nothing corrects the tilt; the median tilt is about \(10^\circ\), but one draw in ten is tilted by much more. In three dimensions a third sample would span everything, which is not useful, but in high dimensions a few extra samples are exactly what fixes this, as the next two sections show.
Exactly low rank
A \(500\times300\) matrix of rank \(8\), sketched with exactly \(\ell=8\) samples and no oversampling. By the exactly low rank theorem, \(\bfQ\bfQ^\top\bfA=\bfA\) with probability \(1\), so the only error should be rounding.
rank of A: 8
relative error ||A - QQ^T A||_F / ||A||_F = 2.8e-15
Now vary the sketch size \(\ell\) from \(1\) to \(16\), and compare with a second matrix: the same \(\bfA\) plus a little Gaussian noise \(\bfE\), scaled so that \(\|\bfE\|_F=10^{-3}\|\bfA\|_F\). The noisy matrix is only approximately rank \(8\): its singular values \(\sigma_9,\sigma_{10},\ldots\) are small but not zero, and its Eckart–Young error at rank \(8\) is about \(10^{-3}\). For each \(\ell\) we draw \(\bfOmega\) \(50\) times.
E = rng.standard_normal(A_low.shape)
A_noisy = A_low + 1e-3 * np.linalg.norm(A_low) / np.linalg.norm(E) * E
ells = np.arange(1, 17)
trials = 50
sketch_errors, sketch_optimum = {}, {}
for name, A in {"exactly rank 8": A_low, "rank 8 plus noise": A_noisy}.items():
S = np.linalg.svd(A, compute_uv=False)
sketch_optimum[name] = np.array([np.sqrt(np.sum(S[ell:] ** 2)) for ell in ells]) / np.linalg.norm(A)
sketch_errors[name] = np.array([[projection_error(A, ell) for _ in range(trials)] for ell in ells])
errors = sketch_errors["rank 8 plus noise"]
for ell in [8, 10, 16]:
a = list(ells).index(ell)
print(f"noisy, ell={ell:>2}: median error {np.median(errors[a]):.1e}, "
f"worst {errors[a].max():.1e}, optimum for rank 8 {sketch_optimum['rank 8 plus noise'][7]:.1e}")noisy, ell= 8: median error 5.0e-03, worst 1.7e-01, optimum for rank 8 9.8e-04
noisy, ell=10: median error 2.3e-03, worst 2.3e-02, optimum for rank 8 9.8e-04
noisy, ell=16: median error 1.4e-03, worst 2.1e-03, optimum for rank 8 9.8e-04
Plot the error against the sketch size
fig = go.Figure()
for (name, errors), color in zip(sketch_errors.items(), [TEAL, ORANGE]):
lo, mid, hi = np.percentile(errors, [10, 50, 90], axis=1)
fig.add_trace(go.Scatter(x=np.concatenate([ells, ells[::-1]]), y=np.concatenate([hi, lo[::-1]]),
fill="toself", fillcolor=color, opacity=0.2, line=dict(width=0),
hoverinfo="skip", showlegend=False))
fig.add_trace(go.Scatter(x=ells, y=mid, mode="lines+markers", name=f"{name}, median",
line=dict(color=color, width=2), marker=dict(size=8),
hovertemplate="ℓ = %{x}<br>median error %{y:.1e}<extra></extra>"))
fig.add_trace(go.Scatter(x=ells, y=sketch_optimum[name], mode="lines", name=f"{name}, optimum",
line=dict(color=color, width=2, dash="dash"),
hovertemplate="ℓ = %{x}<br>optimum %{y:.1e}<extra></extra>"))
fig.add_vline(x=8, line=dict(color=INK, width=1, dash="dot"), annotation_text="ℓ = 8",
annotation_position="top right", annotation_font_color=INK)
style(fig, height=480, showlegend=True)
fig.update_layout(legend=dict(x=0.98, xanchor="right", y=0.55))
fig.update_xaxes(title_text="sketch size ℓ", dtick=1)
fig.update_yaxes(title_text="‖A − QQᵀA‖_F / ‖A‖_F", type="log", exponentformat="power")
fig.show(config=CONFIG)For \(\ell<8\) there are not enough samples to capture the rank \(8\) range, and both matrices behave the same, a little worse than the optimum. At \(\ell=8\) the exactly rank \(8\) matrix is recovered to rounding error, and more samples change nothing. The noisy matrix is the high dimensional version of the tilted plane in Figure 1: with \(\ell=k\) samples its error is typically about ten times the optimum, and the wide band shows that some draws are much worse. Two or three extra samples bring the error down to a small multiple of the optimum.
Why oversample
The bands in Figure 2 hide the shape of the distribution, so here are \(1000\) draws of \(\bfOmega\) for the noisy matrix with \(k=8\) and oversampling \(p=0\), \(2\), and \(10\). We divide each error by the Eckart–Young optimum, so a ratio of \(1\) is as good as the exact SVD.
k = 8
S = np.linalg.svd(A_noisy, compute_uv=False)
optimum = np.sqrt(np.sum(S[k:] ** 2)) / np.linalg.norm(A_noisy)
draws = 1000
oversampling = [0, 2, 10]
ratios = {p: np.array([projection_error(A_noisy, k + p) for _ in range(draws)]) / optimum for p in oversampling}
for p, r in ratios.items():
bound = f", bound on the mean {np.sqrt(1 + k / (p - 1)):.2f}" if p >= 2 else ""
print(f"p={p:>2}: median {np.median(r):.2f}, mean {r.mean():.2f}, worst {r.max():.1f}{bound}")p= 0: median 5.46, mean 16.22, worst 352.9
p= 2: median 2.33, mean 2.73, worst 20.2, bound on the mean 3.00
p=10: median 1.32, mean 1.33, worst 1.6, bound on the mean 1.37
Plot the histograms
bins = np.geomspace(0.9, 1.2 * max(r.max() for r in ratios.values()), 70)
fig = go.Figure()
for (p, r), color in zip(ratios.items(), [ORANGE, BLUE, TEAL]):
counts, _ = np.histogram(r, bins=bins)
fig.add_trace(go.Scatter(x=bins, y=np.append(counts, 0) / draws, mode="lines", line_shape="hv",
fill="tozeroy", line=dict(color=color, width=2), name=f"p = {p}",
hovertemplate="ratio from %{x:.2f}<br>fraction %{y:.3f}<extra></extra>"))
if p >= 2:
fig.add_vline(x=np.sqrt(1 + k / (p - 1)), line=dict(color=color, width=2, dash="dash"),
annotation_text=f"bound, p = {p}", annotation_position="top right",
annotation_font_color=INK)
style(fig, height=440, showlegend=True)
fig.update_layout(legend=dict(x=0.98, xanchor="right", y=0.98))
fig.update_xaxes(title_text="error / Eckart–Young optimum", type="log")
fig.update_yaxes(title_text="fraction of draws")
fig.show(config=CONFIG)With \(p=0\), the sketch \(\bfY=\bfA\bfOmega\) depends on a square \(8\times8\) Gaussian matrix, and the error is large exactly when that matrix is close to singular. This happens rarely, but often enough to give a long tail of bad draws, and in fact the expected error is infinite, which is why the theorem requires \(p\geq2\). Each extra sample makes a nearly singular draw much less likely: with \(p=2\) the tail is already much shorter, and with \(p=10\) every one of the \(1000\) draws is within a factor of about \(2\) of the optimum. For this matrix the means sit just below the bounds, so the bound is nearly sharp: a flat tail of noise is close to the worst case.
Checking the error bound
Now two \(1000\times400\) matrices that are only approximately low rank, with target rank \(k=10\):
- a flat tail, \(\sigma_j=1\) for \(j\leq10\) and \(\sigma_j=0.1\) afterwards, so there is a clear gap after \(\sigma_{10}\) but a heavy tail;
- slow decay, \(\sigma_j=1/j\), with no gap at all.
For each oversampling \(p\) from \(0\) to \(20\) we draw \(100\) independent \(\bfOmega\), and record the error of \(\bfQ\bfQ^\top\bfA\) divided by the Eckart–Young optimum \(\big(\sum_{j>k}\sigma_j^2\big)^{1/2}\). We also record the error of the rank-\(k\) output of the randomized SVD, which is what truncating gives.
m, n, k = 1000, 400, 10
j = np.arange(1, n + 1)
spectra = {
"flat tail": np.where(j <= k, 1.0, 0.1),
"slow decay, 1/j": 1.0 / j,
}
ps = np.arange(0, 21)
trials = 100
results = {}
for name, sigma in spectra.items():
A = matrix_with_singular_values(m, n, sigma)
optimum = np.sqrt(np.sum(sigma[k:] ** 2))
projected, truncated = np.empty((len(ps), trials)), np.empty((len(ps), trials))
for a, p in enumerate(ps):
for t in range(trials):
Q = range_finder(A, k + p)
B = Q.T @ A
projected[a, t] = np.linalg.norm(A - Q @ B) / optimum
U_tilde, s, Vt = np.linalg.svd(B, full_matrices=False)
truncated[a, t] = np.linalg.norm(A - (Q @ U_tilde[:, :k] * s[:k]) @ Vt[:k]) / optimum
results[name] = projected, truncated
for name, (projected, truncated) in results.items():
a = list(ps).index(10)
print(f"{name:>16}, p=10: mean ratio {projected[a].mean():.3f} (rank k+p), "
f"{truncated[a].mean():.3f} (rank k); bound {np.sqrt(1 + k / 9):.3f}") flat tail, p=10: mean ratio 1.260 (rank k+p), 1.270 (rank k); bound 1.453
slow decay, 1/j, p=10: mean ratio 1.112 (rank k+p), 1.220 (rank k); bound 1.453
Plot the error ratios
fig = go.Figure()
pp = np.linspace(2, 20, 200)
fig.add_trace(go.Scatter(x=pp, y=np.sqrt(1 + k / (pp - 1)), mode="lines", name="bound √(1+k/(p−1))",
line=dict(color=INK, width=2, dash="dash")))
for (name, (projected, truncated)), color in zip(results.items(), [ORANGE, TEAL]):
fig.add_trace(go.Scatter(x=np.concatenate([ps, ps[::-1]]),
y=np.concatenate([projected.max(axis=1), projected.min(axis=1)[::-1]]),
fill="toself", fillcolor=color, opacity=0.2, line=dict(width=0),
hoverinfo="skip", showlegend=False))
fig.add_trace(go.Scatter(x=ps, y=projected.mean(axis=1), mode="lines+markers",
name=f"{name}, QQᵀA (rank k+p)", line=dict(color=color, width=2)))
fig.add_trace(go.Scatter(x=ps, y=truncated.mean(axis=1), mode="lines",
name=f"{name}, truncated (rank k)", line=dict(color=color, width=2, dash="dot")))
fig.add_hline(y=1, line=dict(color=INK, width=1))
style(fig, height=480, showlegend=True)
fig.update_layout(legend=dict(x=0.55, y=0.98))
fig.update_xaxes(title_text="oversampling p", range=[-0.5, 20.5])
fig.update_yaxes(title_text="error / Eckart–Young optimum", range=[0.6, 3.5])
fig.show(config=CONFIG)The bound holds with plenty of room, and the bands are narrow: a single draw of \(\bfOmega\) is almost as good as the average. Unlike the noisy matrix in Section 4, here even \(p=0\) is harmless, because the tail is not small compared with the top singular values: no matter how badly \(\bfQ\) is tilted, the error cannot exceed \(\|\bfA\|_F\), which is only a small multiple of the optimum. Already \(p=5\) to \(10\) gets most of the benefit of oversampling. The slow-decay curve for \(\bfQ\bfQ^\top\bfA\) dips below \(1\) for large \(p\); this is not a contradiction, because \(\bfQ\bfQ^\top\bfA\) has rank \(k+p\), not \(k\). After truncating to rank \(k\), every curve stays above \(1\), as Eckart–Young requires, and truncation costs much less than the worst case in the lecture.
What it costs
The operation count for an \(n\times n\) matrix is about \(2n^2\ell\) for the randomized SVD, against \(n^3\) for the full SVD. Here we time both on random square matrices, with \(k=10\) and \(p=10\), taking the best of three runs. The times depend on the computer that rendered this page, but the trend does not.
import time
def seconds(f, repeats=3):
"""Best wall-clock time of f() over a few runs."""
best = np.inf
for _ in range(repeats):
start = time.perf_counter()
f()
best = min(best, time.perf_counter() - start)
return best
sizes = np.array([250, 500, 1000, 1500, 2000, 3000])
full_times, randomized_times = [], []
for size in sizes:
A = rng.standard_normal((size, size))
full_times.append(seconds(lambda: np.linalg.svd(A, full_matrices=False)))
randomized_times.append(seconds(lambda: randomized_svd(A, 10)))
full_times, randomized_times = np.array(full_times), np.array(randomized_times)
for size, t_full, t_rand in zip(sizes, full_times, randomized_times):
print(f"n = {size:>4}: full SVD {t_full:7.3f} s, randomized {t_rand:.4f} s, {t_full / t_rand:5.0f} times faster")n = 250: full SVD 0.006 s, randomized 0.0003 s, 18 times faster
n = 500: full SVD 0.028 s, randomized 0.0006 s, 46 times faster
n = 1000: full SVD 0.136 s, randomized 0.0012 s, 110 times faster
n = 1500: full SVD 0.356 s, randomized 0.0028 s, 128 times faster
n = 2000: full SVD 0.920 s, randomized 0.0048 s, 191 times faster
n = 3000: full SVD 3.798 s, randomized 0.0100 s, 379 times faster
Plot the timings
fig = go.Figure()
for name, times, color in [("full SVD", full_times, ORANGE), ("randomized SVD, k = 10, p = 10", randomized_times, TEAL)]:
fig.add_trace(go.Scatter(x=sizes, y=times, mode="lines+markers", name=name,
line=dict(color=color, width=2), marker=dict(size=8),
hovertemplate="n = %{x}<br>%{y:.4f} s<extra></extra>"))
style(fig, height=440, showlegend=True)
fig.update_layout(legend=dict(x=0.02, y=0.98))
fig.update_xaxes(title_text="matrix size n", type="log", tickvals=sizes)
fig.update_yaxes(title_text="time (seconds)", type="log", exponentformat="power")
fig.show(config=CONFIG)For small matrices both are fast and the comparison is dominated by overhead. As \(n\) grows, the gap widens, because the full SVD grows like \(n^3\) and the randomized SVD only like \(n^2\). For a matrix that does not fit in memory, or a sparse one, the advantage is larger still, since the randomized SVD touches \(\bfA\) only through two matrix products.