Chapter 9 — Lab: Parameters, Hyperparameters and Model Fit
Lab Overview¶
You will fit models of growing capacity, watch them underfit and overfit, tame them with a penalty, and write your own hyperparameter search.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Polynomial regression by least squares | 15 |
| 2 | Choosing the degree on validation data | 15 |
| 3 | Ridge regression in closed form | 20 |
| 4 | Diagnosing a fit | 15 |
| 5 | Grid search | 15 |
| 6 | Random search | 20 |
| Challenge | Measuring bias and variance | +10 |
How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Use NumPy and plain Python. Do not change the check cells.
import itertools
import numpy as np
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
def sample(n, seed):
"""n points of y = sin(pi x) + noise (sd 0.25), x uniform on [-1, 1] (the chapter's data)."""
rng = np.random.default_rng(seed)
x = rng.uniform(-1, 1, n)
return x, np.sin(np.pi * x) + rng.normal(0, 0.25, n)
print('Setup complete.')Exercise 1: Polynomial Regression (15 points)¶
design(x, d)returns the matrix with columns (shape(len(x), d + 1)).fit_poly(x, y, d)returns the least-squares weights ; usenp.linalg.lstsq(A, y, rcond=None)[0].predict_poly(w, x)returns .mse(y, y_hat)returns the mean squared error.
def design(x, d):
# TODO
raise NotImplementedError
def fit_poly(x, y, d):
# TODO
raise NotImplementedError
def predict_poly(w, x):
# TODO
raise NotImplementedError
def mse(y, y_hat):
# TODO
raise NotImplementedErrorcheck('design', lambda: np.allclose(design([2, 3], 2), [[1, 2, 4], [1, 3, 9]]))
check('a line through (0, 1), (1, 3), (2, 5)', lambda: np.allclose(fit_poly([0, 1, 2], [1, 3, 5], 1), [1, 2]))
check('predict', lambda: np.allclose(predict_poly(np.array([1., 0, 2]), [0, 1, 2]), [1, 3, 9]))
check('mse', lambda: abs(mse([1, 2, 3], [1, 2, 5]) - 4 / 3) < 1e-12)Exercise 2: Choosing the Degree (15 points)¶
best_degree(x_tr, y_tr, x_va, y_va, degrees) fits a polynomial of each degree on the training data, measures its MSE on the validation data, and returns (best degree, list of validation errors). On a tie, keep the smaller degree.
def best_degree(x_tr, y_tr, x_va, y_va, degrees):
# TODO
raise NotImplementedErrorx_tr, y_tr = sample(20, 0); x_va, y_va = sample(500, 1)
d, errs = best_degree(x_tr, y_tr, x_va, y_va, [1, 3, 5, 9, 15])
check('a moderate degree wins', lambda: d in (3, 5))
check('degree 1 underfits: its validation MSE is above 0.25', lambda: errs[0] > 0.25)
check('degree 15 overfits: its validation MSE is the worst', lambda: errs[-1] == max(errs))Question. Print the training MSE for the same degrees. What happens to it, and why can it never be used to choose the degree?
Exercise 3: Ridge Regression (20 points)¶
fit_ridge(x, y, d, lam) returns the ridge weights for a polynomial of degree d:
where = design(x, d) and is the identity matrix with a 0 in its top-left corner, so that the intercept is not penalised. Use np.linalg.solve.
def fit_ridge(x, y, d, lam):
# TODO
raise NotImplementedErrorcheck('lambda = 0 is least squares', lambda: np.allclose(fit_ridge([0, 1, 2, 3], [1, 3, 5, 7.5], 1, 0), fit_poly([0, 1, 2, 3], [1, 3, 5, 7.5], 1)))
check('a huge lambda leaves only the intercept: the mean', lambda: np.allclose(fit_ridge([0, 1, 2, 3], [1, 3, 5, 7], 2, 1e9), [4, 0, 0], atol=1e-4))
w_small = fit_ridge(x_tr, y_tr, 12, 1e-3); w_none = fit_poly(x_tr, y_tr, 12)
check('the penalty shrinks the weights', lambda: np.abs(w_small[1:]).sum() < np.abs(w_none[1:]).sum())
check('and lowers the validation error of degree 12', lambda: mse(y_va, predict_poly(w_small, x_va)) < mse(y_va, predict_poly(w_none, x_va)))Exercise 4: Diagnosing a Fit (15 points)¶
diagnose(train_err, val_err, target, gap) returns:
'underfitting'if the training error is abovetarget(the model cannot even fit what it has seen);otherwise
'overfitting'if the validation error exceeds the training error by more thangap;otherwise
'good'.
def diagnose(train_err, val_err, target, gap):
# TODO
raise NotImplementedErrorcheck('high training error', lambda: diagnose(0.24, 0.25, 0.10, 0.05) == 'underfitting')
check('a large gap', lambda: diagnose(0.02, 0.25, 0.10, 0.05) == 'overfitting')
check('close and low', lambda: diagnose(0.06, 0.08, 0.10, 0.05) == 'good')
check('underfitting is checked first', lambda: diagnose(0.30, 0.90, 0.10, 0.05) == 'underfitting')Exercise 5: Grid Search (15 points)¶
grid_search(score, grid) tries every combination of the values in the dictionary grid (use itertools.product over the values, keys in the dictionary’s order), calls score(params) on each params dictionary (higher is better), and returns (best params, best score). On a tie, keep the first combination tried.
def grid_search(score, grid):
# TODO
raise NotImplementedErrortoy = lambda p: -(p['a'] - 2) ** 2 - (p['b'] - 0.1) ** 2
check('the best combination', lambda: grid_search(toy, {'a': [1, 2, 3], 'b': [0.01, 0.1, 1]}) == ({'a': 2, 'b': 0.1}, 0.0))
calls = []
grid_search(lambda p: calls.append(p) or 0, {'a': [1, 2], 'b': [3, 4, 5]})
check('6 combinations tried', lambda: len(calls) == 6)
check('ties keep the first', lambda: grid_search(lambda p: 1, {'a': [7, 8]}) == ({'a': 7}, 1))Exercise 6: Random Search (20 points)¶
random_search(score, space, n, seed) makes rng = np.random.default_rng(seed), then n times builds a params dictionary by choosing, for each key in order, space[key][rng.integers(len(space[key]))]. It returns (best params, best score), keeping the first best on a tie.
def random_search(score, space, n, seed):
# TODO
raise NotImplementedErrorspace = {'a': list(np.linspace(0, 4, 41)), 'b': [0.001, 0.01, 0.1, 1, 10]}
check('the same seed gives the same answer', lambda: random_search(toy, space, 20, 0) == random_search(toy, space, 20, 0))
check('n calls', lambda: (lambda c: (random_search(lambda p: c.append(1) or 0, space, 7, 1), len(c))[1])([]) == 7)
check('close to the best after 200 trials', lambda: random_search(toy, space, 200, 0)[1] > -0.01)Question. Only a matters much in toy. With 9 trials, a 3 × 3 grid tries 3 values of a. How many different values of a do 9 random trials try, typically? Why does this favour random search?
Challenge: Measuring Bias and Variance (+10 points)¶
bias_variance(degree, x0, n_sets, n_points) fits a polynomial of the given degree on n_sets training sets drawn with sample(n_points, 100 + s) for s = 0, 1, …, predicts at x0 with each, and returns (bias², variance) where the truth is and the variance uses np.var.
def bias_variance(degree, x0, n_sets=300, n_points=20):
# TODO
raise NotImplementedErrorb1, v1 = bias_variance(1, 0.5); b3, v3 = bias_variance(3, 0.5); b9, v9 = bias_variance(9, 0.5)
check('a line is biased', lambda: b1 > 0.2 and b3 < 0.01)
check('degree 9 has the largest variance', lambda: v9 > v3 and v9 > v1)Lab Report¶
Submit this notebook with:
every check cell showing ✅,
your answers to the two questions,
one paragraph: for a model you have used, list two parameters and two hyperparameters, and say how you would choose the hyperparameters.