Chapter 18 — Assignment Project: The Right Network for the Data
Overview¶
A small engineering firm has two problems and asks you which kind of neural network to use for each:
Images. Reading handwritten digits that are not always centred (the post office from Chapter 15).
A time series. Forecasting a city’s electricity demand one hour ahead, so that power stations can be started in time.
You will build and compare architectures on both, look inside an attention model, and write a recommendation backed by your numbers.
| Part | Task | Points |
|---|---|---|
| A | Images: MLP against CNN, with augmentation | 30 |
| B | Time series: baselines, MLP, LSTM | 30 |
| C | Attention: does the model look at the right place? | 20 |
| D | Recommendation report | 20 |
Rules
Use
42(or the seeds given) wherever randomness appears.Make every choice on validation data; use each test set only for the final numbers.
Cells marked checked have an automatic check under them; the other parts are graded with the rubric at the end.
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
def check(name, test):
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 n_params(model):
return sum(p.numel() for p in model.parameters())Part A — Images (30 points)¶
The digits, scaled to 0–1, with helpers to train a classifier and to shift images (from Chapter 15).
digits = load_digits()
X_tr, X_te, y_tr, y_te = train_test_split(digits.images / 16.0, digits.target, test_size=0.25, stratify=digits.target, random_state=42)
to_t = lambda A: torch.tensor(A, dtype=torch.float32).unsqueeze(1) # (N, 8, 8) -> (N, 1, 8, 8)
def train_classifier(model, X, y, epochs=40, lr=1e-3, seed=42):
torch.manual_seed(seed)
opt = torch.optim.Adam(model.parameters(), lr=lr)
loader = DataLoader(TensorDataset(to_t(X), torch.tensor(y)), batch_size=64, shuffle=True)
for _ in range(epochs):
model.train()
for xb, yb in loader:
loss = F.cross_entropy(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
return model
def accuracy(model, X, y):
with torch.no_grad():
return (model(to_t(X)).argmax(1).numpy() == y).mean()
def shift_images(X, dx, dy):
out = np.zeros_like(X)
out[:, max(0, dy):8 - max(0, -dy), max(0, dx):8 - max(0, -dx)] = X[:, max(0, -dy):8 - max(0, dy), max(0, -dx):8 - max(0, dx)]
return out
DIRECTIONS = [(dx, dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) if (dx, dy) != (0, 0)]
def shifted_accuracy(model, X, y):
return np.mean([accuracy(model, shift_images(X, dx, dy), y) for dx, dy in DIRECTIONS])A1 (checked). Complete make_cnn(channels). For each number c in channels, add a block Conv2d(previous, c, 3, padding=1), ReLU, MaxPool2d(2) (the first block has 1 input channel). Each block halves the 8×8 image. Then Flatten and a Linear layer to 10 outputs: work out its input size from the last number of channels and the final image size.
def make_cnn(channels=(16, 32)):
raise NotImplementedError # TODOcheck('A1: channels (16, 32) give 6,090 parameters', lambda: n_params(make_cnn((16, 32))) == 6090)
check('A1: channels (8, 16, 32) give 10 scores', lambda: make_cnn((8, 16, 32))(torch.zeros(3, 1, 8, 8)).shape == (3, 10))A2. Train an MLP (nn.Flatten(), a hidden layer of 128 ReLU units, 10 outputs) and make_cnn((16, 32)) with train_classifier. Show a table: parameters, test accuracy, and test accuracy on digits shifted by one pixel (shifted_accuracy).
# TODOA3. Augment the training set with a one-pixel shift of every digit in each of the 8 directions (9 times the data), and train both models again. Add the two augmented models to your table.
# TODOA4. In three or four sentences: what does the CNN gain from its structure, and what does augmentation add?
Your answer:
Part B — Forecasting Electricity Demand (30 points)¶
Twenty weeks of hourly demand (in megawatts) for a hypothetical city, simulated with a daily pattern (a morning and an evening peak), quieter weekends, air-conditioning on hot afternoons, a slowly drifting level and correlated noise. Task: predict the next hour’s demand from the last 48 hours.
def make_demand(seed=42, weeks=20):
rng = np.random.default_rng(seed)
hours = np.arange(24 * 7 * weeks)
hod, dow = hours % 24, (hours // 24) % 7
daily = 15 * np.exp(-((hod - 19) ** 2) / 8) + 10 * np.exp(-((hod - 8) ** 2) / 6)
weekend = np.where(dow >= 5, -12, 0)
level = 100 + np.cumsum(rng.normal(0, 0.3, len(hours)))
temperature = 25 + 8 * np.sin(2 * np.pi * (hod - 9) / 24) + np.repeat(rng.normal(0, 3, len(hours) // 24), 24)
noise = np.zeros(len(hours))
for t in range(1, len(hours)):
noise[t] = 0.7 * noise[t - 1] + rng.normal(0, 2)
return level + daily + weekend + 1.2 * np.maximum(0, temperature - 28) + noise
demand = make_demand()
plt.figure(figsize=(11, 2.8)); plt.plot(demand[:24 * 14]); plt.xlabel('hour'); plt.ylabel('MW'); plt.title('The first two weeks'); plt.show()B1 (checked). Complete make_windows(series, W): row i of X holds series[i : i + W] and y[i] is series[i + W], for every i where that exists.
def make_windows(series, W):
raise NotImplementedError # TODOcheck('B1: a toy series', lambda: (lambda X, y: X.tolist() == [[0, 1, 2], [1, 2, 3]] and y.tolist() == [3, 4])(*make_windows(np.arange(5), 3)))
W = 48
Xw, yw = make_windows(demand, W)
n = len(Xw); a, b = int(0.7 * n), int(0.85 * n) # time order: train, then validation, then test
Xw_tr, yw_tr, Xw_va, yw_va, Xw_te, yw_te = Xw[:a], yw[:a], Xw[a:b], yw[a:b], Xw[b:], yw[b:]
print(f'{len(Xw_tr)} training, {len(Xw_va)} validation, {len(Xw_te)} test windows')B2 (checked). Two baselines, as mean absolute errors (MAE) on given windows: persistence_mae predicts the last value of each window; seasonal_mae predicts the value 24 hours before the target. Why must the data be split in time order, and not shuffled?
def persistence_mae(X, y):
raise NotImplementedError # TODO
def seasonal_mae(X, y):
raise NotImplementedError # TODO_Xs, _ys = make_windows(np.arange(60.0), 48)
check('B2: persistence on a straight line is 1', lambda: np.isclose(persistence_mae(_Xs, _ys), 1.0))
check('B2: same hour yesterday on a straight line is 24', lambda: np.isclose(seasonal_mae(_Xs, _ys), 24.0))Why the time order:
B3. Train and compare on the validation set: ridge regression on the 48 values, an MLP, and an LSTM that reads the 48 values as a sequence (one number per step) and predicts from its last hidden state. Standardise with the training mean and standard deviation. Use the fit_regressor helper below, which keeps the epoch with the best validation MAE. Then report the test MAE of every model, baselines included, in one table.
mu, sd = Xw_tr.mean(), Xw_tr.std()
scale = lambda A: torch.tensor((A - mu) / sd, dtype=torch.float32)
def predict(model, X):
model.eval()
with torch.no_grad():
return model(scale(X)).squeeze(-1).numpy() * sd + mu
def fit_regressor(model, epochs=60, lr=1e-3, seed=42):
torch.manual_seed(seed)
opt = torch.optim.Adam(model.parameters(), lr=lr)
Xt, yt = scale(Xw_tr), scale(yw_tr)
best, best_state = np.inf, None
for _ in range(epochs):
model.train()
perm = torch.randperm(len(Xt))
for k in range(0, len(perm), 64):
idx = perm[k:k + 64]
loss = F.mse_loss(model(Xt[idx]).squeeze(-1), yt[idx])
opt.zero_grad(); loss.backward(); opt.step()
val = np.mean(np.abs(predict(model, Xw_va) - yw_va))
if val < best:
best, best_state = val, {k: v.clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
return model, best
# TODO: the LSTM class, the three models, and the tableB4. Plot one week of the test period: the true demand and the predictions of your best model and of persistence.
# TODOPart C — Where Does Attention Look? (20 points)¶
A sequence of 50 steps has two channels: a value (random noise) and a marker (0 everywhere, except 1 at one random position). At the marked position the value is +2 or -2, and the label is its sign. The position changes from sequence to sequence, so a model cannot just learn “look at position 7”: it has to find the marker.
C1 (checked). Complete make_marked(n, T, seed), returning X (a float tensor of shape (n, T, 2)), y (int64 labels 0/1) and pos (the marked positions, a NumPy array). Use rng = np.random.default_rng(seed); draw the values with rng.normal(0, 1, (n, T)), the positions with rng.integers(0, T, n), the labels with rng.random(n) > 0.5; put +2 (label 1) or -2 (label 0) at each marked position.
def make_marked(n, T, seed):
raise NotImplementedError # TODOdef _marked_ok():
X, y, pos = make_marked(100, 20, 0)
one_marker = (X[:, :, 1].sum(1) == 1).all().item() and (X[np.arange(100), pos, 1] == 1).all().item()
signs = ((X[np.arange(100), pos, 0] > 0).long() == y).all().item()
return X.shape == (100, 20, 2) and X.dtype == torch.float32 and y.dtype == torch.int64 and one_marker and signs
check('C1: shapes, one marker per sequence, labels match the signs', _marked_ok)C2. The attention classifier below embeds each step, scores every step against one learned query, and classifies the attention-weighted sum. Train it on 3000 sequences (seed 0) for 10 epochs with Adam (learning rate 0.003, batches of 64), and report the accuracy on 500 test sequences (seed 1).
class AttentionClassifier(nn.Module):
def __init__(self, d_in=2, d=32):
super().__init__()
self.embed = nn.Linear(d_in, d)
self.query = nn.Parameter(torch.randn(d) / math.sqrt(d))
self.key = nn.Linear(d, d)
self.value = nn.Linear(d, d)
self.out = nn.Linear(d, 2)
def forward(self, x, return_weights=False):
h = torch.relu(self.embed(x))
weights = torch.softmax(self.key(h) @ self.query / math.sqrt(h.shape[-1]), dim=1)
logits = self.out((weights.unsqueeze(-1) * self.value(h)).sum(1))
return (logits, weights) if return_weights else logits
# TODOC3. For three test sequences, plot the attention weights over the 50 positions and mark the true marked position. Does the model look at the right place? Is attention strictly necessary for this task? (Hint: each step is embedded separately, through a ReLU, before any pooling. Could a plain average of the embeddings also single out the marked step?)
# TODOYour answer:
Part D — Recommendation Report (20 points)¶
Write 300–400 words for the firm:
Images: which architecture, and why (parameters, accuracy, robustness to shifts, the role of augmentation).
Electricity: which model, and why. Is the most complex model worth it? Quote your MAEs against the baselines.
Attention: what your Part C experiment shows, and where attention-based models (Transformers) would be the right choice.
General rule: how to choose an architecture for a new kind of data.
Your report:
Grading Rubric¶
| Part | Full marks if… |
|---|---|
| A (30) | make_cnn correct (checked); a fair comparison table with and without augmentation; a clear explanation |
| B (30) | windows and baselines correct (checked); three models compared on validation, test used once; a readable forecast plot; the time-order question answered |
| C (20) | the data generator correct (checked); the model trained and its attention plotted; an honest answer on whether attention is needed |
| D (20) | all four sections; numbers that match the notebook; sound, practical advice |