Lab: Evolving a Model That Generalizes
This lab is where Chapters 2 and 3 meet. It mirrors the shape of the classic MDL genetic-algorithm assignment. You are given an overfit weight vector for a degree-10 polynomial regressor (11 weights) and a black-box server: send it any weight vector and it returns the training and validation MSE. You never see the data. Your job is to evolve weights that do well on a hidden test set.
Bolt's delivery-time predictor was fitted to only 25 logged deliveries with a degree-10 polynomial. It is overfit: training MSE 1.99 but validation MSE 6.79. The data now lives on a server, and each query takes time. Make the predictor generalize.
Step 1: think before you code
Answer these design questions on paper first. Your report will be graded on them as much as on your final numbers.
| Decision | Options | What we'll use, and why |
|---|---|---|
| Representation | 11 real numbers; or binary-encoded | Real vector. Weights are continuous, and binary encoding would make a small change in a weight look like a big change in bits. |
| Fitness | −train; −val; −(train+val); add a gap penalty | −(train + val + |train − val|). Low error on both, plus a penalty on the gap, which is the signature of overfitting (§2.2). |
| Initial population | Random; mutants of the overfit vector | Mutants of the overfit vector. It's already a decent fit. Random 11-D vectors would mostly be absurd and waste queries. |
| Selection | Roulette; tournament; truncation | Truncation: the top half breeds. Fitness is negative, so roulette won't work directly. |
| Crossover | One-point; uniform; blend | Blend (\(\alpha a + (1-\alpha)b\)). Polynomial weights are strongly coupled, so mixing whole vectors keeps them consistent. |
| Mutation | Gaussian with fixed σ; shrinking σ | Gaussian with shrinking σ: big exploratory jumps early, fine-tuning later, as in annealing (§3.2). |
| Elitism | 0–few | 4 elites, so the best is never lost. |
The overfit vector's high-order weights are huge (hundreds to a thousand) and of alternating sign, carefully cancelling each other inside [−1, 1]. Change one of them by 20% and the cancellation breaks, so predictions explode. This is a textbook ridge (§3.1): good solutions lie along narrow diagonal directions in weight space, and single-gene moves fall off the ridge. Two things help: small additive mutations, and blend crossover, which moves along the line between two good vectors and so stays near the ridge.
Step 2: the code
The block between the dashed lines simulates the server, so you can run everything locally. In the real assignment you'd replace get_errors with the provided API call. Everything else carries over.
import numpy as np
# ---------------- the "server" (in the assignment this lives on a remote machine) --------------
_rng = np.random.default_rng(3)
def _true(z): # z = distance rescaled to [-1, 1]
return 14 + 8 * z + 3 * np.sin(3.5 * z)
def _sample(n):
z = _rng.uniform(-1, 1, n)
return z, _true(z) + _rng.normal(0, 2.0, n)
_ztr, _ytr = _sample(25) # training set (hidden from you)
_zva, _yva = _sample(25) # validation set (hidden from you)
_zte, _yte = _sample(5000) # the grader's secret test set
def _mse(w, z, y):
return float(np.mean((np.polyval(w[::-1], z) - y) ** 2))
QUERIES = 0
def get_errors(w):
"""Black box: send 11 weights, receive [train MSE, validation MSE]."""
global QUERIES
QUERIES += 1
return [_mse(w, _ztr, _ytr), _mse(w, _zva, _yva)]
# the overfit vector you're handed: an unregularized degree-10 fit to the training set
OVERFIT = np.linalg.lstsq(np.vander(_ztr, 11, increasing=True), _ytr, rcond=None)[0]
# -----------------------------------------------------------------------------------------------
rng = np.random.default_rng(0)
print("overfit vector: train=%.2f val=%.2f" % tuple(get_errors(OVERFIT)))
def fitness(w):
tr, va = get_errors(w)
return -(tr + va + abs(tr - va)) # higher is better; low errors AND a small gap
def crossover(a, b):
alpha = rng.random() # blend (arithmetic) crossover for real genes
return alpha * a + (1 - alpha) * b
def mutate(w, sigma, pm=0.3):
mask = rng.random(w.size) < pm # each gene mutates with probability pm
return w + mask * rng.normal(0, sigma, w.size)
POP, GENS, ELITE = 30, 150, 4
pop = [OVERFIT.copy()] + [mutate(OVERFIT, 1.0, pm=1.0) for _ in range(POP - 1)]
for gen in range(GENS):
sigma = 2.0 * 0.97 ** gen + 0.05 # big jumps early, fine-tuning late ("cooling")
fits = np.array([fitness(w) for w in pop])
order = np.argsort(-fits)
pop = [pop[i] for i in order]
if gen % 30 == 0:
print("gen %3d: best train=%.2f val=%.2f (sigma=%.2f)" % ((gen, *get_errors(pop[0]), sigma)))
parents = pop[:POP // 2] # truncation selection: the top half may breed
children = []
while len(children) < POP - ELITE:
i, j = rng.choice(len(parents), 2, replace=False)
children.append(mutate(crossover(parents[i], parents[j]), sigma))
pop = pop[:ELITE] + children # elitism: the best 4 survive unchanged
best = pop[0]
print("final: train=%.2f val=%.2f queries used: %d" % (*get_errors(best), QUERIES))
print("hidden TEST MSE overfit vector: %.2f" % _mse(OVERFIT, _zte, _yte))
print("hidden TEST MSE GA result : %.2f" % _mse(best, _zte, _yte))overfit vector: train=1.99 val=6.79
gen 0: best train=3.18 val=5.98 (sigma=2.05)
gen 30: best train=3.79 val=4.00 (sigma=0.85)
gen 60: best train=3.92 val=3.93 (sigma=0.37)
gen 90: best train=3.89 val=3.90 (sigma=0.18)
gen 120: best train=3.88 val=3.88 (sigma=0.10)
final: train=3.86 val=3.86 queries used: 4507
hidden TEST MSE overfit vector: 7.34
hidden TEST MSE GA result : 5.22
Step 3: read the results like a scientist
- Training error went up (1.99 → 3.86), and that is the point. The GA traded training fit for generalization. The noise floor is \(\sigma^2 = 4\), so a training MSE of 1.99 was too good to be true: the model had memorized noise.
- The gap closed (1.99 vs 6.79 → 3.86 vs 3.86). This is exactly what the \(|\text{train}-\text{val}|\) term in the fitness asked for.
- Hidden test error fell from 7.34 to 5.22, a 29% improvement on data the GA never touched.
- But test (5.22) is worse than validation (3.86). Why? We optimized against the validation set for 4,500 queries. It has become part of the training signal, and the GA has started to overfit it. This is §2.4's warning in action: any data you use to make decisions stops being an honest estimate. The grader's separate test set is the only honest judge.
- The shrinking σ is a cooling schedule, borrowed straight from simulated annealing.
- The fitness function's gap penalty is a hand-made regularizer (§2.4). An alternative is to penalize \(\lVert w \rVert^2\) inside the fitness, which is literally ridge regression solved by evolution.
- Overfitting the validation set via too many queries is the same disease as tuning on the test set. One cure is early stopping: stop when validation error stops improving meaningfully.
Step 4: what to put in your report
- Explain every design choice with a reason, as in the Step 1 table. "I used crossover" earns nothing. "I used blend crossover because the weights are coupled and need to change together" earns marks.
- Show generation traces. For a few generations, show the population, fitness, selected parents, children after crossover and children after mutation. Assignments often ask for exactly this.
- Plot best and mean fitness against generation. If the mean catches up with the best within a few generations, say so and call it premature convergence.
- Respect the query budget. Cache results in a dictionary keyed on the weight tuple, and never re-query the elites.
- Save everything to disk (JSON) after each generation. Servers go down and laptops sleep.
- Clip weights to the allowed range if there is one (e.g. [−10, 10]).
- Don't submit the vector with the lowest validation error blindly. Prefer one with low and balanced train/val errors. A vector with train 3.9 / val 3.9 usually beats one with train 1.5 / val 3.7.
- Explain the heuristics you tried that failed, and why. That shows understanding.
Exercises
- Change the fitness to
-vaonly. What happens to the train/val gap and to the test error? - Replace blend crossover with one-point crossover. Why does it do worse here? (Think about ridges.)
- Add an \(L_2\) penalty \(\lambda \lVert w \rVert^2\) to the fitness and sweep \(\lambda\). Compare with the ridge results of §2.4.
- Halve the query budget. Which settings (population size, generations) give the best result under the budget?