Dictionary of Applied Machine Learning · data imputation

data imputation — Python demo

Updated on 2026-11-03

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

Two experiments carry out the entry's construction, that filling in a missing value is a prediction task: the missing value is the label of a data point, the values recorded beside it are its feature vector, and the complete data points are the training set on which a hypothesis is learned.

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

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

"""
dataimputation.py -- numerical companion to the glossary entry
'data imputation'.

Two experiments carry out the entry's construction, that filling in a
missing value is a prediction task: the missing value is the label of a
data point, the values recorded beside it are its feature vector, and the
complete data points are the training set on which a hypothesis is
learned.

The first experiment is on tabular data. The daily weather measurements
of 2024 at the station Krems an der Donau (GeoSphere Austria) form a
table with one row per day and the columns date, minimum temperature,
precipitation and maximum temperature. Fifteen days spread over the
year are taken, three of their maximum-temperature cells are emptied, a
linear hypothesis from the minimum temperature of a day to its maximum
temperature is learned from the twelve complete rows, and the emptied
cells are filled with its predictions.
The values that were removed are known, so the filled values are scored
against them and against the baseline that fills every empty cell with
the column average.

The second experiment is on an image. A piece of the aerial photograph
of the Wachau (assets/wachau_ortho.jpg, orthophoto (c) basemap.at,
CC BY 4.0; 0.9 km by 0.6 km, reduced to 64 x 96 pixels of 9.5 m) shows
an arm of the Danube between forest and fields. Ten rectangular patches
of its pixels are lost. Each pixel is a data point whose feature vector holds
the red, green and blue values of its eight neighbors and whose label is
its own triple, the intact pixels are the training set, and the lost
pixels are filled by iterating the learned hypothesis to a fixed point,
since a lost pixel has lost neighbors.

Self-contained (numpy/matplotlib only), fixed seed. The weather table is
downloaded from GeoSphere Austria; the photograph is read from the
repository or downloaded from dictionaryofml.org.

Blocks
------
[B-table]  The 2024 Krems table: 366 rows, four columns, no empty cell.
[B-cells]  Fifteen days, every 25th day of the year, and three of their
           maximum-temperature cells emptied. The twelve complete rows
           are the training set; a linear hypothesis from the minimum to
           the maximum temperature of a day is learned from them and
           fills the empty cells. The filled values are scored against
           the removed ones and against the column average.
[B-view]   The piece of the aerial photograph and the ten rectangular
           patches of 6 x 8 pixels that are lost, with the share of
           pixels that went missing.
[B-pixels] Every intact pixel whose eight neighbors are also intact
           becomes a data point, with a feature vector of 24 numbers and
           a label of 3.
[B-fit]    A linear hypothesis from the 24 features to the 3 label
           values is learned from the intact pixels by least squares and
           by ridge regression, and compared on intact pixels kept out of
           the training set against the baseline that predicts the
           average color.
[B-sweep]  One sweep re-predicts every lost pixel from its eight current
           neighbors, an affine map on the lost pixels' values. Iterating
           it converges to its unique fixed point if and only if the
           spectral radius of its linear part is below one. For the
           least-squares hypothesis it is 2.97, so the sweeps diverge;
           the ridge penalty shrinks the weights and brings it below one.
[B-fill]   The lost patches are filled by iterating the ridge sweep: the
           lost pixels start at the average color and are re-predicted
           from their neighbors until a sweep stops changing them, which
           is the fixed point. The result is scored against the pixels
           that were removed.
[B-edge]   Where the error falls: the filling is accurate where the
           surrounding colors are nearly constant and worst on the pixels
           where the river meets its bank.

Outputs
-------
dataimputation_table.csv : the 2024 Krems table, four columns (date,
                           tmin, precip, tmax), for the entry's Fig. 1.
dataimputation_days.csv  : the twelve complete days (tmin, tmax), for
                           the scatterplot of Fig. 2.
dataimputation_cells.csv : the three emptied cells, with the removed
                           value and the filled value, for Fig. 2.
dataimputation_line.csv  : two points of the learned line, for Fig. 2.
dataimputation_radius.csv: the penalty values tried, with the training
                           error and the spectral radius of the sweep.
dataimputation_err.csv   : per-method average squared error on the lost
                           pixels, for the entry's Fig. 4.
dataimputation.png       : preview of both experiments (checking only).

Data generated by pythondemos/dataimputation.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
from matplotlib.image import imread

OUT_DIR = Path(__file__).parent
ASSET_URL = "https://dictionaryofml.org/demoassets/"
rng = np.random.default_rng(20261007)

report = []


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


def demo_asset(name):
    """Path to the input file `name`, fetched once if it is not already here.

    Inside the repository the committed copy is used (pythondemos/ first,
    then assets/), so a run there reproduces the committed outputs exactly.
    Run from anywhere else -- from the copy published on dictionaryofml.org,
    say -- the file is downloaded and cached beside the script, so the demo
    is runnable without the repository.
    """
    for cand in (OUT_DIR / name, OUT_DIR.parent / "assets" / name):
        if cand.exists():
            return cand
    cached = OUT_DIR / name
    print(f"    fetching {name} from {ASSET_URL}{name}")
    with urllib.request.urlopen(ASSET_URL + name, timeout=180) as resp:
        cached.write_bytes(resp.read())
    return cached


def learn_linear(X, y, penalty=0.0):
    """Linear hypothesis with an intercept: the minimizer of the average
    squared error loss plus penalty * squared norm of the weights (the
    intercept is not penalized); penalty 0 is least squares."""
    A = np.c_[X, np.ones(len(X))]
    P = np.eye(A.shape[1])
    P[-1, -1] = 0.0
    return np.linalg.solve(A.T @ A + penalty * len(X) * P, A.T @ y)


def apply_linear(w, X):
    return np.c_[X, np.ones(len(X))] @ w

B-table

The 2024 Krems table: 366 rows, four columns, no empty cell.

print("[B-table] the 2024 weather table of Krems an der Donau")

URL = ("https://dataset.api.hub.geosphere.at/v1/station/historical/"
       "klima-v2-1d?parameters=tlmin,rr,tlmax&station_ids=3805"
       "&start=2024-01-01&end=2024-12-31")
with urllib.request.urlopen(URL, timeout=120) as resp:
    payload = json.load(resp)
params = payload["features"][0]["properties"]["parameters"]
rows = [(stamp[:10], lo, rr, hi)
        for stamp, lo, rr, hi in zip(payload["timestamps"],
                                     params["tlmin"]["data"],
                                     params["rr"]["data"],
                                     params["tlmax"]["data"])]
with open(OUT_DIR / "dataimputation_table.csv", "w") as fh:
    fh.write("date,tmin,precip,tmax\n")
    for day, lo, rr, hi in rows:
        fh.write(f"{day},{lo},{rr},{hi}\n")
print(f"    {len(rows)} rows, four columns; first row {rows[0]}")
check("[B-table] the table has one row per day of 2024", len(rows) == 366)
check("[B-table] every cell of the downloaded table holds a value",
      all(v is not None for row in rows for v in row[1:]))
check("[B-table] the record matches the archive (Jan 1: 2.6 to 9.6)",
      rows[0][1] == 2.6 and rows[0][3] == 9.6)
[B-table] the 2024 weather table of Krems an der Donau
    366 rows, four columns; first row ('2024-01-01', 2.6, 0.0, 9.6)
  [ok] [B-table] the table has one row per day of 2024
  [ok] [B-table] every cell of the downloaded table holds a value
  [ok] [B-table] the record matches the archive (Jan 1: 2.6 to 9.6)

B-cells

Fifteen days, every 25th day of the year, and three of their maximum-temperature cells emptied. The twelve complete rows are the training set; a linear hypothesis from the minimum to the maximum temperature of a day is learned from them and fills the empty cells. The filled values are scored against the removed ones and against the column average.

print("\n[B-cells] fifteen days, three emptied cells, filled from the complete rows")

STEP, N_EMPTY = 25, 3
days = list(range(0, len(rows), STEP))          # every 25th day: 15 days
rows = [rows[i] for i in days]
tmin = np.array([r[1] for r in rows])
tmax = np.array([r[3] for r in rows])
empty = np.zeros(len(rows), dtype=bool)
empty[rng.choice(len(rows), size=N_EMPTY, replace=False)] = True
complete = ~empty
print(f"    {len(rows)} days from {rows[0][0]} to {rows[-1][0]}; emptied: "
      + ", ".join(rows[i][0] for i in np.flatnonzero(empty)))

# the complete rows are the training set: feature = minimum temperature,
# label = maximum temperature of the same day
w_day = learn_linear(tmin[complete, None], tmax[complete])
filled_cells = apply_linear(w_day, tmin[empty, None])
column_mean = tmax[complete].mean()
err_cells = float(np.mean((filled_cells - tmax[empty]) ** 2))
err_cells_mean = float(np.mean((column_mean - tmax[empty]) ** 2))
print(f"    learned line: tmax = {w_day[0]:.3f} * tmin + {w_day[1]:.2f}")
print(f"    average squared error on the {N_EMPTY} emptied cells: "
      f"{err_cells:.2f} (deg C)^2; column average: {err_cells_mean:.2f}")

with open(OUT_DIR / "dataimputation_days.csv", "w") as fh:
    fh.write("tmin,tmax\n")
    for lo, hi in zip(tmin[complete], tmax[complete]):
        fh.write(f"{lo},{hi}\n")
with open(OUT_DIR / "dataimputation_cells.csv", "w") as fh:
    fh.write("date,tmin,tmax_removed,tmax_filled\n")
    for i, hat in zip(np.flatnonzero(empty), filled_cells):
        fh.write(f"{rows[i][0]},{tmin[i]},{tmax[i]},{hat:.2f}\n")
with open(OUT_DIR / "dataimputation_line.csv", "w") as fh:
    fh.write("tmin,tmax\n")
    for lo in (tmin.min(), tmin.max()):
        fh.write(f"{lo},{apply_linear(w_day, np.array([[lo]]))[0]:.3f}\n")

check("[B-cells] fifteen days are taken and twelve of them are complete",
      len(rows) == 15 and complete.sum() == 15 - N_EMPTY)
check("[B-cells] the learned line fills better than the column average",
      err_cells < err_cells_mean)
check("[B-cells] the filled values stay within the recorded range",
      filled_cells.min() > tmax.min() - 5 and filled_cells.max() < tmax.max() + 5)
[B-cells] fifteen days, three emptied cells, filled from the complete rows
    15 days from 2024-01-01 to 2024-12-16; emptied: 2024-02-20, 2024-08-13, 2024-09-07
    learned line: tmax = 1.373 * tmin + 7.76
    average squared error on the 3 emptied cells: 17.64 (deg C)^2; column average: 150.18
  [ok] [B-cells] fifteen days are taken and twelve of them are complete
  [ok] [B-cells] the learned line fills better than the column average
  [ok] [B-cells] the filled values stay within the recorded range

B-view

The piece of the aerial photograph and the ten rectangular patches of 6 x 8 pixels that are lost, with the share of pixels that went missing.

print("\n[B-view] a piece of the aerial photograph and the patches that are lost")

photo = imread(demo_asset("wachau_ortho.jpg")) / 255.0
H, W, REDUCE = 64, 96, 4
R0, C0 = 300, 1280                 # the piece: an arm of the Danube near Rossatz
piece = photo[R0:R0 + REDUCE * H, C0:C0 + REDUCE * W]
scene = piece.reshape(H, REDUCE, W, REDUCE, 3).mean(axis=(1, 3))

PATCH_H, PATCH_W = 6, 8             # each lost patch is 6 x 8 pixels
PATCH_CORNERS = [(6, 8), (6, 40), (6, 76), (24, 18), (24, 52), (42, 8),
                 (42, 36), (42, 70), (28, 80), (52, 56)]
lost = np.zeros((H, W), dtype=bool)
for r, c in PATCH_CORNERS:
    lost[r:r + PATCH_H, c:c + PATCH_W] = True
share = lost.mean()
print(f"    view {H} x {W} pixels of {2.38 * REDUCE:.1f} m; the "
      f"{len(PATCH_CORNERS)} lost patches cover {lost.sum()} pixels "
      f"({100 * share:.1f}%)")
check("[B-view] the piece is 64 x 96 pixels with three color channels",
      scene.shape == (H, W, 3))
check("[B-view] between 5 and 10 percent of the pixels are lost",
      0.05 < share < 0.10)
[B-view] a piece of the aerial photograph and the patches that are lost
    view 64 x 96 pixels of 9.5 m; the 10 lost patches cover 480 pixels (7.8%)
  [ok] [B-view] the piece is 64 x 96 pixels with three color channels
  [ok] [B-view] between 5 and 10 percent of the pixels are lost

B-pixels

Every intact pixel whose eight neighbors are also intact becomes a data point, with a feature vector of 24 numbers and a label of 3.

print("\n[B-pixels] every intact pixel with intact neighbors is a data point")

OFFSETS = [(dr, dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1)
           if (dr, dc) != (0, 0)]


def neighbor_features(img, r, c):
    return np.concatenate([img[r + dr, c + dc] for dr, dc in OFFSETS])


def build_set(img, usable):
    feats, labels, where = [], [], []
    for r in range(1, H - 1):
        for c in range(1, W - 1):
            if not usable[r, c]:
                continue
            if not all(usable[r + dr, c + dc] for dr, dc in OFFSETS):
                continue
            feats.append(neighbor_features(img, r, c))
            labels.append(img[r, c])
            where.append((r, c))
    return np.array(feats), np.array(labels), where


intact = ~lost
X, y, coords = build_set(scene, intact)
print(f"    {len(y)} data points, {X.shape[1]} features, "
      f"{y.shape[1]} label values each")
check("[B-pixels] the feature vector holds the RGB of the eight neighbors",
      X.shape[1] == 8 * 3)
check("[B-pixels] the label is the pixel's own RGB triple", y.shape[1] == 3)
check("[B-pixels] no data point uses a lost pixel",
      all(intact[r, c] for r, c in coords))
[B-pixels] every intact pixel with intact neighbors is a data point
    5028 data points, 24 features, 3 label values each
  [ok] [B-pixels] the feature vector holds the RGB of the eight neighbors
  [ok] [B-pixels] the label is the pixel's own RGB triple
  [ok] [B-pixels] no data point uses a lost pixel

B-fit

A linear hypothesis from the 24 features to the 3 label values is learned from the intact pixels by least squares and by ridge regression, and compared on intact pixels kept out of the training set against the baseline that predicts the average color.

print("\n[B-fit] a linear hypothesis learned from the intact pixels")

perm = rng.permutation(len(y))
cut = int(0.8 * len(y))
tr, va = perm[:cut], perm[cut:]
mean_color = y[tr].mean(axis=0)
err_base = float(np.mean((mean_color - y[va]) ** 2))
PENALTY = 0.03
w_ls = learn_linear(X[tr], y[tr])
w_ridge = learn_linear(X[tr], y[tr], PENALTY)
err_ls = float(np.mean((apply_linear(w_ls, X[va]) - y[va]) ** 2))
err_ridge = float(np.mean((apply_linear(w_ridge, X[va]) - y[va]) ** 2))
print(f"    average squared error on intact pixels outside the training "
      f"set: least squares {err_ls:.5f}, ridge (penalty {PENALTY}) "
      f"{err_ridge:.5f}, average color {err_base:.5f}")
check("[B-fit] both learned hypotheses beat the average-color baseline",
      err_ls < 0.5 * err_base and err_ridge < 0.5 * err_base)
[B-fit] a linear hypothesis learned from the intact pixels
    average squared error on intact pixels outside the training set: least squares 0.00095, ridge (penalty 0.03) 0.00177, average color 0.01335
  [ok] [B-fit] both learned hypotheses beat the average-color baseline

B-sweep

One sweep re-predicts every lost pixel from its eight current neighbors, an affine map on the lost pixels' values. Iterating it converges to its unique fixed point if and only if the spectral radius of its linear part is below one. For the least-squares hypothesis it is 2.97, so the sweeps diverge; the ridge penalty shrinks the weights and brings it below one.

print("\n[B-sweep] one sweep over the lost pixels as an affine map")

lost_coords = [(r, c) for r in range(1, H - 1) for c in range(1, W - 1)
               if lost[r, c]]
check("[B-sweep] no lost pixel touches the border of the view",
      len(lost_coords) == int(lost.sum()))
slot = {p: i for i, p in enumerate(lost_coords)}


def sweep_matrix(w):
    """Linear part of one sweep, acting on the stacked RGB values of the
    lost pixels: the entry for lost pixel p and its lost neighbor q is the
    3 x 3 block of weights that carries q's color into p's prediction."""
    n = len(lost_coords)
    M = np.zeros((3 * n, 3 * n))
    for p, (r, c) in enumerate(lost_coords):
        for k, (dr, dc) in enumerate(OFFSETS):
            q = slot.get((r + dr, c + dc))
            if q is not None:
                M[3 * p:3 * p + 3, 3 * q:3 * q + 3] = w[3 * k:3 * k + 3, :].T
    return M


def spectral_radius(M):
    return float(np.abs(np.linalg.eigvals(M)).max())


with open(OUT_DIR / "dataimputation_radius.csv", "w") as fh:
    fh.write("penalty,trainerr,radius\n")
    for pen in (0.0, 0.001, 0.01, PENALTY, 0.1):
        w = learn_linear(X[tr], y[tr], pen)
        err_tr = float(np.mean((apply_linear(w, X[tr]) - y[tr]) ** 2))
        rho = spectral_radius(sweep_matrix(w))
        print(f"    penalty {pen:<6g} training error {err_tr:.5f}   "
              f"spectral radius of the sweep {rho:.3f}")
        fh.write(f"{pen},{err_tr:.5f},{rho:.3f}\n")
rho_ls = spectral_radius(sweep_matrix(w_ls))
rho_ridge = spectral_radius(sweep_matrix(w_ridge))
check("[B-sweep] the least-squares sweep is not a contraction", rho_ls > 1.0)
check("[B-sweep] the ridge sweep is a contraction", rho_ridge < 1.0)
[B-sweep] one sweep over the lost pixels as an affine map
  [ok] [B-sweep] no lost pixel touches the border of the view
    penalty 0      training error 0.00089   spectral radius of the sweep 2.719
    penalty 0.001  training error 0.00105   spectral radius of the sweep 1.301
    penalty 0.01   training error 0.00142   spectral radius of the sweep 0.905
    penalty 0.03   training error 0.00169   spectral radius of the sweep 0.838
    penalty 0.1    training error 0.00257   spectral radius of the sweep 0.674
  [ok] [B-sweep] the least-squares sweep is not a contraction
  [ok] [B-sweep] the ridge sweep is a contraction

B-fill

The lost patches are filled by iterating the ridge sweep: the lost pixels start at the average color and are re-predicted from their neighbors until a sweep stops changing them, which is the fixed point. The result is scored against the pixels that were removed.

print("\n[B-fill] filling the lost patches by iterating the ridge sweep")

# The lost pixels start at the average color and are then re-predicted from
# their eight current neighbors, over and over. One sweep applies the map
# T; filling in means iterating u^(t+1) = T(u^(t)) to its fixed point.
TOL, MAX_SWEEPS = 1e-5, 1000


def fill_by_sweeps(w):
    filled = scene.copy()
    filled[lost] = mean_color
    changes = []
    for sweep in range(MAX_SWEEPS):
        nxt = filled.copy()
        Xq = np.array([neighbor_features(filled, r, c) for r, c in lost_coords])
        nxt[tuple(np.array(lost_coords).T)] = np.clip(
            apply_linear(w, Xq), 0.0, 1.0)
        changes.append(float(np.abs(nxt - filled).max()))
        filled = nxt
        if changes[-1] < TOL:
            break
    return filled, sweep + 1, changes


filled_ls, sweeps_ls, changes_ls = fill_by_sweeps(w_ls)
err_ls_fill = float(np.mean((filled_ls[lost] - scene[lost]) ** 2))
print(f"    least squares: {sweeps_ls} sweeps, last change "
      f"{changes_ls[-1]:.2e}, average squared error on the lost pixels "
      f"{err_ls_fill:.5f}")
filled, n_sweeps, changes = fill_by_sweeps(w_ridge)
err_filled = float(np.mean((filled[lost] - scene[lost]) ** 2))
err_filled_base = float(np.mean((mean_color - scene[lost]) ** 2))
print(f"    ridge: {n_sweeps} sweeps to a change of {changes[-1]:.2e}; "
      f"average squared error on the lost pixels: {err_filled:.5f}   "
      f"(average color: {err_filled_base:.5f})")
check("[B-fill] the least-squares sweeps do not settle",
      changes_ls[-1] >= TOL)
check("[B-fill] the ridge sweeps reach a fixed point of that map",
      changes[-1] < TOL and changes[-1] < changes[0])
check("[B-fill] the filled values stay inside the range of a color",
      filled.min() >= 0.0 and filled.max() <= 1.0)
check("[B-fill] filling beats predicting the average color",
      err_filled < 0.6 * err_filled_base)
[B-fill] filling the lost patches by iterating the ridge sweep
    least squares: 1000 sweeps, last change 1.00e+00, average squared error on the lost pixels 0.27061
    ridge: 44 sweeps to a change of 8.57e-06; average squared error on the lost pixels: 0.00447   (average color: 0.00980)
  [ok] [B-fill] the least-squares sweeps do not settle
  [ok] [B-fill] the ridge sweeps reach a fixed point of that map
  [ok] [B-fill] the filled values stay inside the range of a color
  [ok] [B-fill] filling beats predicting the average color

B-edge

Where the error falls: the filling is accurate where the surrounding colors are nearly constant and worst on the pixels where the river meets its bank.

print("\n[B-edge] where the error sits")

# A lost pixel sits on a boundary when the recorded colors of the 3 x 3
# block around it spread (largest minus smallest value in some channel)
# by more than SPREAD; otherwise its surroundings are nearly constant.
SPREAD = 0.15
sq_err = ((filled - scene) ** 2).mean(axis=2)
block_max = np.full((H, W, 3), -np.inf)
block_min = np.full((H, W, 3), np.inf)
for dr in (-1, 0, 1):
    for dc in (-1, 0, 1):
        shifted = np.roll(np.roll(scene, dr, axis=0), dc, axis=1)
        block_max = np.maximum(block_max, shifted)
        block_min = np.minimum(block_min, shifted)
on_edge = ((block_max - block_min) > SPREAD).any(axis=2)
edge_lost = lost & on_edge
flat_lost = lost & ~on_edge
print(f"    lost pixels on a boundary: {edge_lost.sum()}, error "
      f"{sq_err[edge_lost].mean():.5f}")
print(f"    lost pixels with nearly constant surroundings: "
      f"{flat_lost.sum()}, error {sq_err[flat_lost].mean():.5f}")
check("[B-edge] both kinds of lost pixel occur among the lost patches",
      edge_lost.sum() >= 20 and flat_lost.sum() >= 20)
check("[B-edge] the error is larger on the boundary pixels",
      sq_err[edge_lost].mean() > 2 * sq_err[flat_lost].mean())

with open(OUT_DIR / "dataimputation_err.csv", "w") as fh:
    fh.write("method,err\n")
    fh.write(f"average color,{err_filled_base:.5f}\n")
    fh.write(f"learned from neighbors,{err_filled:.5f}\n")
    fh.write(f"constant surroundings,{sq_err[flat_lost].mean():.5f}\n")
    fh.write(f"on a boundary,{sq_err[edge_lost].mean():.5f}\n")


# ---------------------------------------------------------------- preview
corrupted = scene.copy()
corrupted[lost] = 1.0

fig, axs = plt.subplots(1, 4, figsize=(14.5, 3.4),
                        gridspec_kw={"width_ratios": [1.25, 1, 1, 1]})
ax_k, ax_a, ax_b, ax_c = axs

ax_k.plot(tmin[complete], tmax[complete], "o", ms=2, color="0.6",
          label="complete days")
line_x = np.array([tmin.min(), tmin.max()])
ax_k.plot(line_x, apply_linear(w_day, line_x[:, None]), "k-", lw=1.2,
          label="learned line")
ax_k.plot(tmin[empty], tmax[empty], "kx", ms=5, label="removed value")
ax_k.plot(tmin[empty], filled_cells, "s", ms=5, mfc="none", mec="k",
          label="filled value")
ax_k.set_xlabel("minimum temperature of the day (deg C)")
ax_k.set_ylabel("maximum temperature of the day (deg C)")
ax_k.set_title(f"Krems 2024, {N_EMPTY} emptied cells filled", fontsize=9)
ax_k.legend(frameon=False, fontsize=7)

for ax, img, title in ((ax_a, scene, "the piece of the photograph"),
                       (ax_b, corrupted,
                        f"{100 * share:.0f}% of the pixels lost (white patches)"),
                       (ax_c, filled,
                        f"filled in, squared error {err_filled:.4f}")):
    ax.imshow(img, interpolation="nearest")
    ax.set_xlabel("pixel column")
    ax.set_ylabel("pixel row")
    ax.set_title(title, fontsize=9)

fig.tight_layout()
fig.savefig(OUT_DIR / "dataimputation.png", dpi=110)

n_ok = sum(ok for _, ok in report)
print(f"\n{n_ok}/{len(report)} checks pass")
print("wrote dataimputation_table.csv, dataimputation_days.csv, "
      "dataimputation_cells.csv, dataimputation_line.csv, "
      "dataimputation_radius.csv, dataimputation_err.csv, "
      "dataimputation.png")
if n_ok != len(report):
    raise SystemExit(1)
[B-edge] where the error sits
    lost pixels on a boundary: 139, error 0.00998
    lost pixels with nearly constant surroundings: 341, error 0.00222
  [ok] [B-edge] both kinds of lost pixel occur among the lost patches
  [ok] [B-edge] the error is larger on the boundary pixels

21/21 checks pass
wrote dataimputation_table.csv, dataimputation_days.csv, dataimputation_cells.csv, dataimputation_line.csv, dataimputation_radius.csv, dataimputation_err.csv, dataimputation.png
Preview figure produced by dataimputation.py
The preview figure the block B-edge writes when the script runs