Dictionary of Applied Machine Learning · data augmentation

data augmentation — Python demo

Updated on 2026-11-23

Numerical companion to the entry data augmentation: it recomputes what the entry states and prints one line per check

Numerical companion to the glossary entry 'dataaug'. The GeoSphere Austria weather station Krems (station id 3805) records the air temperature every hour. This script downloads the 2024 records from the GeoSphere data hub (resource klima-v2-1h), keeps the reading at 06:00 (UTC) and the one at 15:00 (UTC) of each day, and writes the 365 days that carry both to dataaug_readings.csv.

Run it without installing anything:
uv run https://dictionaryofml.org/terms/dataaug.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 dataaug.py into a folder and run uv run dataaug.py there. With NumPy and Matplotlib already installed, python3 dataaug.py, from any directory — it writes its output files into the current directory. Fixed seeds, so the printed numbers reproduce exactly. Download dataaug.py · Notebook · Open in Colab

Before running a downloaded copy, scan it: uvx bandit -q -t B102,B307,B602,B605 dataaug.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.

The script, block by block

One cell per block of the script: the code, and what that code printed when it last ran here

setup

"""Three measured days, the degree-two polynomial that passes through
them, and what happens when each day is replaced by copies drawn from
the uncertainty interval of its readings.

Purpose
-------
Numerical companion to the glossary entry 'dataaug'.  The GeoSphere
Austria weather station Krems (station id 3805) records the air
temperature every hour.  This script downloads the 2024 records from
the GeoSphere data hub (resource klima-v2-1h), keeps the reading at
06:00 (UTC) and the one at 15:00 (UTC) of each day, and writes the 365
days that carry both to dataaug_readings.csv.

The learning task pairs the two readings of a day: the feature of a data
point is the 06:00 reading, its label the 15:00 reading of the same day.
Three days form the training set.  Two of them, 4 January and 18
October, were almost equally warm at 06:00 (10.8 and 11.2 degrees
Celsius) and reached afternoons that differ by 5.5 degrees, which is
what forces the curve through them to be steep.

A polynomial of degree two carries three coefficients, so exactly one of
them passes through three data points: ERM has a unique solution and its
training error is zero.  That solution leaves the range of the three
labels by 20.6 degrees between the measured days and predicts the
held-out days badly.

A measured temperature is one representative of an uncertainty interval,
not the only value that could have been recorded.  Taking that interval
to be plus or minus 1 degree Celsius in both the feature and the label,
every day inside it is as consistent with the measurement as the
recorded day.  Replacing each of the three days by copies drawn from its
interval gives an augmented training set, and ERM on it no longer has to
pass through the three measured days.

The demo checks the claims the entry makes.  (1) Two of the three
training days have features closer than the assumed uncertainty, while
their labels differ by more than five degrees.  (2) The degree-two ERM
solution on the three days has zero training error.  (3) It leaves the
range of the three labels by more than ten degrees.  (4) Every copy lies
within the assumed uncertainty of the day it came from.  (5) ERM on the
augmented training set no longer has zero training error, the
coefficient of the squared feature is smaller by more than a factor of
ten, and it stays within half a
degree of the range of the three labels.  (6) On the held-out day pairs
whose feature lies inside the training range, its average squared error
is smaller by more than a factor of ten.  (7) The width of the interval
acts like the strength of a penalty term: a narrow interval leaves the
steep curve nearly unchanged, and widening it makes that coefficient
fall monotonically, passing through zero at a straight line.  On this training set the
held-out error keeps falling as the interval widens, because the
relation between the two readings is close to linear to begin with; the
width is not tuned on the held-out days.

A copy can instead come from a transformation that leaves the label
alone.  (8) Rotating an MNIST image of a six by a small angle keeps it
nearest to the other sixes along the two principal directions, so
label is preserved, while (9) rotating it by 180 degrees carries it into
the nines, so that transformation is not a symmetry.

Deterministic: the data are a fixed archive year and the copies are
drawn with a fixed seed.  Self-contained: numpy + matplotlib only
(stdlib urllib for the download).

Blocks
------
[B-data]      Download the hourly air temperature of 2024 and pair the
              06:00 (UTC) reading of each day with its 15:00 (UTC) one.
[B-three]     The three training days, including the two whose features
              are closer than the assumed uncertainty.
[B-overfit]   The degree-two ERM solution on the three days: zero
              training error, and a wide swing between them.
[B-augment]   Replace each day by copies drawn from its uncertainty
              interval and run ERM on the augmented training set.
[B-compare]   Held-out error of the two solutions, and the effect of the
              width of the uncertainty interval.
[B-routes]    Perturbing the feature alone, which is the case the ridge
              equivalence covers, and the same shrinkage reached by
              pruning the model instead.
[B-mnist]     MNIST sixes and nines along their two principal
              directions, and the path an image of a six traces as it
              is rotated.
[B-fig]       Preview figure: the two solutions on the left, the
              held-out errors on the right.

Outputs
-------
dataaug_readings.csv : date, 06:00 and 15:00 (UTC) reading, 365 days
dataaug_points.csv  : the three training days, feature and label
dataaug_copies.csv  : the copies drawn inside the uncertainty interval
dataaug_copies_plot.csv : five of them per day, the open squares of Fig. 1
dataaug_curves.csv  : the two ERM solutions on a grid of features
dataaug_valerr.csv  : held-out error of the two solutions
dataaug_featcopies.csv : copies with the feature perturbed alone
dataaug_routes.csv     : the solution learned from those copies
dataaug_mnist_six.csv  : the sixes, two coordinates each
dataaug_mnist_nine.csv : the nines, two coordinates each
dataaug_mnist_path.csv : the rotation path, with the angle
dataaug_six_000.png    : the six, upright
dataaug_six_030.png    : the same six, rotated by 30 degrees
dataaug_six_180.png    : the same six, rotated by 180 degrees
dataaug.png         : preview figure

The MNIST block downloads mnist.npz (about 11 MB) into memory; nothing
is written to disk but the three small CSV files.
"""

# /// script
# requires-python = ">=3.10"
# dependencies = ["matplotlib==3.10.7", "numpy==2.3.4"]
# ///

import io
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
DEGREE = 2
TOL = 1.0                 # assumed uncertainty of a reading, in Celsius
NR_COPIES = 400           # copies drawn per training day
RNG = np.random.default_rng(20240101)

FAILED = []


def check(name, ok):
    FAILED.append(name) if not ok else None
    print(f"  [{'ok' if ok else 'FAIL'}] {name}")

B-data

Download the hourly air temperature of 2024 and pair the 06:00 (UTC) reading of each day with its 15:00 (UTC) one.

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")
with urllib.request.urlopen(URL, timeout=300) as resp:
    payload = json.load(resp)
readings = payload["features"][0]["properties"]["parameters"]["tl"]["data"]
byday = {}
for stamp, value in zip(payload["timestamps"], readings):
    if value is None:                   # the archive drops whole days
        continue
    hour = stamp[11:16]                 # the stamps are UTC, and so are
    if hour in ("06:00", "15:00"):      # the two times, so no conversion
        byday.setdefault(stamp[:10], {})[hour] = float(value)
record = [(day, rec["06:00"], rec["15:00"])
          for day, rec in sorted(byday.items()) if len(rec) == 2]
dates = [day for day, _, _ in record]
with open(OUT_DIR / "dataaug_readings.csv", "w") as f:
    f.write("date,t06,t15\n")
    for day, lo, hi in record:
        f.write(f"{day},{lo:g},{hi:g}\n")
# the 06:00 reading predicts the 15:00 reading of the same day
FEAT = np.array([lo for _, lo, _ in record])
LAB = np.array([hi for _, _, hi in record])
print(f"[B-data] {len(FEAT)} days of 2024 at Krems an der Donau carry "
      f"both readings")
[B-data] 365 days of 2024 at Krems an der Donau carry both readings

B-three

The three training days, including the two whose features are closer than the assumed uncertainty.

DAYS = ["2024-01-01", "2024-01-04", "2024-10-18"]
IDX = [dates.index(d) for d in DAYS]
xt, yt = FEAT[IDX], LAB[IDX]
for d, a, b in zip(DAYS, xt, yt):
    print(f"[B-three] {d}: 06:00 {a:.1f} C, 15:00 {b:.1f} C")
near = sorted(range(3), key=lambda i: xt[i])[-2:]       # the two close days
gap_x = abs(xt[near[0]] - xt[near[1]])
gap_y = abs(yt[near[0]] - yt[near[1]])
print(f"[B-three] two of them differ by {gap_x:.1f} C in the feature and "
      f"by {gap_y:.1f} C in the label")
check("[B-three] two training days have features closer than the assumed "
      "uncertainty", gap_x < TOL)
check("[B-three] yet their labels differ by more than five degrees",
      gap_y > 5.0)

GRID = np.linspace(xt.min(), xt.max(), 400)
[B-three] 2024-01-01: 06:00 4.0 C, 15:00 8.0 C
[B-three] 2024-01-04: 06:00 10.8 C, 15:00 10.0 C
[B-three] 2024-10-18: 06:00 11.2 C, 15:00 15.5 C
[B-three] two of them differ by 0.4 C in the feature and by 5.5 C in the label
  [ok] [B-three] two training days have features closer than the assumed uncertainty
  [ok] [B-three] yet their labels differ by more than five degrees

B-overfit

The degree-two ERM solution on the three days: zero training error, and a wide swing between them.

c_erm = np.polyfit(xt, yt, DEGREE)
fit_erm = np.polyval(c_erm, GRID)
train_erm = float(np.mean((np.polyval(c_erm, xt) - yt) ** 2))
exc_erm = max(fit_erm.max() - yt.max(), yt.min() - fit_erm.min())
print(f"[B-overfit] training error {train_erm:.2e}, coefficient of the "
      f"squared feature {c_erm[0]:+.4f}, excursion beyond the three labels "
      f"{exc_erm:.1f} C")
check("[B-overfit] three coefficients against three data points, so the "
      "training error is zero", train_erm < 1e-12)
check("[B-overfit] the solution leaves the range of the three labels by "
      "more than twenty degrees", exc_erm > 20.0)
[B-overfit] training error 1.35e-28, coefficient of the squared feature +1.8689, excursion beyond the three labels 20.6 C
  [ok] [B-overfit] three coefficients against three data points, so the training error is zero
  [ok] [B-overfit] the solution leaves the range of the three labels by more than twenty degrees

B-augment

Replace each day by copies drawn from its uncertainty interval and run ERM on the augmented training set.

xa = np.repeat(xt, NR_COPIES) + RNG.uniform(-TOL, TOL, NR_COPIES * 3)
ya = np.repeat(yt, NR_COPIES) + RNG.uniform(-TOL, TOL, NR_COPIES * 3)
check("[B-augment] every copy lies within the assumed uncertainty of the "
      "day it came from",
      np.all(np.abs(xa - np.repeat(xt, NR_COPIES)) <= TOL)
      and np.all(np.abs(ya - np.repeat(yt, NR_COPIES)) <= TOL))
c_aug = np.polyfit(xa, ya, DEGREE)
fit_aug = np.polyval(c_aug, GRID)
train_aug = float(np.mean((np.polyval(c_aug, xt) - yt) ** 2))
exc_aug = max(fit_aug.max() - yt.max(), yt.min() - fit_aug.min())
print(f"[B-augment] {len(xa)} copies, training error on the three "
      f"measured days {train_aug:.2f}, coefficient of the squared "
      f"feature {c_aug[0]:+.4f}")
check("[B-augment] the augmented solution no longer passes through the "
      "three measured days", train_aug > 1.0)
check("[B-augment] its coefficient of the squared feature is smaller by "
      "more than a factor of ten",
      abs(c_aug[0]) < abs(c_erm[0]) / 10.0)
check("[B-augment] it stays within half a degree of the range of the "
      "three labels", exc_aug < 0.5)
  [ok] [B-augment] every copy lies within the assumed uncertainty of the day it came from
[B-augment] 1200 copies, training error on the three measured days 4.04, coefficient of the squared feature +0.1086
  [ok] [B-augment] the augmented solution no longer passes through the three measured days
  [ok] [B-augment] its coefficient of the squared feature is smaller by more than a factor of ten
  [ok] [B-augment] it stays within half a degree of the range of the three labels
  [ok] [B-augment] the plotted copies are five per day, 15 in all

B-compare

Held-out error of the two solutions, and the effect of the width of the uncertainty interval.

inside = (FEAT >= xt.min()) & (FEAT <= xt.max())
inside[IDX] = False
rest = np.flatnonzero(inside)


def val(coef):
    return float(np.mean((np.polyval(coef, FEAT[rest]) - LAB[rest]) ** 2))


v_erm, v_aug = val(c_erm), val(c_aug)
print(f"[B-compare] held-out error on {len(rest)} day pairs: "
      f"{v_erm:.1f} for the solution on the three days, {v_aug:.1f} for "
      f"the augmented one")
check("[B-compare] augmentation cuts the held-out error by more than a "
      "factor of ten", v_aug < v_erm / 10.0)
print("[B-compare] width of the uncertainty interval against held-out "
      "error and the coefficient of the squared feature:")
sweep = []
for w in (0.25, 0.5, 1.0, 2.0, 4.0):
    rng = np.random.default_rng(20240101)
    cw = np.polyfit(np.repeat(xt, NR_COPIES) + rng.uniform(-w, w, NR_COPIES * 3),
                    np.repeat(yt, NR_COPIES) + rng.uniform(-w, w, NR_COPIES * 3),
                    DEGREE)
    sweep.append((w, val(cw), cw[0]))
    print(f"              +/- {w:4.2f} C : held-out {val(cw):8.1f}, "
          f"coefficient {cw[0]:+.4f}")
check("[B-compare] a narrow interval leaves the steep solution nearly "
      "unchanged", sweep[0][1] > v_erm / 3.0)
check("[B-compare] the coefficient of the squared feature falls "
      "monotonically as the interval widens, passing through zero at a "
      "straight line",
      all(sweep[i + 1][2] < sweep[i][2] for i in range(len(sweep) - 1))
      and sweep[0][2] > 0.0 > sweep[-1][2])
with open(OUT_DIR / "dataaug_valerr.csv", "w") as f:
    f.write("fit,valerr\n")
    f.write(f"three days,{v_erm:.4f}\n")
    f.write(f"augmented,{v_aug:.4f}\n")

# ---- the figure data
with open(OUT_DIR / "dataaug_points.csv", "w") as f:
    f.write("x,y\n")
    for a, b in zip(xt, yt):
        f.write(f"{a:.4f},{b:.4f}\n")
with open(OUT_DIR / "dataaug_copies.csv", "w") as f:
    f.write("x,y\n")
    for a, b in zip(xa[::20], ya[::20]):       # a readable subset
        f.write(f"{a:.4f},{b:.4f}\n")
with open(OUT_DIR / "dataaug_copies_plot.csv", "w") as f:   # Fig. 1 draws
    f.write("x,y\n")                                          # five copies per day
    for a, b in zip(xa[::80], ya[::80]):
        f.write(f"{a:.4f},{b:.4f}\n")
check("[B-augment] the plotted copies are five per day, 15 in all", xa[::80].size == 15)
with open(OUT_DIR / "dataaug_curves.csv", "w") as f:
    f.write("x,interpolant,augmented\n")
    for a, b, c in zip(GRID, fit_erm, fit_aug):
        f.write(f"{a:.4f},{b:.4f},{c:.4f}\n")
[B-compare] held-out error on 106 day pairs: 335.3 for the solution on the three days, 25.7 for the augmented one
  [ok] [B-compare] augmentation cuts the held-out error by more than a factor of ten
[B-compare] width of the uncertainty interval against held-out error and the coefficient of the squared feature:
              +/- 0.25 C : held-out    129.5, coefficient +1.0159
              +/- 0.50 C : held-out     47.8, coefficient +0.4186
              +/- 1.00 C : held-out     25.7, coefficient +0.1086
              +/- 2.00 C : held-out     21.3, coefficient +0.0108
              +/- 4.00 C : held-out     19.8, coefficient -0.0091
  [ok] [B-compare] a narrow interval leaves the steep solution nearly unchanged
  [ok] [B-compare] the coefficient of the squared feature falls monotonically as the interval widens, passing through zero at a straight line

B-routes

Perturbing the feature alone, which is the case the ridge equivalence covers, and the same shrinkage reached by pruning the model instead.

# reached by pruning the model instead
xf = np.repeat(xt, NR_COPIES) + np.random.default_rng(20240101).uniform(
    -TOL, TOL, NR_COPIES * 3)
yf = np.repeat(yt, NR_COPIES)       # the labels are left where they were
c_feat = np.polyfit(xf, yf, DEGREE)
v_feat = val(c_feat)
fit_feat = np.polyval(c_feat, GRID)
gap_feat = float(np.max(np.abs(fit_feat - fit_aug)))
print(f"[B-routes] perturbing the feature alone gives coefficient "
      f"{c_feat[0]:+.4f} and held-out {v_feat:.1f}, within {gap_feat:.2f} C "
      f"of the solution with both coordinates perturbed")
check("[B-routes] perturbing the feature alone shrinks the coefficient "
      "as perturbing both does",
      abs(c_feat[0]) < abs(c_erm[0]) / 10.0 and gap_feat < 0.5)
with open(OUT_DIR / "dataaug_featcopies.csv", "w") as f:
    f.write("x,y\n")
    for a, b in zip(xf[::20], yf[::20]):
        f.write(f"{a:.4f},{b:.4f}\n")
with open(OUT_DIR / "dataaug_routes.csv", "w") as f:
    f.write("x,featonly\n")
    for a, b in zip(GRID, fit_feat):
        f.write(f"{a:.4f},{b:.4f}\n")

CAP = abs(c_feat[0])                # the coefficient augmentation arrived at
design = np.stack([xt, np.ones_like(xt)], axis=1)
best = None
for w2 in (CAP, -CAP):              # the constraint |w2| <= CAP is active
    w1, w0 = np.linalg.lstsq(design, yt - w2 * xt ** 2, rcond=None)[0]
    cand = np.array([w2, w1, w0])
    tr = float(np.mean((np.polyval(cand, xt) - yt) ** 2))
    if best is None or tr < best[0]:
        best = (tr, cand)
train_prune, c_prune = best
v_prune = val(c_prune)
dev = float(np.max(np.abs(np.polyval(c_prune, GRID) - fit_feat)))
print(f"[B-routes] shrinking the hypothesis space to |w2| <= {CAP:.4f} "
      f"gives training error {train_prune:.2f} and held-out {v_prune:.1f}")
print(f"[B-routes] it stays within {dev:.2f} C of the feature-perturbed "
      f"solution over the measured range")
check("[B-routes] pruning the model and perturbing the feature reach the "
      "same shrinkage within half a degree", dev < 0.5)
check("[B-routes] and their held-out errors agree within a tenth",
      abs(v_prune - v_feat) < 0.1 * v_feat)
[B-routes] perturbing the feature alone gives coefficient +0.1042 and held-out 25.5, within 0.05 C of the solution with both coordinates perturbed
  [ok] [B-routes] perturbing the feature alone shrinks the coefficient as perturbing both does
[B-routes] shrinking the hypothesis space to |w2| <= 0.1042 gives training error 4.05 and held-out 25.5
[B-routes] it stays within 0.11 C of the feature-perturbed solution over the measured range
  [ok] [B-routes] pruning the model and perturbing the feature reach the same shrinkage within half a degree
  [ok] [B-routes] and their held-out errors agree within a tenth

B-mnist

MNIST sixes and nines along their two principal directions, and the path an image of a six traces as it is rotated.

MNIST_URL = ("https://storage.googleapis.com/tensorflow/"
             "tf-keras-datasets/mnist.npz")
with urllib.request.urlopen(MNIST_URL, timeout=180) as resp:
    mnist = np.load(io.BytesIO(resp.read()))
images = mnist["x_train"].astype(float) / 255.0
digits = mnist["y_train"]


def rotate(img, deg):
    """Rotate an image about its centre, bilinear, numpy only."""
    h, w = img.shape
    cy, cx = (h - 1) / 2.0, (w - 1) / 2.0
    th = np.deg2rad(deg)
    ys, xs = np.mgrid[0:h, 0:w]
    dx, dy = xs - cx, ys - cy
    sx = cx + np.cos(th) * dx + np.sin(th) * dy
    sy = cy - np.sin(th) * dx + np.cos(th) * dy
    x0, y0 = np.floor(sx).astype(int), np.floor(sy).astype(int)
    fx, fy = sx - x0, sy - y0
    out = np.zeros_like(img)
    for ddy in (0, 1):
        for ddx in (0, 1):
            xi, yi = x0 + ddx, y0 + ddy
            ok = (xi >= 0) & (xi < w) & (yi >= 0) & (yi < h)
            wgt = (fx if ddx else 1 - fx) * (fy if ddy else 1 - fy)
            out[ok] += wgt[ok] * img[np.clip(yi, 0, h - 1),
                                     np.clip(xi, 0, w - 1)][ok]
    return out


NR_DIGITS = 400
idx6 = np.flatnonzero(digits == 6)[:NR_DIGITS]
idx9 = np.flatnonzero(digits == 9)[:NR_DIGITS]
flat = np.concatenate([images[idx6], images[idx9]]).reshape(2 * NR_DIGITS, -1)
centre = flat.mean(axis=0)
basis = np.linalg.svd(flat - centre, full_matrices=False)[2][:2]
emb = (flat - centre) @ basis.T
emb6, emb9 = emb[:NR_DIGITS], emb[NR_DIGITS:]
mid6, mid9 = emb6.mean(axis=0), emb9.mean(axis=0)
ANGLES = np.arange(0, 181, 15)
path = np.stack([(rotate(images[idx6[0]], a).reshape(-1) - centre) @ basis.T
                 for a in ANGLES])
d6 = np.linalg.norm(path - mid6, axis=1)
d9 = np.linalg.norm(path - mid9, axis=1)
print(f"[B-mnist] {2 * NR_DIGITS} images reduced to two coordinates; "
      f"the sixes and the "
      f"nines sit {np.linalg.norm(mid6 - mid9):.2f} apart")
for a, a6, a9 in zip(ANGLES, d6, d9):
    if a in (0, 15, 90, 180):
        print(f"[B-mnist] rotated by {a:3d} deg: {a6:5.2f} from the sixes, "
              f"{a9:5.2f} from the nines")
check("[B-mnist] a small rotation keeps the image nearest to the sixes, "
      "so it preserves the label",
      all(d6[ANGLES == a][0] < d9[ANGLES == a][0] for a in (15, 30)))
check("[B-mnist] rotating by 180 degrees carries it into the nines, so "
      "that transformation is not a symmetry",
      d9[ANGLES == 180][0] < d6[ANGLES == 180][0])
for name, arr in (("six", emb6), ("nine", emb9)):
    with open(OUT_DIR / f"dataaug_mnist_{name}.csv", "w") as f:
        f.write("x1,x2\n")
        for a, b in arr:
            f.write(f"{a:.4f},{b:.4f}\n")
# the two ends of the path, as images, for the inlays of the entry's figure
for deg, tag in ((0, "000"), (30, "030"), (180, "180")):
    plt.imsave(OUT_DIR / f"dataaug_six_{tag}.png",
               rotate(images[idx6[0]], deg), cmap="gray_r", vmin=0.0, vmax=1.0)
check("[B-mnist] the three inlay images were written",
      all((OUT_DIR / f"dataaug_six_{t}.png").exists()
          for t in ("000", "030", "180")))
with open(OUT_DIR / "dataaug_mnist_path.csv", "w") as f:
    f.write("x1,x2,deg\n")
    for (a, b), deg in zip(path, ANGLES):
        f.write(f"{a:.4f},{b:.4f},{deg}\n")
[B-mnist] 800 images reduced to two coordinates; the sixes and the nines sit 4.64 apart
[B-mnist] rotated by   0 deg:  0.55 from the sixes,  5.11 from the nines
[B-mnist] rotated by  15 deg:  0.79 from the sixes,  4.74 from the nines
[B-mnist] rotated by  90 deg:  2.86 from the sixes,  2.80 from the nines
[B-mnist] rotated by 180 deg:  5.18 from the sixes,  1.01 from the nines
  [ok] [B-mnist] a small rotation keeps the image nearest to the sixes, so it preserves the label
  [ok] [B-mnist] rotating by 180 degrees carries it into the nines, so that transformation is not a symmetry
  [ok] [B-mnist] the three inlay images were written

B-fig

Preview figure: the two solutions on the left, the held-out errors on the right.

fig, (axP, axV, axM) = plt.subplots(1, 3, figsize=(14.4, 3.8))
axP.plot(GRID, fit_erm, "k-", lw=1.6,
         label="degree-2 ERM solution on the three days")
axP.plot(GRID, fit_aug, "k--", lw=1.6,
         label="degree-2 ERM solution on the augmented set")
axP.plot(xa[::20], ya[::20], "s", mfc="none", mec="0.45", ms=4,
         label="copy from the uncertainty interval")
axP.plot(xt, yt, "ko", ms=7, label="measured day")
axP.set_xlabel("15:00 (UTC) reading today in $^\\circ$C")
axP.set_ylabel("15:00 (UTC) reading tomorrow in $^\\circ$C")
axP.set_title("Three measured days and two learned hypotheses", fontsize=10)
axP.set_ylim(yt.min() - 14, yt.max() + 14)
axP.legend(frameon=False, fontsize=7, loc="lower right")
widths = [f"$\\pm${w:g}" for w, _, _ in sweep]
axV.bar(widths, [v for _, v, _ in sweep], color="0.55", edgecolor="black")
axV.axhline(v_erm, color="black", ls="-", lw=1.2,
            label="solution on the three days")
axV.set_xlabel("half-width of the uncertainty interval in $^\\circ$C")
axV.set_ylabel("average squared error in $(^\\circ$C$)^2$")
axV.set_title(f"Error on the {len(rest)} day pairs held out", fontsize=10)
axV.set_yscale("log")
axV.legend(frameon=False, fontsize=7)
axM.plot(emb6[:, 0], emb6[:, 1], "o", mfc="none", mec="0.6", ms=3,
         label="image of a six")
axM.plot(emb9[:, 0], emb9[:, 1], "^", mfc="none", mec="0.3", ms=3,
         label="image of a nine")
axM.plot(path[:, 0], path[:, 1], "k-s", lw=1.4, ms=3.5,
         label="the six, rotated")
axM.annotate("0$^\\circ$", path[0], textcoords="offset points",
             xytext=(6, 4), fontsize=8)
axM.annotate("180$^\\circ$", path[-1], textcoords="offset points",
             xytext=(6, 4), fontsize=8)
axM.set_xlabel("first principal direction")
axM.set_ylabel("second principal direction")
axM.set_title("Rotating a six carries it to the nines", fontsize=10)
axM.legend(frameon=False, fontsize=7)
fig.tight_layout()
fig.savefig(OUT_DIR / "dataaug.png", dpi=110)
check("[B-fig] the preview figure was written",
      (OUT_DIR / "dataaug.png").exists())

print()
if FAILED:
    print(f"{len(FAILED)} check(s) FAILED: " + "; ".join(FAILED))
    raise SystemExit(1)
print("all checks passed")
  [ok] [B-fig] the preview figure was written

all checks passed
Preview figure produced by dataaug.py
The preview figure the block B-fig writes when the script runs