Dictionary of Applied Machine Learning · feature matrix
Updated on 2026-11-03
Numerical companion to the entry feature matrix: it recomputes what the entry states and prints one line per check
Numerical companion to the glossary entry 'featuremtx'. The GeoSphere Austria weather station Krems (station id 3805) records eight measurements per day: lowest, highest and mean air temperature, precipitation, sunshine duration, relative humidity, air pressure and wind speed. This script downloads the records for 2024 from the GeoSphere data hub (dataset klima-v2-1d) and writes them to featuremtx_weather.csv. A value of -1 for precipitation marks a trace of rain too small to record and is set to 0.
Run it without installing anything:uv run https://dictionaryofml.org/terms/featuremtx.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 featuremtx.py into a folder and run uv run featuremtx.py there. With NumPy and Matplotlib already installed, python3 featuremtx.py, from any directory — it writes its output files into the current directory. Fixed seeds, so the printed numbers reproduce exactly. Download featuremtx.py · Notebook · Open in Colab
Before running a downloaded copy, scan it: uvx bandit -q -t B102,B307,B602,B605 featuremtx.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 feature matrix of one weather year, summarized by a handful of
numbers: its shape, its rank, its singular values and its condition number.
Purpose
-------
Numerical companion to the glossary entry 'featuremtx'. The GeoSphere
Austria weather station Krems (station id 3805) records eight
measurements per day: lowest, highest and mean air temperature,
precipitation, sunshine duration, relative humidity, air pressure and
wind speed. This script downloads the records for 2024 from the
GeoSphere data hub (dataset klima-v2-1d) and writes them to
featuremtx_weather.csv. A value of -1 for precipitation marks a trace
of rain too small to record and is set to 0.
Collecting the eight measurements of each day as a row gives the feature
matrix of the year. Every measurement is scaled to zero sample mean and
unit sample variance first, because temperatures, precipitation and
pressure carry different units and the singular values of an unscaled
matrix would report the choice of units rather than the data.
The demo checks the claims the entry makes. (1) The shape is the pair
(number of data points, number of features), and the whole year is 366
times 8 numbers while the shape is two of them. (2) The singular values
are the square roots of the eigenvalues of X^T X, and X^T X divided by
the number of data points is the sample covariance matrix of the scaled
measurements, so the singular values carry the eigenvalues that PCA uses.
(3) The sum of the squared singular values is the squared Frobenius norm
of the feature matrix, which for scaled measurements is the number of
data points times the number of features. (4) The condition number is
the ratio of the largest to the smallest singular value. (5) The
smallest singular value is the smallest norm of a combination of the
columns with unit-norm coefficients, attained at the last right singular
vector and never beaten by a random unit vector; here it is far below
the largest because the mean temperature of a day is the midpoint of its
lowest and its highest up to a residual with standard deviation 0.03
degrees, a near-dependency among three columns on which that singular
vector places all of its weight; dropping the mean temperature raises
the smallest singular value by more than an order of magnitude, while a
change of unit of one measurement multiplies the condition number by
fifty and leaves the rank and the column space unchanged. (6) Linear regression depends on
the square of the condition number: gradient descent needs a number of
steps that grows with it, and noise of relative size eps changes the
learned weights by at most eps kappa (|y| / lambda_1 + |w|) / (1 - eps
kappa) + eps kappa^2 (|r| / lambda_1) / (1 - eps kappa)^2, r the least
squares residual, for every eps kappa < 1: the bound obtained by
subtracting the normal equations of the perturbed and the unperturbed
dataset. (7) A
transformation of the features changes the conditioning without changing
the predictions: relative humidity and wind speed in their recorded units
give a condition number of 14.5, scaling each to unit sample variance
gives 1.45, while the column space, and with it the least squares
predictions, stays the same. From the start for which gradient descent
is slowest, the number of steps matches the exact rate ((q - 1)/(q + 1))^2
per step, q the squared condition number, and no random start needs more
steps. (8) For the features (1, lowest temperature) and the label highest
temperature of the twelve first days of the months, the perturbation that lowers the smallest singular value by
eps lambda_1 and pushes the label vector along the matching left singular
vector reaches more than half of the bound on |dw| up to eps = 0.02,
while random perturbations of the same size stay below half; the
prediction for a feature vector x changes by at most |x| times that
bound (Cauchy-Schwarz), which no realized perturbation exceeds.
Deterministic: the data are a fixed archive year and the decomposition
is a singular value decomposition. Self-contained: numpy + matplotlib
only (stdlib urllib for the download).
Blocks
------
[B-data] Download the 366 days with eight measurements each and
scale every measurement to zero sample mean and unit
sample variance.
[B-shape] The shape of the feature matrix, and how many numbers it
takes to state it.
[B-singvals] The singular values, their link to the eigenvalues of
X^T X and to the sample covariance matrix, and the share
of the squared Frobenius norm that the leading ones carry.
[B-cond] The rank and the condition number, the near-dependency
among the three temperature columns that makes the
smallest singular value small, and a change of unit of
one measurement.
[B-conditioning] The two roles of the condition number in linear
regression: the number of gradient descent steps, and the
change of the learned weights under noise.
[B-transform] A transformation of the features changes the conditioning:
two features in recorded units against the same two scaled
to unit sample variance, with the gradient descent gap per
step, written for the entry's third figure.
[B-perturb] The perturbation bound on one feature: the slope learned
from the lowest temperature, its change under the
adversarial perturbation and under random perturbations of
the same size, against the bound; written for the entry's
fourth figure.
[B-fig] The preview figure: the singular values as a stem plot and the
share of the squared Frobenius norm that k singular values
carry.
Outputs
-------
featuremtx_weather.csv : date and the eight measurements, 366 days
featuremtx_spectrum.csv : index, singular value, cumulative share
featuremtx_gdtrace.csv : step, relative gap in recorded units, scaled
featuremtx_oneline.csv : lowest and highest temperature, zero mean
featuremtx_perturb.csv : relative size, bound, adversarial and largest
random change of the slope
featuremtx.png : preview figure
"""
# /// script
# requires-python = ">=3.10"
# dependencies = ["matplotlib==3.10.7", "numpy==2.3.4"]
# ///
import json
import urllib.request
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
OUT_DIR = Path(__file__).parent
FAILED = []
def check(name, ok):
FAILED.append(name) if not ok else None
print(f" [{'ok' if ok else 'FAIL'}] {name}")
Traceback (most recent call last):
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/urllib/request.py", line 1348, in do_open
h.request(req.get_method(), req.selector, req.data, headers,
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/http/client.py", line 1303, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/http/client.py", line 1349, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/http/client.py", line 1298, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/http/client.py", line 1058, in _send_output
self.send(msg)
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/http/client.py", line 996, in send
self.connect()
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/http/client.py", line 1468, in connect
super().connect()
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/http/client.py", line 962, in connect
self.sock = self._create_connection(
^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/socket.py", line 839, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/socket.py", line 974, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/junga1/dictionaryappliedml/pythondemos/featuremtx.py", line 137, in <module>
with urllib.request.urlopen(URL, timeout=180) as resp:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/urllib/request.py", line 216, in urlopen
return opener.open(url, data, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/urllib/request.py", line 519, in open
response = self._open(req, data)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/urllib/request.py", line 536, in _open
result = self._call_chain(self.handle_open, protocol, protocol +
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/urllib/request.py", line 496, in _call_chain
result = func(*args)
^^^^^^^^^^^
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/urllib/request.py", line 1391, in https_open
return self.do_open(http.client.HTTPSConnection, req,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/junga1/anaconda3/envs/adictml-np2/lib/python3.11/urllib/request.py", line 1351, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 8] nodename nor servname provided, or not known>
Download the 366 days with eight measurements each and scale every measurement to zero sample mean and unit sample variance.
PARAMS = ["tlmin", "tlmax", "tl_mittel", "rr", "so_h", "rf_mittel",
"p_mittel", "vv_mittel"]
URL = ("https://dataset.api.hub.geosphere.at/v1/station/historical/"
f"klima-v2-1d?parameters={','.join(PARAMS)}&station_ids=3805"
"&start=2024-01-01&end=2024-12-31")
with urllib.request.urlopen(URL, timeout=180) as resp:
payload = json.load(resp)
params = payload["features"][0]["properties"]["parameters"]
stamps = [t[:10] for t in payload["timestamps"]]
RAW = np.stack([np.array(params[p]["data"], dtype=float) for p in PARAMS], 1)
RAW[:, 3] = np.maximum(RAW[:, 3], 0.0) # -1 marks a trace of rain
with open(OUT_DIR / "featuremtx_weather.csv", "w") as f:
f.write("date," + ",".join(PARAMS) + "\n")
for day, row in zip(stamps, RAW):
f.write(day + "," + ",".join(f"{v:g}" for v in row) + "\n")
X = (RAW - RAW.mean(0)) / RAW.std(0) # zero mean, unit variance
print("[B-data] the feature matrix of one weather year")
check("[B-data] every measurement has zero sample mean and unit variance",
np.allclose(X.mean(0), 0.0, atol=1e-12)
and np.allclose(X.std(0), 1.0, atol=1e-12))
The shape of the feature matrix, and how many numbers it takes to state it.
m, d = X.shape
print(f"[B-shape] shape ({m}, {d}): {m} data points, {d} features")
print(f"[B-shape] {m * d} numbers in the matrix, 2 in its shape")
check("[B-shape] 366 days with eight measurements each",
(m, d) == (366, 8))
check("[B-shape] more data points than features", m > d)
The singular values, their link to the eigenvalues of X^T X and to the sample covariance matrix, and the share of the squared Frobenius norm that the leading ones carry.
sv = np.linalg.svd(X, compute_uv=False)
eigs = np.linalg.eigvalsh(X.T @ X)[::-1]
print("[B-singvals] singular values: "
+ ", ".join(f"{s:.2f}" for s in sv))
check("[B-singvals] the squared singular values are the eigenvalues "
"of X^T X", np.allclose(sv ** 2, eigs, rtol=1e-9, atol=1e-9))
samplecov = (X.T @ X) / m
check("[B-singvals] X^T X divided by the number of data points is the "
"sample covariance matrix of the scaled measurements",
np.allclose(samplecov, np.cov(X, rowvar=False, bias=True),
atol=1e-12))
The rank and the condition number, the near-dependency among the three temperature columns that makes the smallest singular value small, and a change of unit of one measurement.
rank = int(np.linalg.matrix_rank(X))
cond = sv[0] / sv[-1]
print(f"[B-cond] rank {rank}, condition number {cond:.1f}")
check("[B-cond] the rank is the number of nonzero singular values, here "
"the number of features", rank == d == int((sv > 1e-10 * sv[0]).sum()))
check("[B-cond] the condition number is the ratio of the largest to "
"the smallest singular value",
abs(cond - np.linalg.cond(X)) < 1e-6)
a small singular value names a near-dependency among the columns
u_min = np.linalg.svd(X)[2][-1] # last right singular vector
rng_u = np.random.default_rng(0)
best_random = min(np.linalg.norm(X @ (v / np.linalg.norm(v)))
for v in rng_u.normal(size=(2000, d)))
print(f"[B-collinear] smallest singular value {sv[-1]:.3f}, largest {sv[0]:.1f}; "
f"best of 2000 random unit vectors {best_random:.2f}")
check("[B-collinear] the smallest singular value is the norm of X u at "
"the last right singular vector u, and no random unit vector gives "
"a smaller norm",
abs(np.linalg.norm(X @ u_min) - sv[-1]) < 1e-9 and best_random > sv[-1])
temp_mass = float((u_min[:3] ** 2).sum())
print("[B-collinear] right singular vector "
+ ", ".join(f"{c:.2f}" for c in u_min)
+ f"; weight on the three temperature columns {temp_mass:.3f}")
check("[B-collinear] that vector places all of its weight, to three "
"decimals, on the lowest, the highest and the mean temperature",
temp_mass > 0.9995)
midpoint = (RAW[:, 0] + RAW[:, 1]) / 2.0
resid_std = float((RAW[:, 2] - midpoint).std())
print(f"[B-collinear] mean temperature minus the midpoint of lowest and "
f"highest: standard deviation {resid_std:.3f} degrees")
check("[B-collinear] the mean temperature is the midpoint of the lowest "
"and the highest up to a residual with standard deviation below "
"0.05 degrees", resid_std < 0.05)
sv_drop = np.linalg.svd(np.delete(X, 2, axis=1), compute_uv=False)
print(f"[B-collinear] without the mean temperature the smallest singular "
f"value is {sv_drop[-1]:.2f}")
check("[B-collinear] dropping the mean temperature raises the smallest "
"singular value by more than an order of magnitude",
sv_drop[-1] > 10.0 * sv[-1])
The two roles of the condition number in linear regression: the number of gradient descent steps, and the change of the learned weights under noise.
def ls_solve(M, rhs):
"""The weights that minimize the squared error, by least squares."""
return np.linalg.lstsq(M, rhs, rcond=None)[0]
def gd_steps(M, rhs, gap=1e-6, w0=None):
"""Gradient descent with an exact line search: steps to close the gap."""
w = np.zeros(M.shape[1]) if w0 is None else w0.copy()
best = 0.5 * np.sum((M @ ls_solve(M, rhs) - rhs) ** 2)
start = 0.5 * np.sum((M @ w - rhs) ** 2) - best
for step in range(1, 200001):
res = M @ w - rhs
if 0.5 * np.sum(res ** 2) - best <= gap * start:
return step - 1
grad = M.T @ res
Mg = M @ grad
w = w - (Mg @ res) / (Mg @ Mg) * grad
return -1
LBL = 1 # maximum temperature as label
FEAT = [j for j in range(d) if j != LBL]
Xr, yr = X[:, FEAT], X[:, LBL]
Xill = Xr.copy()
Xill[:, 0] *= 0.2 # the same features, worse scaled
k_r, k_i = np.linalg.cond(Xr), np.linalg.cond(Xill)
steps_r, steps_i = gd_steps(Xr, yr), gd_steps(Xill, yr)
for name, k, steps in (("as recorded", k_r, steps_r),
("one feature rescaled", k_i, steps_i)):
print(f"[B-conditioning] {name}: condition number {k:.1f}, "
f"{steps} gradient descent steps")
check("[B-conditioning] a larger condition number costs more gradient "
"descent steps", steps_i > steps_r)
print(f"[B-conditioning] the step counts grew by {steps_i / steps_r:.1f}, "
f"the squared condition numbers by {(k_i / k_r) ** 2:.1f}")
check("[B-conditioning] and the step counts grow in proportion to the "
"square of the condition number, within a factor of two",
0.5 <= (steps_i / steps_r) / (k_i / k_r) ** 2 <= 2.0)
EPS = 1e-7
rng2 = np.random.default_rng(7)
w_hat = ls_solve(Xr, yr)
dX = rng2.standard_normal(Xr.shape)
dX *= EPS * np.linalg.norm(Xr, 2) / np.linalg.norm(dX, 2)
U_full = np.linalg.svd(Xr, full_matrices=True)[0]
outside = U_full[:, Xr.shape[1]:][:, 0] # a direction no X w reaches
y_exact = Xr @ w_hat
y_far = y_exact + 3 * np.linalg.norm(y_exact) * outside
def pinv_bound(M, y, eps):
"""Bound on the change dw of the least squares solution w under noise
of relative size eps in M and y. Subtracting the normal equations
of the perturbed and the unperturbed dataset gives the exact equation
(M+dM)^T (M+dM) dw = (M+dM)^T (dy - dM w) + dM^T r, r the residual,
so |dw| <= |(M+dM)^+| (|dy| + |dM| |w|) + |((M+dM)^T (M+dM))^{-1}|
|dM| |r|. With |dM| = eps lambda_1, |dy| = eps |y| and the smallest
singular value of M+dM at least lambda_d - eps lambda_1 (Golub and
Van Loan, Cor. 8.6.2) this is, for eps kappa < 1,
eps kappa (|y|/lambda_1 + |w|) / (1 - eps kappa)
+ eps kappa^2 (|r|/lambda_1) / (1 - eps kappa)^2."""
sv = np.linalg.svd(M, compute_uv=False)
lam_1, lam_d = sv[0], sv[-1]
kappa = lam_1 / lam_d
assert eps * kappa < 1.0
w = ls_solve(M, y)
r = y - M @ w
return (eps * kappa * (np.linalg.norm(y) / lam_1 + np.linalg.norm(w))
/ (1 - eps * kappa)
+ eps * kappa ** 2 * (np.linalg.norm(r) / lam_1)
/ (1 - eps * kappa) ** 2)
moved, bounds = {}, {}
for name, y in (("reproduced exactly", y_exact), ("not reproduced", y_far)):
dy = rng2.standard_normal(y.shape)
dy *= EPS * np.linalg.norm(y) / np.linalg.norm(dy)
moved[name] = np.linalg.norm(ls_solve(Xr + dX, y + dy) - w_hat)
bounds[name] = pinv_bound(Xr, y, EPS)
print(f"[B-conditioning] labels {name}: noise of relative size {EPS:g} "
f"moves the weights by {moved[name] / np.linalg.norm(w_hat):.2e} "
f"of their norm")
print(f"[B-conditioning] the pseudoinverse bound, relative to the norm of "
f"the weights, is {bounds['reproduced exactly'] / np.linalg.norm(w_hat):.2e} "
f"for labels reproduced exactly and "
f"{bounds['not reproduced'] / np.linalg.norm(w_hat):.2e} for labels "
f"not reproduced")
check("[B-conditioning] both changes stay below the pseudoinverse bound",
all(moved[k] <= bounds[k] for k in moved))
check("[B-conditioning] labels the features reproduce exactly leave the "
"first term only, so the weights move less",
moved["reproduced exactly"] < moved["not reproduced"])
A transformation of the features changes the conditioning: two features in recorded units against the same two scaled to unit sample variance, with the gradient descent gap per step, written for the entry's third figure.
def colspace_projector(M):
"""Orthogonal projection onto the column space of M."""
U_, s_, _ = np.linalg.svd(M, full_matrices=False)
r = int((s_ > s_[0] * 1e-10).sum())
return U_[:, :r] @ U_[:, :r].T
def gd_trace(M, rhs, steps, w0, floor=1e-12):
"""Relative gap f(w^(t)) - f(w_hat) over f(w^(0)) - f(w_hat), per step,
until it falls below `floor`."""
w = w0.copy()
best = np.sum((M @ ls_solve(M, rhs) - rhs) ** 2)
start = np.sum((M @ w - rhs) ** 2) - best
out = []
for _ in range(steps + 1):
res = M @ w - rhs
gap = (np.sum(res ** 2) - best) / start
out.append(max(gap, floor))
if gap < floor:
break
grad = M.T @ res
Mg = M @ grad
w = w - (Mg @ res) / (Mg @ Mg) * grad
return np.array(out)
HUM, WIND = 5, 7 # relative humidity, wind speed
CEN = RAW - RAW.mean(0) # every column with zero sample mean
Xrec, yrec = CEN[:, [HUM, WIND]], CEN[:, LBL] # recorded units
Xsc = Xrec / Xrec.std(0) # unit sample variance
cases = (("recorded units", Xrec), ("unit sample variance", Xsc))
def slowest_start(M, rhs):
"""w_hat plus an error at distance |w_hat| whose component along each
eigenvector of the Hessian is inversely proportional to the eigenvalue:
the start for which the gap shrinks by exactly ((q - 1)/(q + 1))^2 per
step, q the condition number of the Hessian (Boyd and Vandenberghe,
Sect. 9.3.2)."""
w_hat = ls_solve(M, rhs)
mu, V = np.linalg.eigh(M.T @ M)
e = V @ (1.0 / mu)
return w_hat + e * np.linalg.norm(w_hat) / np.linalg.norm(e)
kap = {name: float(np.linalg.cond(M)) for name, M in cases}
stp = {name: gd_steps(M, yrec, w0=slowest_start(M, yrec)) for name, M in cases}
stp0 = {name: gd_steps(M, yrec) for name, M in cases}
for name, _ in cases:
q = kap[name] ** 2
exact = (np.log(1e-6) / np.log(((q - 1) / (q + 1)) ** 2)
if q > 1 else 1.0)
print(f"[B-transform] {name}: condition number {kap[name]:.2f}, "
f"{stp[name]} gradient descent steps from the slowest start "
f"({exact:.0f} by the exact rate), {stp0[name]} from zero")
check("[B-transform] scaling to unit sample variance lowers the condition "
"number by more than a factor of five",
kap["recorded units"] > 5 * kap["unit sample variance"])
check("[B-transform] from the slowest start the step counts match the "
"exact rate ((q - 1)/(q + 1))^2 per step, q the squared condition "
"number, to within one step",
all(abs(stp[n] - np.log(1e-6) / np.log(((kap[n] ** 2 - 1)
/ (kap[n] ** 2 + 1)) ** 2)) <= 1
for n, _ in cases[:2]))
check("[B-transform] and fall with the squared condition number, within "
"a factor of two",
0.5 <= (stp["recorded units"] / stp["unit sample variance"])
/ (kap["recorded units"] / kap["unit sample variance"]) ** 2 <= 2.0)
check("[B-transform] from the zero vector the same two cases are both "
"faster: the condition number bounds the worst start",
stp0["recorded units"] <= stp["recorded units"]
and stp0["unit sample variance"] <= stp["unit sample variance"])
P_rec = colspace_projector(Xrec)
check("[B-transform] both have the same column space, so the least "
"squares predictions do not change",
all(np.allclose(colspace_projector(M), P_rec, atol=1e-8)
for _, M in cases))
rng4 = np.random.default_rng(5)
w_rec_hat = ls_solve(Xrec, yrec)
rand_steps = []
for _ in range(200):
e = rng4.standard_normal(2)
w0 = w_rec_hat + e * np.linalg.norm(w_rec_hat) / np.linalg.norm(e)
rand_steps.append(gd_steps(Xrec, yrec, w0=w0))
print(f"[B-transform] 200 random starts at the same distance from w_hat in "
f"recorded units need {min(rand_steps)} to {max(rand_steps)} steps")
check("[B-transform] no random start at that distance needs more steps than "
"the slowest start: its rate is the worst case over all starts",
max(rand_steps) <= stp["recorded units"])
tr_rec = gd_trace(Xrec, yrec, 300, slowest_start(Xrec, yrec))
tr_sc = gd_trace(Xsc, yrec, 300, slowest_start(Xsc, yrec))
with open(OUT_DIR / "featuremtx_gdtrace.csv", "w") as f:
f.write("step,recorded,scaled\n")
for t in range(max(len(tr_rec), len(tr_sc))):
a = f"{tr_rec[t]:.6e}" if t < len(tr_rec) else "nan"
b = f"{tr_sc[t]:.6e}" if t < len(tr_sc) else "nan"
f.write(f"{t},{a},{b}\n")
The perturbation bound on one feature: the slope learned from the lowest temperature, its change under the adversarial perturbation and under random perturbations of the same size, against the bound; written for the entry's fourth figure.
FIRST = [i for i, day in enumerate(stamps) if day.endswith("-01")]
m2 = len(FIRST) # the first day of each month
X2 = np.column_stack([np.ones(m2), RAW[FIRST, 0]]) # a constant and the lowest temperature
y2 = RAW[FIRST, 1] # the highest temperature
U2, sv2, Vt2 = np.linalg.svd(X2, full_matrices=False)
lam2_1, lam2_d = sv2[0], sv2[-1]
kappa2 = lam2_1 / lam2_d
w2 = ls_solve(X2, y2) # intercept and slope
r2 = y2 - X2 @ w2
ny2 = np.linalg.norm(y2)
print(f"[B-perturb] features (1, lowest temperature) of the {m2} first days of "
f"the months: condition number "
f"{kappa2:.1f}, intercept {w2[0]:.2f}, slope {w2[1]:.3f}, residual norm "
f"{np.linalg.norm(r2) / ny2:.3f} of the label norm, lowest temperature "
f"from {X2[:, 1].min():.1f} to {X2[:, 1].max():.1f}")
def bound2(eps):
"""The perturbation bound of the entry for this feature matrix."""
return (eps * kappa2 * (ny2 / lam2_1 + np.linalg.norm(w2)) / (1 - eps * kappa2)
+ eps * kappa2 ** 2 * (np.linalg.norm(r2) / lam2_1)
/ (1 - eps * kappa2) ** 2)
def adversarial(eps):
"""The perturbation the bound is built for: shrink the smallest singular
value by eps lambda_1 and push y along the matching left singular vector;
of the four sign choices, the one that moves w_hat the most."""
v_d, u_d = U2[:, -1], Vt2[-1] # left and right singular vectors
best, best_w = -1.0, None
for s_X in (1, -1):
for s_y in (1, -1):
dX = s_X * eps * lam2_1 * np.outer(v_d, u_d)
dy = s_y * eps * ny2 * v_d
w = ls_solve(X2 + dX, y2 + dy)
if np.linalg.norm(w - w2) > best:
best, best_w = np.linalg.norm(w - w2), w
return best_w
rng3 = np.random.default_rng(11)
NDRAW = 100
EPSS = np.array([0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05])
rows, fans = [], {}
for eps in EPSS:
w_adv = adversarial(eps)
W = []
for _ in range(NDRAW):
dX = rng3.standard_normal(X2.shape); dX *= eps * lam2_1 / np.linalg.norm(dX, 2)
dy = rng3.standard_normal(m2); dy *= eps * ny2 / np.linalg.norm(dy)
W.append(ls_solve(X2 + dX, y2 + dy))
W = np.array(W)
rows.append((eps, bound2(eps), np.linalg.norm(w_adv - w2),
np.linalg.norm(W - w2, axis=1).max()))
fans[eps] = (w_adv, W)
with open(OUT_DIR / "featuremtx_perturb.csv", "w") as f:
f.write("eps,bound,adversarial,random\n")
for eps, b, a, rmax in rows:
f.write(f"{eps:.6e},{b:.6e},{a:.6e},{rmax:.6e}\n")
for eps, b, a, rmax in rows:
print(f"[B-perturb] eps {eps}: bound {b:.3f}, adversarial {a:.3f} ({100 * a / b:.0f}%), "
f"random max {rmax:.3f} ({100 * rmax / b:.0f}%), prediction bound at x=20: {b * np.hypot(1, 20):.1f}")
EPS1 = 0.01
k1 = int(np.argmin(np.abs(EPSS - EPS1))); assert abs(EPSS[k1] - EPS1) < 1e-12
eps, b, a, rmax = rows[k1]; w_adv, W = fans[EPS1]
grid = np.linspace(-6, 20, 53)
G = np.column_stack([np.ones_like(grid), grid])
fit, adv = G @ w2, G @ w_adv
lines = G @ W.T # 69 x NDRAW
lo, hi = lines.min(1), lines.max(1)
env = b * np.sqrt(1 + grid ** 2) # |x^T dw| <= |x| |dw| <= |x| R
with open(OUT_DIR / "featuremtx_lines.csv", "w") as f:
f.write("x,fit,adv,bndlo,bndhi\n")
for i, x in enumerate(grid):
f.write(f"{x:.4f},{fit[i]:.4f},{adv[i]:.4f},{fit[i] - env[i]:.4f},{fit[i] + env[i]:.4f}\n")
with open(OUT_DIR / "featuremtx_fan.csv", "w") as f: # polygon: lo forward, hi back
f.write("x,y\n")
for i, x in enumerate(grid): f.write(f"{x:.4f},{lo[i]:.4f}\n")
for i in range(len(grid) - 1, -1, -1): f.write(f"{grid[i]:.4f},{hi[i]:.4f}\n")
with open(OUT_DIR / "featuremtx_oneline.csv", "w") as f:
f.write("x,y\n")
for x, yv in zip(X2[:, 1], y2): f.write(f"{x:.4f},{yv:.4f}\n")
print(f"[B-perturb] at relative size {EPS1}: bound {b:.3f} on |dw|, adversarial "
f"{a:.3f} ({100 * a / b:.0f}%), largest of {NDRAW} random draws {rmax:.3f} "
f"({100 * rmax / b:.0f}%); adversarial intercept {w_adv[0]:.2f} and slope "
f"{w_adv[1]:.3f}; the bound allows a change of the prediction of "
f"{env[np.argmin(np.abs(grid))]:.1f} degrees at lowest temperature 0 and "
f"{env[-1]:.1f} at {grid[-1]:.0f} degrees")
check("[B-perturb] every perturbation of relative size eps changes the "
"parameters by less than the bound",
all(a <= b and rmax <= b for _, b, a, rmax in rows))
check("[B-perturb] the adversarial perturbation reaches more than half of "
"the bound at every relative size up to 0.02",
all(a / b > 0.5 for eps, b, a, _ in rows if eps <= 0.02))
check("[B-perturb] and the random draws stay below half of it",
all(rmax < b / 2 for _, b, _, rmax in rows))
# the prediction bound: |x^T dw| <= |x| |dw| <= |x| times the bound on |dw|
norms = np.linalg.norm(X2, axis=1)
check(f"[B-perturb] every prediction for the {m2} days, under the adversarial "
"and every random perturbation, changes by at most |x| times the bound "
"on |dw|",
np.all(np.abs(X2 @ (w_adv - w2)) <= norms * b)
and np.all(np.abs(X2 @ (W - w2).T) <= norms[:, None] * b))
The preview figure: the singular values as a stem plot and the share of the squared Frobenius norm that k singular values carry.
fig, (axG, axN) = plt.subplots(1, 2, figsize=(10.4, 4.4))
axG.semilogy(np.arange(len(tr_rec)), np.maximum(tr_rec, 1e-12), "k-", lw=2,
label=f"recorded units, $\\kappa = {kap['recorded units']:.1f}$")
axG.semilogy(np.arange(len(tr_sc)), np.maximum(tr_sc, 1e-12), "k--", lw=2,
label=f"unit sample variance, $\\kappa = "
f"{kap['unit sample variance']:.2f}$")
axG.set_xlabel("gradient descent step $t$")
axG.set_ylabel(r"$\frac{f(\mathbf{w}^{(t)}) - \min_{\mathbf{w}} f(\mathbf{w})}{f(\mathbf{w}^{(0)}) - \min_{\mathbf{w}} f(\mathbf{w})}$")
axG.set_xlim(0, 50)
axG.set_title("Gradient descent before and after scaling\n(relative "
"humidity and wind speed)", fontsize=10)
axG.legend(frameon=False, loc="upper right")
axN.fill(np.concatenate([grid, grid[::-1]]), np.concatenate([lo, hi[::-1]]),
color="0.45", label=f"{NDRAW} random perturbations")
axN.plot(X2[:, 1], y2, "o", color="0.3", ms=4, label=f"the {m2} first days of the months")
axN.plot(grid, fit, "k-", lw=2, label="least squares line")
axN.plot(grid, adv, "k--", lw=2, label="adversarial perturbation")
axN.plot(grid, fit - env, "k:", lw=2, label="bound")
axN.plot(grid, fit + env, "k:", lw=2)
axN.set_xlim(-6, 20); axN.set_ylim(-10, 45)
axN.set_xlabel("lowest temperature of the day ($^\\circ$C)")
axN.set_ylabel("highest temperature of the day ($^\\circ$C)")
axN.set_title(f"Perturbation bound, features (1, lowest temperature)\n"
f"(relative size $\\varepsilon = {EPS1}$, $\\kappa = {kappa2:.1f}$)",
fontsize=10)
axN.legend(frameon=False, loc="upper left", fontsize=8)
fig.tight_layout()
fig.savefig(OUT_DIR / "featuremtx.png", dpi=110)
check("[B-fig] the preview figure was written",
(OUT_DIR / "featuremtx.png").exists())
print()
if FAILED:
print(f"{len(FAILED)} check(s) FAILED: " + "; ".join(FAILED))
raise SystemExit(1)
print("all checks passed")

B-fig writes when the script runs