Exercises
Eighteen exercises across the whole course, most of them small enough to do on paper. Try each one before opening the answer. Three answers include a program that checks the hand computation, which you can edit and run.
| # | Exercise | Practises |
|---|---|---|
| 1 | A line through four points | Linear Regression |
| 2 | How big a step? | Gradient Descent |
| 3 | Bias or variance? | Polynomial Regression |
| 4 | Ridge or lasso? | Ridge, Lasso and Elastic Net |
| 5 | One logistic prediction | Logistic Regression |
| 6 | Softmax by hand | Softmax Regression |
| 7 | Score a split | Decision Trees |
| 8 | Forest or single tree? | Bagging, Random Forests |
| 9 | One round of boosting | Gradient Boosting |
| 10 | An XGBoost leaf | XGBoost |
| 11 | Neighbours by hand | k-Nearest Neighbours |
| 12 | Which points matter to an SVM? | SVM: Margin and Hinge Loss |
| 13 | Spam or not? | Naive Bayes for Text |
| 14 | k-means and DBSCAN on a line | k-Means, DBSCAN |
| 15 | Principal components of a covariance | PCA |
| 16 | An alarm threshold | Isolation Forests |
| 17 | Pick the algorithm | Choosing an Algorithm |
| 18 | Is the new model better? | Comparison Bench |
Exercise 1: A line through four points
Fit by least squares to the points , , , using the normal equation.
Answer
With , , , , :
import numpy as np
from sklearn.linear_model import LinearRegression
x = np.array([0, 1, 2, 3])
y = np.array([1, 3, 5, 6])
X = np.column_stack([np.ones(4), x])
print("normal equation:", np.linalg.solve(X.T @ X, X.T @ y).round(3))
m = LinearRegression().fit(x[:, None], y)
print("scikit-learn: ", round(m.intercept_, 3), round(m.coef_[0], 3))normal equation: [1.2 1.7]
scikit-learn: 1.2 1.7
Exercise 2: How big a step?
A squared-error loss has Hessian eigenvalues 2 and 18 (one feature measured on a much larger scale than the other). What is the largest learning rate for which gradient descent converges, and why would standardising the features help?
Answer
. Along the direction with eigenvalue 2 such a step is small, so progress there is slow (condition number 9). Standardising brings the eigenvalues closer together, so one learning rate suits all directions.
Exercise 3: Bias or variance?
For each case, say whether the main problem is bias or variance, and one fix: (a) training MSE 0.30, validation MSE 0.31, noise variance about 0.05; (b) training MSE 0.01, validation MSE 0.40; (c) a degree-15 polynomial fitted to 20 points.
Answer
(a) Bias (underfitting): both errors are far above the noise level and close to each other. Use a more flexible model or better features. (b) Variance (overfitting): a big gap between training and validation. Regularise, simplify, or get more data. (c) Variance: 16 coefficients for 20 points; lower the degree or add a ridge penalty.
Exercise 4: Ridge or lasso?
(a) A gene-expression study has 5000 features and 80 patients; biologists expect a handful of genes to matter. (b) A sales model has 12 features, several of them strongly correlated measures of store size, all plausibly relevant. Which penalty would you try first in each case?
Answer
(a) Lasso (or elastic net): it sets most coefficients to exactly zero and selects a small set of genes; elastic net is safer if relevant genes are correlated. (b) Ridge: it keeps all features and shares the weight among the correlated ones instead of picking one arbitrarily.
Exercise 5: One logistic prediction
A logistic model has and . Compute for and , and the log-loss of the second prediction if its label is 1.
Answer
For : , , on the boundary. For : , . Log-loss .
Exercise 6: Softmax by hand
Scores for three classes. Compute the probabilities. Which class is predicted, and what happens to the probabilities if every score is multiplied by 2?
Answer
, , , sum : , class 1 predicted. Doubling gives : , , , sum , so . The prediction is the same but more confident; scaling scores acts like lowering a temperature.
Exercise 7: Score a split
A node holds 6 examples of class A and 4 of class B. A split sends 5 A and 1 B to the left, 1 A and 3 B to the right. Compute the Gini impurity decrease.
Answer
Parent: . Left: . Right: . Weighted: . Decrease: .
Exercise 8: Forest or single tree?
A single deep tree scores 0.78 on validation data with a lot of variation between random seeds; a forest of 300 such trees scores 0.86. (a) Which error component did the forest reduce? (b) Why would 3000 trees probably not reach 0.90? (c) What does the out-of-bag score give you that the training score does not?
Answer
(a) Variance: averaging decorrelated trees removes their disagreement. (b) The remaining variance is (it does not shrink with more trees) and the bias of the trees is unchanged; extra trees only remove the already small term. (c) An estimate of accuracy on unseen data: each row is predicted only by trees that did not train on it, while the training score of deep trees is close to 1 by construction.
Exercise 9: One round of boosting
Targets for three examples. Start from the mean. The first tree is a stump that puts the first two examples in one leaf and the third in the other, predicting the mean residual in each leaf. With learning rate 0.5, what are the predictions after one round?
Answer
; residuals ; leaf values (first two) and (third). . The training MSE drops from to .
Exercise 10: An XGBoost leaf
A leaf contains examples with log-loss gradients summing to and hessians summing to . Compute the leaf value with , and its contribution to the structure score .
Answer
(in log-odds; multiplied by the learning rate when added). Contribution: . A split is worth making if the children's contributions together are lower than the parent's by more than .
Exercise 11: Neighbours by hand
Training points: A, A, B, B, B. Classify with and (Euclidean distance). Then imagine the second coordinate were measured in millimetres instead of metres (multiplied by 1000): which neighbour would be nearest?
Answer
Distances: : ; : ; : 1; : ; : . : B (the point ). : B, A, B, so B. After rescaling, the second coordinate dominates: the query's second coordinate is 2000, and the nearest second coordinates are 1000 (point ) and 3000 (point ), both 1000 away; the first coordinate then breaks the tie, so wins (1000 against 1000.0005). Small differences in the first feature have become irrelevant, which is why kNN needs scaling.
Exercise 12: Which points matter to an SVM?
A linear SVM has and . Compute the margin width, and the hinge loss of: with ; with ; with . Which are support vectors?
Answer
Margin . : , hinge 0, exactly on the margin: a support vector. : , hinge 0, beyond the margin: not a support vector. with : , hinge , misclassified: a support vector with .
Exercise 13: Spam or not?
. Word probabilities: "offer" 0.10 in spam and 0.01 in ham; "meeting" 0.01 in spam and 0.05 in ham. Compute with naive Bayes.
Answer
Spam: . Ham: . . The strong spam word and the strong ham word nearly cancel.
Exercise 14: k-means and DBSCAN on a line
(a) Run k-means with on the values 1, 2, 3, 10, 11, 12, starting from centroids 1 and 2, until it stops. Give the final centroids and the inertia. (b) Run DBSCAN with and minPts on 1, 2, 3, 7, 8, 20. Which points are core, border and noise?
Answer
(a) First assignment: 1 to centroid 1; 2, 3, 10, 11, 12 to centroid 2. Update: centroids 1 and . Second assignment: 1, 2, 3 to the first (distances to 7.6 are larger), 10, 11, 12 to the second. Update: 2 and 11. Third assignment: no change, stop. Inertia .
(b) Neighbourhoods (itself included): 1: {1, 2}; 2: {1, 2, 3}; 3: {2, 3}; 7: {7, 8}; 8: {7, 8}; 20: {20}. Only 2 is a core point. 1 and 3 are border points of its cluster. 7, 8 and 20 are noise: 7 and 8 are close to each other, but two points are not dense enough for minPts .
import numpy as np
from sklearn.cluster import KMeans, DBSCAN
x = np.array([1, 2, 3, 10, 11, 12], dtype=float)[:, None]
km = KMeans(n_clusters=2, init=np.array([[1.0], [2.0]]), n_init=1).fit(x)
print("k-means centroids:", km.cluster_centers_.ravel(), " inertia:", km.inertia_, " iterations:", km.n_iter_)
pts = np.array([1, 2, 3, 7, 8, 20], dtype=float)[:, None]
db = DBSCAN(eps=1.5, min_samples=3).fit(pts)
print("DBSCAN labels:", db.labels_.tolist(), " core points:", pts[db.core_sample_indices_].ravel().tolist())k-means centroids: [ 2. 11.] inertia: 4.0 iterations: 3
DBSCAN labels: [0, 0, 0, -1, -1, -1] core points: [2.0]
Exercise 15: Principal components of a covariance
A centred data set has covariance . Find the eigenvalues, the first principal component and its explained variance. What does the result say about the data?
Answer
, so and . For : , so . It explains %: every point lies on the line , so one coordinate describes the data exactly.
import numpy as np
S = np.array([[4.0, 2.0], [2.0, 1.0]])
lam, V = np.linalg.eigh(S)
print("eigenvalues:", np.abs(lam.round(6)))
print("first component (up to sign):", np.abs(V[:, -1]).round(4), " explained share:", round(lam[-1] / lam.sum(), 3))eigenvalues: [0. 5.]
first component (up to sign): [0.8944 0.4472] explained share: 1.0
Exercise 16: An alarm threshold
An isolation forest scores 10 000 transactions a day. The fraud team can review 50 cases a day. How do you set the alarm threshold, and which metric tells you whether the detector is useful?
Answer
Flag the 50 highest scores each day (a threshold at the 99.5th percentile of the scores), not a threshold from contamination guessed in advance. Judge the detector by precision among those 50 (how many reviewed cases are real fraud), and, as labelled cases accumulate, by average precision; accuracy is useless at this imbalance.
Exercise 17: Pick the algorithm
Choose a first model and a stronger second one for each: (a) 2 million rows of web events with 40 numeric and categorical columns, predicting a purchase; (b) 300 customer reviews labelled positive or negative; (c) GPS positions of 50 000 delivery stops, to find natural depot areas, with some stray points; (d) 200 rows of lab measurements, a regulator wants to see how each measurement affects the result.
Answer
(a) Logistic regression baseline, then LightGBM or XGBoost with native categorical handling and early stopping. (b) Tf-idf with multinomial naive Bayes or logistic regression; with so few labels, naive Bayes is a strong start. (c) DBSCAN or HDBSCAN on projected coordinates (irregular shapes, noise); k-means if depots must be compact and their number is fixed. (d) Regularised linear or logistic regression with standardised features (readable coefficients), with repeated cross-validation; a shallow tree as a readable alternative.
Exercise 18: Is the new model better?
On the same 10 cross-validation splits, a new model's accuracy minus the old model's is: 0.02, 0.01, 0.00, 0.03, -0.01, 0.02, 0.01, 0.00, 0.02, 0.01. Summarise the evidence. What else would you check before switching?
Answer
Mean difference ; the new model wins 7 splits, ties 2 and loses 1. The evidence favours the new model, but fold scores are correlated, so a naive t-test overstates the certainty; use the corrected test or simply report the mean and the spread. Before switching: was the new model tuned on these same splits (then its advantage is optimistic; use nested CV)? Is 1.1 points worth any extra cost in training time, latency, interpretability or maintenance? Does it fail on an important subgroup?
Test yourself
Which algorithm in this course needs no feature scaling at all?
- kNN
- RBF SVM
- Random forest
- k-means
Which pair of methods are equivalent at their optimum?
- k-means and DBSCAN
- A linear autoencoder with squared error and PCA
- Naive Bayes and logistic regression
- Bagging and boosting
Which statement about gradient boosting and random forests is right?
- Both grow trees independently
- Boosting fits each tree to the current residuals; a forest averages independent deep trees
- A forest overfits as trees are added; boosting never does
- Both need feature scaling