Lesson 2.4 — Generalization & Model Debugging
Risk · training objective vs. true risk
The training set is only a finite sample from the data distribution. Empirical risk is the sample average, whereas expected risk is the model's average loss over the target distribution. Under IID sampling for a fixed model, sample mean is unbiased, but selecting a model on the same training set introduces selection bias.
01 · Empirical Risk Sampler
Dataset splitting · prevent evaluation contamination
Suppose deployment means predicting the next state on a new robot run. A validation row can have a unique row number and still contain measurements the model has already seen. Track raw record IDs through the windowing step.
| Window from run T0 | Record 2 | Record 3 | Record 4 | Record 5 |
|---|---|---|---|---|
| Training input ending at time 4 | Used | Used | Used | |
| Validation input ending at time 5 | Used | Used | Used |
Two of the three validation inputs are the very same records used in training. Even windows with disjoint records may share a run's sensor calibration or motion pattern. For a new-run evaluation, assign complete runs to splits first and form windows inside each split. In the inspector, switch from Mixed rows to Hold out trajectories and follow the highlighted run.
A future-time evaluation asks a different question. A forecast may use earlier measurements that would be available at its forecast origin. Training targets must precede the validation period, and preprocessing statistics must come from training data. The split should reproduce the information available when a real forecast is made.
02 · Trajectory Split Inspector (6 Trajectories × 10 Steps)
Model capacity · underfitting and overfitting
At fixed input x, write the test outcome as y = f(x) + ε, with f(x) = E[y | x]. The predictor varies over training samples or training randomness. The fresh test noise is independent of that randomness conditional on x; its conditional variance is σ²ε in the identity below.
The bias–variance decomposition above holds for fixed x, squared error, and
zero-mean independent noise; it does not imply that deep network error always follows a U-curve
with parameter count.
03 · Capacity & Bias–Variance Explorer
Regularization · L1/L2 shrinkage & Dropout
04 · L1 / L2 Shrinkage
In inverted dropout, activations are masked independently with probability p and
scaled by 1/(1 − p) during train(), so eval() uses the
raw activations unchanged. Dropout does not guarantee better generalization, and excessive
p causes underfitting.
05 · Dropout Mask Player
Early stopping · select checkpoint on validation
Patience tolerates short-term validation fluctuations. Once patience triggers, stop training and restore the best saved state—remembering that validation sets also have statistical variance, so repeated selection makes validation metrics optimistic.
06 · Early Stopping on an Illustrative Loss Trace
Data leakage & distribution shift
Near-zero validation error when a model sees future state features does not reflect real prediction quality. Fix leakage by removing leaked features, re-training, and rebuilding a split matching the real collection pipeline.
07 · Leakage & Shift Simulator
Model debugging · controlled fault injection
Tiny-batch overfit proves the training path works on those few samples, not that labels or data across the dataset are bug-free. Change one factor at a time and log seeds, configs, and metrics.
08 · Live MLP Fault Injection
| Failure signature | Diagnostic meaning |
|---|---|
| Flat loss with non-zero gradients | Check optimizer.step() and whether parameters were passed to the optimizer. |
| Zero gradients in first layer | Check accidental .detach() or torch.no_grad() in the forward path. |
| Erratic / exploding step sizes | Check excessive learning rate or missing optimizer.zero_grad(). |
| Training loss drops on wrong labels | Misaligned labels can still be memorized—inspect raw (input, target) pairs. |
Complete PyTorch scripts · Fault Injection & Early Stopping
import math
import torch
from torch import nn
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
def data(n, offset=0):
i = torch.arange(offset + 1, offset + n + 1, dtype=torch.float64)
x = torch.stack([1.7 * torch.sin(i * 1.71), torch.cos(i * 2.13)], dim=1)
y = 0.65 * x[:, 0] + 0.5 * torch.sin(2 * x[:, 0]) + 0.35 * x[:, 1]
return x, y[:, None]
def new_model():
m = nn.Sequential(nn.Linear(2, 12), nn.Tanh(), nn.Linear(12, 1))
with torch.no_grad():
for j in range(12):
for k in range(2):
m[0].weight[j, k] = 0.45 * math.sin(1.37 * (k * 12 + j + 1))
m[2].weight[0, j] = 0.3 * math.cos(1.91 * (j + 1))
m[0].bias.zero_()
m[2].bias.zero_()
return m
def run(fault="clean", n=8, lr=0.08, epochs=120):
X, Y = data(n)
V, T = data(32, 100)
model = new_model()
opt = torch.optim.SGD(model.parameters(), lr=lr if fault != "lr" else 8 * lr)
train_y = Y.roll(-1, 0) if fault == "labels" else Y
hist = []
for epoch in range(epochs + 1):
model.eval()
with torch.no_grad():
tr = nn.functional.mse_loss(model(X), Y).item()
va = nn.functional.mse_loss(model(V), T).item()
hist.append((tr, va))
if not math.isfinite(tr) or tr > 1e12 or epoch == epochs:
break
model.train()
if fault != "accum":
opt.zero_grad(set_to_none=True)
a = model[1](model[0](X))
if fault == "detach":
a = a.detach()
loss = nn.functional.mse_loss(model[2](a), train_y)
loss.backward()
if fault != "frozen":
opt.step()
return hist
for fault in ["clean", "frozen", "detach", "labels", "lr", "accum"]:
h = run(fault)
print(fault, len(h) - 1, h[0], h[-1])
# Standalone early-stopping pattern (call with your own model and loaders).
import copy
import torch
def fit(model, train_loader, val_loader, optimizer, criterion, epochs=200, patience=10):
best = float("inf")
state = None
stale = 0
for epoch in range(epochs):
model.train()
for x, y in train_loader:
optimizer.zero_grad(set_to_none=True)
loss = criterion(model(x), y)
loss.backward()
optimizer.step()
model.eval()
total = count = 0
with torch.no_grad():
for x, y in val_loader:
total += criterion(model(x), y).item() * len(x)
count += len(x)
if not count:
raise ValueError("Empty validation set")
val = total / count
if val < best:
best = val
state = copy.deepcopy(model.state_dict())
stale = 0
else:
stale += 1
if stale >= patience:
break
if state is None:
raise RuntimeError("No valid checkpoint")
model.load_state_dict(state)
model.eval()
return best