Dictionary of Applied Machine Learning · spectrum
Updated on 2026-11-23
Numerical companion to the entry spectrum: it recomputes what the entry states and prints one line per check
Numerical companion to the glossary entry 'spectrum'. The entry defines the spectrum of a linear operator T as the set of values lambda for which T - lambda I fails to be invertible, and then extends the notion to any object that carries an associated linear operator -- a square matrix, and a stochastic process through its covariance function. The demo takes that definition literally rather than through a library routine: it sweeps lambda along the line, measures how far A - lambda I is from failing to be invertible, and confirms that the values at which it does fail are exactly the ones a solver reports. Off the spectrum the operator is invertible and the equation (A - lambda I) v = b has one solution; on the spectrum it is not, and the failure is visible as a direction that A - lambda I sends to zero.
Run it without installing anything:uv run https://dictionaryofml.org/terms/spectrum.py
uv downloads this script and the pinned NumPy and Matplotlib it needs, then runs it; the script fetches any input file it uses. To keep the output files, download spectrum.py into a folder and run uv run spectrum.py there. With NumPy and Matplotlib already installed, python3 spectrum.py, from any directory — it writes its output files into the current directory. Fixed seeds, so the printed numbers reproduce exactly. Download spectrum.py · Notebook · Open in Colab
Before running a downloaded copy, scan it: uvx bandit -q -t B102,B307,B602,B605 spectrum.py (B102,B307,B602,B605 are the exec, eval and shell checks of bandit) reports nothing: the script runs no shell command and evaluates no generated code.
One cell per block of the script: the code, and what that code printed when it last ran here
"""The spectrum: the values at which an operator fails to be invertible.
Purpose
-------
Numerical companion to the glossary entry 'spectrum'. The entry defines
the spectrum of a linear operator T as the set of values lambda for which
T - lambda I fails to be invertible, and then extends the notion to any
object that carries an associated linear operator -- a square matrix, and
a stochastic process through its covariance function. The demo takes that
definition literally rather than through a library routine: it sweeps
lambda along the line, measures how far A - lambda I is from failing to be
invertible, and confirms that the values at which it does fail are exactly
the ones a solver reports. Off the spectrum the operator is invertible and
the equation (A - lambda I) v = b has one solution; on the spectrum it is
not, and the failure is visible as a direction that A - lambda I sends to
zero.
The last two blocks are the entry's two extensions. A rotation of the
plane shows that the spectrum depends on the field the operator acts over:
over the real numbers it is empty, over the complex numbers it is not. A
year of air temperature at Krems an der Donau supplies the stochastic
process, whose covariance function builds a linear operator whose spectrum
is a set of nonnegative numbers.
Self-contained (numpy and matplotlib only), fixed seed; the GeoSphere
download falls back to the committed CSV.
Blocks
------
[B-definition] A 3-by-3 matrix: det(A - lambda I) over a sweep of lambda
vanishes at exactly three values, and those are the ones a
solver returns. The definition is applied as written.
[B-invertible] Off the spectrum, A - lambda I is invertible and
(A - lambda I) v = b has exactly one solution. On the
spectrum it is not invertible: it sends a nonzero direction
to zero, so a solution either fails to exist or is not
unique. The size of the inverse grows without bound as
lambda approaches a value of the spectrum.
[B-field] A rotation of the plane by 90 degrees has an empty spectrum
over the real numbers and a two-element spectrum over the
complex numbers, so the field is part of the question. A
matrix that is not the zero matrix can have the spectrum
{0}.
[B-process] The 365 days of 2024 at Krems that carry a reading at 15:00
(UTC) are one record of a stochastic process. Its
covariance function at lags 0 to 29 builds a linear operator
whose spectrum holds 30 nonnegative values. Writes the CSV
files of the entry's figure.
Outputs
-------
spectrum_sweep.csv : lambda, |det(A - lambda I)|, and the size of the
inverse, over 601 values of lambda.
spectrum_values.csv : the three values of the spectrum of A.
spectrum_weather.csv : date and 15:00 (UTC) temperature of each day of 2024
(committed copy).
spectrum_acf.csv : lag, covariance function of the record at that lag.
spectrum_process.csv : index, the 30 values of the spectrum of the operator
the covariance function builds.
spectrum.png : matplotlib preview (checking only).
Data generated by pythondemos/spectrum.py.
"""
# /// script
# requires-python = ">=3.10"
# dependencies = ["matplotlib==3.10.7", "numpy==2.3.4"]
# ///
import json
import urllib.request
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
OUT_DIR = Path(__file__).parent
rng = np.random.default_rng(42)
report = []
def check(name, ok):
report.append((name, bool(ok)))
print(f" [{'ok' if ok else 'FAIL'}] {name}")
A 3-by-3 matrix: det(A - lambda I) over a sweep of lambda vanishes at exactly three values, and those are the ones a solver returns. The definition is applied as written.
print("[B-definition] the values at which A - lambda I fails to be invertible")
A = np.array([[4.0, 1.0, 0.0],
[1.0, 3.0, 1.0],
[0.0, 1.0, 2.0]])
check("[B-definition] A is a square matrix, so it carries an associated "
"linear operator", A.shape[0] == A.shape[1])
# 600 points rather than 601, so that no value of the spectrum lands
# exactly on a grid point: a determinant of zero there would be counted as
# two sign changes rather than one crossing
grid = np.linspace(0.0, 6.0, 600)
dets = np.array([np.linalg.det(A - t * np.eye(3)) for t in grid])
sign_changes = np.flatnonzero(dets[:-1] * dets[1:] < 0)
check(f"[B-definition] the determinant of A - lambda I changes sign "
f"{len(sign_changes)} times over the sweep, so the sweep brackets "
"three values", len(sign_changes) == 3)
values = np.sort(np.linalg.eigvalsh(A))
check(f"[B-definition] the spectrum is "
f"{{{values[0]:.2f}, {values[1]:.2f}, {values[2]:.2f}}}",
len(values) == 3)
bracketed = sorted(0.5 * (grid[i] + grid[i + 1]) for i in sign_changes)
check("[B-definition] each bracketed value agrees with a value the solver "
"returns, to within the width of the sweep",
bool(np.all(np.abs(np.array(bracketed) - values) < 0.02)))
check("[B-definition] the determinant of A - lambda I is zero at every "
"value of the spectrum, to within 1e-12",
all(abs(np.linalg.det(A - v * np.eye(3))) < 1e-12 for v in values))
check("[B-definition] away from the spectrum the determinant is not zero",
all(abs(np.linalg.det(A - t * np.eye(3))) > 1e-6
for t in (0.0, 1.0, 6.0)))
[B-definition] the values at which A - lambda I fails to be invertible
[ok] [B-definition] A is a square matrix, so it carries an associated linear operator
[ok] [B-definition] the determinant of A - lambda I changes sign 3 times over the sweep, so the sweep brackets three values
[ok] [B-definition] the spectrum is {1.27, 3.00, 4.73}
[ok] [B-definition] each bracketed value agrees with a value the solver returns, to within the width of the sweep
[ok] [B-definition] the determinant of A - lambda I is zero at every value of the spectrum, to within 1e-12
[ok] [B-definition] away from the spectrum the determinant is not zero
Off the spectrum, A - lambda I is invertible and (A - lambda I) v = b has exactly one solution. On the spectrum it is not invertible: it sends a nonzero direction to zero, so a solution either fails to exist or is not unique. The size of the inverse grows without bound as lambda approaches a value of the spectrum.
print("[B-invertible] on the spectrum the equation loses its one solution")
b = np.array([1.0, 2.0, 3.0])
off = 1.0 # not in the spectrum
M = A - off * np.eye(3)
v = np.linalg.solve(M, b)
check("[B-invertible] off the spectrum A - lambda I is invertible and the "
"equation has exactly one solution", bool(np.allclose(M @ v, b)))
check("[B-invertible] that solution is the only one: nothing but the zero "
"vector is sent to zero",
int(np.linalg.matrix_rank(M)) == 3)
on = values[0]
S = A - on * np.eye(3)
check(f"[B-invertible] at lambda = {on:.2f}, a value of the spectrum, "
"A - lambda I has rank 2 rather than 3, so it is not invertible",
int(np.linalg.matrix_rank(S)) == 2)
_, _, Vt = np.linalg.svd(S)
null_dir = Vt[-1]
check("[B-invertible] it sends a nonzero direction to zero, which is "
"exactly the failure the definition names",
np.linalg.norm(null_dir) > 0.5
and float(np.linalg.norm(S @ null_dir)) < 1e-12)
sizes = np.array([1.0 / max(np.linalg.svd(A - t * np.eye(3),
compute_uv=False)[-1], 1e-300)
for t in grid])
near = np.argmin(np.abs(grid - values[0]))
check("[B-invertible] the size of the inverse grows without bound as lambda "
"approaches a value of the spectrum",
sizes[near] > 50 * sizes[0])
np.savetxt(OUT_DIR / "spectrum_sweep.csv",
np.column_stack([grid, np.abs(dets), np.minimum(sizes, 1e3)]),
delimiter=",", header="lam,absdet,invsize", comments="",
fmt="%.6g")
np.savetxt(OUT_DIR / "spectrum_values.csv", values.reshape(-1, 1),
delimiter=",", header="lam", comments="", fmt="%.6f")
[B-invertible] on the spectrum the equation loses its one solution [ok] [B-invertible] off the spectrum A - lambda I is invertible and the equation has exactly one solution [ok] [B-invertible] that solution is the only one: nothing but the zero vector is sent to zero [ok] [B-invertible] at lambda = 1.27, a value of the spectrum, A - lambda I has rank 2 rather than 3, so it is not invertible [ok] [B-invertible] it sends a nonzero direction to zero, which is exactly the failure the definition names [ok] [B-invertible] the size of the inverse grows without bound as lambda approaches a value of the spectrum
A rotation of the plane by 90 degrees has an empty spectrum over the real numbers and a two-element spectrum over the complex numbers, so the field is part of the question. A matrix that is not the zero matrix can have the spectrum {0}.
print("[B-field] the spectrum depends on the field the operator acts over")
R = np.array([[0.0, -1.0], [1.0, 0.0]]) # a rotation by 90 degrees
real_hits = [t for t in np.linspace(-5, 5, 2001)
if abs(np.linalg.det(R - t * np.eye(2))) < 1e-9]
check("[B-field] over the real numbers no lambda makes R - lambda I fail to "
"be invertible, so the real spectrum of a 90-degree rotation is "
"empty", len(real_hits) == 0)
cvals = np.linalg.eigvals(R)
check("[B-field] over the complex numbers the spectrum holds the two values "
"i and -i", bool(np.allclose(np.sort_complex(cvals), [-1j, 1j])))
Nmat = np.array([[0.0, 1.0], [0.0, 0.0]])
check("[B-field] the spectrum of the matrix [[0, 1], [0, 0]] is the single "
"value 0, although the matrix itself is not the zero matrix",
bool(np.allclose(np.linalg.eigvals(Nmat), 0.0))
and not np.allclose(Nmat, 0.0))
[B-field] the spectrum depends on the field the operator acts over [ok] [B-field] over the real numbers no lambda makes R - lambda I fail to be invertible, so the real spectrum of a 90-degree rotation is empty [ok] [B-field] over the complex numbers the spectrum holds the two values i and -i [ok] [B-field] the spectrum of the matrix [[0, 1], [0, 0]] is the single value 0, although the matrix itself is not the zero matrix
The 365 days of 2024 at Krems that carry a reading at 15:00 (UTC) are one record of a stochastic process. Its covariance function at lags 0 to 29 builds a linear operator whose spectrum holds 30 nonnegative values. Writes the CSV files of the entry's figure.
print("[B-process] the 15:00 (UTC) temperature at Krems, 2024, as a record")
URL = ("https://dataset.api.hub.geosphere.at/v1/station/historical/"
"klima-v2-1h?parameters=tl&station_ids=3805"
"&start=2024-01-01T00:00&end=2024-12-31T23:00")
CSV = OUT_DIR / "spectrum_weather.csv"
try:
with urllib.request.urlopen(URL, timeout=120) as resp:
payload = json.load(resp)
series = payload["features"][0]["properties"]["parameters"]["tl"]["data"]
byday = {}
for stamp, value in zip(payload["timestamps"], series):
if value is None: # the archive drops whole days
continue
if stamp[11:16] == "15:00": # the stamps are UTC, and so is
byday[stamp[:10]] = float(value) # the time
stamps = sorted(byday)
y = np.array([byday[d] for d in stamps])
with open(CSV, "w") as fh:
fh.write("date,t15\n")
for day, val in zip(stamps, y):
fh.write(f"{day},{val:g}\n")
print(f" downloaded {len(y)} days with a 15:00 reading")
except (OSError, KeyError, ValueError) as err:
print(f" download failed ({err}); reading {CSV.name}")
rows = np.genfromtxt(CSV, delimiter=",", skip_header=1, dtype=str)
stamps = [str(s) for s in rows[:, 0]]
y = rows[:, 1].astype(float)
check("[B-process] 365 of the days of 2024 carry a 15:00 reading (the "
"hourly record drops 2024-01-12)", len(y) == 365)
check("[B-process] the record matches the archive (1 January: 8.0 at 15:00 "
"UTC)", stamps[0] == "2024-01-01" and bool(np.isclose(y[0], 8.0)))
LAGS = 30
z = y - y.mean()
acf = np.array([float(np.dot(z[:len(z) - k], z[k:]) / len(z))
for k in range(LAGS)])
check(f"[B-process] the covariance function at lag 0 is the variance "
f"{acf[0]:.1f} squared degrees", bool(np.isclose(acf[0], z.var())))
check("[B-process] the covariance function falls off with the lag: lag 1 "
"exceeds lag 10", acf[1] > acf[10])
Cop = np.array([[acf[abs(i - j)] for j in range(LAGS)] for i in range(LAGS)])
check("[B-process] the covariance function builds a symmetric linear "
"operator on 30 consecutive days", bool(np.allclose(Cop, Cop.T)))
spec = np.sort(np.linalg.eigvalsh(Cop))[::-1]
check(f"[B-process] its spectrum holds {LAGS} values, the largest "
f"{spec[0]:.1f} and the smallest {spec[-1]:.1f} squared degrees",
len(spec) == LAGS)
check("[B-process] no value of the spectrum is negative, as a covariance "
"function requires", bool(spec.min() > -1e-9))
check("[B-process] the operator is invertible exactly because 0 is not in "
"its spectrum",
bool(spec.min() > 1e-9)
and int(np.linalg.matrix_rank(Cop)) == LAGS)
np.savetxt(OUT_DIR / "spectrum_acf.csv",
np.column_stack([np.arange(LAGS), acf]), delimiter=",",
header="lag,cov", comments="", fmt="%.4f")
np.savetxt(OUT_DIR / "spectrum_process.csv",
np.column_stack([np.arange(1, LAGS + 1), spec]), delimiter=",",
header="index,lam", comments="", fmt="%.4f")
# ---- the preview figure
fig, ax = plt.subplots(1, 2, figsize=(9.4, 3.8))
ax[0].plot(grid, np.abs(dets), linestyle="-", color="black",
label="|det(A - $\\lambda$I)| (solid curve)")
ax[0].plot(values, np.zeros_like(values), "o", color="black", ms=7,
markerfacecolor="white", label="the spectrum (open circles)")
ax[0].set_xlabel("$\\lambda$")
ax[0].set_ylabel("|det(A - $\\lambda$I)|")
ax[0].set_title("(a) the spectrum is where the determinant vanishes",
fontsize=9)
ax[0].legend(frameon=False, fontsize=8)
ax[1].plot(np.arange(1, LAGS + 1), spec, "s", color="black", ms=4,
label="the 30 values (filled squares)")
ax[1].set_xlabel("index, largest value first")
ax[1].set_yscale("log") # the largest value is 700 times the
# smallest, so a linear axis would show
# one square and 29 on the floor
ax[1].set_ylabel("value of the spectrum (°C$^2$, log scale)")
ax[1].set_title("(b) the spectrum the Krems covariance function builds",
fontsize=9)
ax[1].legend(frameon=False, fontsize=8)
fig.tight_layout()
fig.savefig(OUT_DIR / "spectrum.png", dpi=150)
print(f"\n{sum(ok for _, ok in report)}/{len(report)} checks passed")
[B-process] the 15:00 (UTC) temperature at Krems, 2024, as a record
downloaded 365 days with a 15:00 reading
[ok] [B-process] 365 of the days of 2024 carry a 15:00 reading (the hourly record drops 2024-01-12)
[ok] [B-process] the record matches the archive (1 January: 8.0 at 15:00 UTC)
[ok] [B-process] the covariance function at lag 0 is the variance 87.2 squared degrees
[ok] [B-process] the covariance function falls off with the lag: lag 1 exceeds lag 10
[ok] [B-process] the covariance function builds a symmetric linear operator on 30 consecutive days
[ok] [B-process] its spectrum holds 30 values, the largest 1927.0 and the smallest 2.7 squared degrees
[ok] [B-process] no value of the spectrum is negative, as a covariance function requires
[ok] [B-process] the operator is invertible exactly because 0 is not in its spectrum
22/22 checks passed

B-process writes when the script runs