Exercises
Fifteen exercises covering the whole course, from definitions to the learning types and the math map. Try each one before opening the answer. Two answers include a program that checks the result, which you can edit and run.
| # | Exercise | Practises |
|---|---|---|
| 1 | AI, ML or deep learning? | AI vs ML vs DL |
| 2 | Task, performance, experience | What Is ML? |
| 3 | Learned or chosen? | Models, Parameters and Loss |
| 4 | Fit a line by hand | Models, Parameters and Loss |
| 5 | Count the parameters | What Is Deep Learning? |
| 6 | Rules or learning? | Traditional Programming vs ML |
| 7 | A model that was fine yesterday | The ML Lifecycle |
| 8 | Where does the compute go? | Training vs Inference |
| 9 | Name the learning type | Choosing a Learning Type |
| 10 | k-means by hand | Unsupervised Learning |
| 11 | One bandit, four pulls | Reinforcement Learning |
| 12 | One Q-learning update | Reinforcement Learning |
| 13 | Which example to label next? | Active Learning |
| 14 | Spot the leak | Ten Principles |
| 15 | How precise is the score? | The Math You Need |
Exercise 1: AI, ML or deep learning?
For each system, give the narrowest correct label (deep learning, machine learning but not deep learning, or AI without learning): (a) a sudoku solver using backtracking search, (b) a gradient-boosted model predicting loan defaults from 40 columns, (c) a convolutional network detecting pedestrians in camera images, (d) a thermostat schedule written by the user, (e) a chatbot built on a large language model.
Answer
(a) AI without learning (search). (b) Machine learning, not deep learning. (c) Deep learning. (d) Not really AI at all: a fixed schedule, no reasoning or learning. (e) Deep learning (a transformer network), used through prompting.
Exercise 2: Task, performance, experience
A factory wants to predict which machines will fail within the next 7 days, from vibration and temperature sensors. State , and , and name one way the performance measure could mislead.
Answer
: for each machine each day, predict "fails within 7 days" or not. : for example recall of failures (share caught in time) together with precision (share of alarms that were real). : historical sensor readings labelled with whether a failure followed within 7 days. Plain accuracy would mislead: failures are rare, so "never fails" scores very high while catching nothing.
Exercise 3: Learned or chosen?
After model = RandomForestClassifier(n_estimators=200, max_depth=8, random_state=0).fit(X, y), which of these are parameters (learned by fit) and which are hyperparameters: n_estimators, max_depth, the split thresholds inside each tree, the feature used at each split, random_state, model.classes_?
Answer
Hyperparameters (chosen before training): n_estimators, max_depth, and random_state (a setting for reproducibility). Learned by fit: the split thresholds, the feature at each split, and model.classes_ (read from the labels; note the trailing underscore).
Exercise 4: Fit a line by hand
Find the least-squares line through , , , and its mean squared error. Use and .
Answer
, . The numerator is ; the denominator is . So and . Predictions 1.2, 2.9, 4.6, 6.3; errors ; MSE .
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0])
y = np.array([1.0, 3.0, 5.0, 6.0])
w, b = np.polyfit(x, y, 1) # least-squares line
pred = w * x + b
print("w =", round(w, 3), " b =", round(b, 3))
print("predictions:", pred.round(2))
print("MSE:", round(np.mean((pred - y) ** 2), 4))w = 1.7 b = 1.2
predictions: [1.2 2.9 4.6 6.3]
MSE: 0.075
Exercise 5: Count the parameters
A fully connected network classifies grey-scale images into 10 classes with layer sizes 784, 128, 64, 10. How many parameters does it have? Which layer holds most of them?
Answer
; ; . Total . The first layer holds about 92 % of them, because it connects every pixel to every hidden neuron. Convolutional networks share weights across the image to avoid exactly this.
Exercise 6: Rules or learning?
For a ride-hailing app, decide for each component whether you would write rules or train a model: (a) the fare formula from distance and time, (b) the estimated time of arrival, (c) blocking accounts on a government sanctions list, (d) detecting fake driver-licence photos.
Answer
(a) rules: the pricing formula is a business decision. (b) a model: arrival time depends on traffic patterns learned from past trips. (c) rules: an exact list lookup, legally required to be deterministic. (d) a model (deep learning on images), with human review of flagged cases.
Exercise 7: A model that was fine yesterday
A demand-forecasting model had a mean absolute error of 12 units in testing and in its first month. Since Monday it is 45 units. The code has not changed. List three things to check, in order, and say which lifecycle stage each belongs to.
Answer
- Monitoring / data: did the inputs change? A broken feed, a new unit (boxes instead of items), missing values filled with zeros, a new store. Compare this week's input distributions with the training data.
- Deployment: was anything redeployed around the model (a library upgrade, a different preprocessing step)? Check for train/serve skew.
- Concept drift: did the world change (a promotion, a holiday, a competitor closing)? If so, collect recent labelled data and retrain, which sends you back to the data and training stages.
Exercise 8: Where does the compute go?
Training a model takes 6 hours on one GPU, once a month. In service it answers 20 requests per second, 24 hours a day, each needing 10 ms on the same kind of GPU. Per 30-day month, which phase uses more GPU time, and by how much?
Answer
Inference: GPU-seconds per second; a 30-day month has seconds, so GPU-seconds = 144 hours. Training: 6 hours. Inference uses 24 times as much.
Exercise 9: Name the learning type
(a) Grouping 10,000 songs by sound without any genre tags. (b) Training a model on 300 labelled and 50,000 unlabelled product photos. (c) An agent that learns to schedule lifts in a building by trial and error in a simulator. (d) Pretraining on all of a company's unlabelled emails by predicting masked words. (e) A spam filter updated every few minutes with users' "report spam" clicks. (f) A model that chooses which 500 of 100,000 contracts a lawyer should label.
Answer
(a) unsupervised (clustering); (b) semi-supervised; (c) reinforcement; (d) self-supervised; (e) supervised, trained online; (f) active learning.
Exercise 10: k-means by hand
Run k-means with on the one-dimensional points 1, 2, 3, 10, 11, 12, starting from centroids 1 and 2. Write down the clusters and centroids after each iteration.
Answer
Iteration 1: point 1 is nearest to centroid 1; all other points are nearer to centroid 2. New centroids: 1 and . Iteration 2: 1, 2 and 3 are nearer to 1 than to 7.6; 10, 11, 12 to 7.6. New centroids 2 and 11. Iteration 3: no point changes cluster, so the algorithm stops with clusters and .
import numpy as np
x = np.array([1.0, 2.0, 3.0, 10.0, 11.0, 12.0])
centroids = np.array([1.0, 2.0])
for it in range(1, 10):
labels = np.abs(x[:, None] - centroids[None, :]).argmin(axis=1) # assign
new = np.array([x[labels == j].mean() for j in range(2)]) # update
print(f"iteration {it}: clusters {labels}, centroids {new}")
if np.allclose(new, centroids):
break
centroids = newiteration 1: clusters [0 1 1 1 1 1], centroids [1. 7.6]
iteration 2: clusters [0 0 0 1 1 1], centroids [ 2. 11.]
iteration 3: clusters [0 0 0 1 1 1], centroids [ 2. 11.]
Exercise 11: One bandit, four pulls
An arm of a bandit gives rewards 1, 0, 1, 1 on its first four pulls. Using the update from , compute after each pull.
Answer
: . : . : . : . This is exactly the running average .
Exercise 12: One Q-learning update
The agent is in state , takes action with , receives reward and lands in where the best action value is . With and , what is the new ?
Answer
.
Exercise 13: Which example to label next?
A binary classifier gives these probabilities of class 1 for four unlabelled examples: A 0.97, B 0.52, C 0.10, D 0.35. In which order does uncertainty sampling ask for labels? Why might a good labelling plan still include some examples like A?
Answer
By distance from 0.5: B (0.02), D (0.15), C (0.40), A (0.47). So B, D, C, A. Confident examples are not useless: if the model is confidently wrong about some of them, only labelling a few at random will reveal it. A random share of labels also gives an unbiased test set.
Exercise 14: Spot the leak
scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2)
model = LogisticRegression().fit(X_train, y_train)
print(model.score(X_test, y_test))What leaks, how serious is it, and how do you fix it?
Answer
The scaler is fitted on all rows, so the means and standard deviations include the test rows. The effect for a scaler is usually small, but it is still leakage, and the same pattern with feature selection or target encoding can inflate scores enormously (as in principle 4). Fix: split first, then fit the scaler on the training rows only, most simply with make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train).
Exercise 15: How precise is the score?
A model is right on 340 of 400 test examples. Compute its accuracy and an approximate 95 % confidence interval. Could its true accuracy be 0.80?
Answer
. Standard error . Interval . A true accuracy of 0.80 lies outside the interval, so it is unlikely but not impossible; 0.82 would be entirely plausible.
Test yourself
A network has layer sizes 784, 128, 64, 10. How many parameters does it have?
- 109,386
- 100,480
- 8,256
- 1,000
Which learning type fits a model trained on 300 labelled and 50,000 unlabelled photos?
- Unsupervised
- Semi-supervised
- Reinforcement
- Batch only
With , , , and , what is the updated ?
- -0.5
- 1.75
- 3.5
- 4.5