Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 18 — Assignment Project: The Right Network for the Data

Open in Colab

Overview

A small engineering firm has two problems and asks you which kind of neural network to use for each:

  1. Images. Reading handwritten digits that are not always centred (the post office from Chapter 15).

  2. 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.

PartTaskPoints
AImages: MLP against CNN, with augmentation30
BTime series: baselines, MLP, LSTM30
CAttention: does the model look at the right place?20
DRecommendation report20

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.


Part A — Images (30 points)

The digits, scaled to 0–1, with helpers to train a classifier and to shift images (from Chapter 15).

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.

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).

A3. 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.

A4. 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.

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.

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?

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.

B4. Plot one week of the test period: the true demand and the predictions of your best model and of persistence.


Part 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.

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).

C3. 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?)

Your answer:


Part D — Recommendation Report (20 points)

Write 300–400 words for the firm:

  1. Images: which architecture, and why (parameters, accuracy, robustness to shifts, the role of augmentation).

  2. Electricity: which model, and why. Is the most complex model worth it? Quote your MAEs against the baselines.

  3. Attention: what your Part C experiment shows, and where attention-based models (Transformers) would be the right choice.

  4. General rule: how to choose an architecture for a new kind of data.

Your report:


Grading Rubric

PartFull 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