Answer key — all 37 practice questions
Every question on the practice sheet, worked in exam form and grouped into the six question types the paper actually uses: two math, two coding, two short answer.
This page answers every question on CS460G_MidtermPractice.docx, in exam form. The questions are grouped into the six question types the paper actually uses, so you can revise by section rather than in the document's original order.
The paper: 6 questions, 50 minutes, 100 points — 2 math (40), 2 coding (40), 2 short answer (20). Budget: 8–9 minutes per math question, 10 per coding, 5 per short answer. The short answers are only 10 points each, so do not write essays there; the math is where the marks are.
Legend: sections A and B are the two math questions. C and D are the two short-answer questions. E and F are the two coding questions.
A. Math I — decision trees, confusion matrix, entropy, ensembles
A1. Confusion matrix → F1 for both classes
> A binary classifier produces the following confusion matrix. Calculate the F1 score for the Positive and the Negative class.
| Actual \\ Predicted | Positive | Negative |
|---|---|---|
| Positive | 85 | 15 |
| Negative | 20 | 80 |
Worked answer
Read the cells off first. For the positive class:
$$TP = 85,\quad FN = 15,\quad FP = 20,\quad TN = 80$$
Positive class
$$P = \frac{TP}{TP+FP} = \frac{85}{85+20} = \frac{85}{105} = 0.8095$$
$$R = \frac{TP}{TP+FN} = \frac{85}{85+15} = \frac{85}{100} = 0.8500$$
$$F_1 = \frac{2PR}{P+R} = \frac{2(0.8095)(0.85)}{0.8095+0.85} = \frac{1.3762}{1.6595} = \boxed{0.8293}$$
Shortcut that saves a minute in the exam:
$$F_1^{+} = \frac{2TP}{2TP+FP+FN} = \frac{170}{170+20+15} = \frac{170}{205} = 0.8293$$
Negative class — relabel so that Negative becomes the positive class. Then $TP'=80$, $FN'=20$, $FP'=15$, $TN'=85$:
$$P' = \frac{80}{80+15} = 0.8421, \qquad R' = \frac{80}{80+20} = 0.8000$$
$$F_1^{-} = \frac{2(0.8421)(0.8)}{0.8421+0.8} = \frac{1.3474}{1.6421} = \boxed{0.8205}$$
Sensitivity check. Overall accuracy is $\frac{85+80}{200} = 0.8250$. Both class F1s (0.829, 0.821) sit just above it, which is what you expect when the classes are balanced and the errors are roughly symmetric (35 errors total, 20 FP vs 15 FN). If one class F1 had come out below accuracy while the other was far above, that would signal class imbalance — a useful sanity check to state.
Two errors here cost marks. (1) Mixing up $FP$ and $FN$: $FP$ is actual negative, predicted positive — the column sum minus the diagonal; $FN$ is actual positive, predicted negative — the row sum minus the diagonal. (2) Writing a single "F1" when the question asks for both classes. Always label which class each number belongs to.
A2. Entropy of a 3-class subset
> Calculate the entropy of the following subset of a dataset with 3 classes. > A A B C A A B C C A C A
Worked answer
Count the classes. Twelve observations:
| Class | Count | $p_i$ |
|---|---|---|
| A | 6 | 0.500 |
| B | 2 | 0.1667 |
| C | 4 | 0.3333 |
| Total | 12 | 1.000 |
Apply the formula:
$$H(S) = \sum_{i=1}^{c} -p_i\log_2 p_i = -\sum_i p_i \log_2 p_i$$
$$H = -\left[\tfrac{6}{12}\log_2\tfrac{6}{12} + \tfrac{2}{12}\log_2\tfrac{2}{12} + \tfrac{4}{12}\log_2\tfrac{4}{12}\right]$$
Evaluate each term:
$$\log_2\tfrac12 = -1.0000 \;\Rightarrow\; -0.5(-1) = +0.5000$$ $$\log_2\tfrac16 = -2.5850 \;\Rightarrow\; -0.1667(-2.585) = +0.4308$$ $$\log_2\tfrac13 = -1.5850 \;\Rightarrow\; -0.3333(-1.585) = +0.5283$$
$$H = 0.5000 + 0.4308 + 0.5283 = \boxed{1.459 \text{ bits}}$$
Sanity check. The maximum possible entropy for $c=3$ is $\log_2 3 = 1.585$ bits, which occurs at a perfectly uniform split. Our split is 50/16.7/33.3, so it is less mixed than uniform and $H$ must be below 1.585. It is. A pure subset would give 0. So 1.459 is in the right interval — say that; it shows you know what the number means.
The lecture's own worked example uses $p=(1/5, 3/5, 1/5)$ and gets 0.88 bits. Same formula, different counts — do not copy 0.88.
A3. Decision tree by information gain (the 4-row table)
> Suppose we have a train set with 3 features and 2 classes. How to distinguish between class 1 and class 2 using a decision tree? [Hint: calculate information gain to select the parent and child nodes]
| $x_1$ | $x_2$ | $x_3$ | $y$ |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 2 |
| 1 | 1 | 1 | 2 |
| 1 | 1 | 0 | 1 |
Worked answer
Step 0 — parent entropy. $y=\{1,2,2,1\}$: two of each.
$$H(S) = -\tfrac12\log_2\tfrac12 - \tfrac12\log_2\tfrac12 = 1.000 \text{ bit}$$
Step 1 — information gain for every candidate attribute.
For a split of $S$ into subsets $S_v$:
$$IG = H(S) - \sum_v \frac{|S_v|}{|S|}\,H(S_v)$$
$(x_1)$: value 0 → row 1 only, $y=\{1\}$, $H=0$. Value 1 → rows 2,3,4, $y=\{2,2,1\}$:
$$H = -\tfrac23\log_2\tfrac23 - \tfrac13\log_2\tfrac13 = 0.9183$$
$$E_{\text{avg}} = \tfrac14(0) + \tfrac34(0.9183) = 0.6887 \qquad IG = 1 - 0.6887 = \mathbf{0.3113}$$
$(x_2)$: value 0 → row 2 only, $y=\{2\}$, $H=0$. Value 1 → rows 1,3,4, $y=\{1,2,1\}$:
$$H = 0.9183, \qquad E_{\text{avg}} = \tfrac14(0)+\tfrac34(0.9183) = 0.6887 \qquad IG = \mathbf{0.3113}$$
$(x_3)$: value 1 → row 3 only, $y=\{2\}$, $H=0$. Value 0 → rows 1,2,4, $y=\{1,2,1\}$:
$$H = 0.9183, \qquad E_{\text{avg}} = \tfrac34(0.9183) = 0.6887 \qquad IG = \mathbf{0.3113}$$
| Attribute | $E(S_v{=}0)$ | $E(S_v{=}1)$ | $E_{\text{avg}}$ | $IG$ |
|---|---|---|---|---|
| $x_1$ | 0 (1 sample) | 0.9183 (3) | 0.6887 | 0.3113 |
| $x_2$ | 0 (1 sample) | 0.9183 (3) | 0.6887 | 0.3113 |
| $x_3$ | 0.9183 (3) | 0 (1) | 0.6887 | 0.3113 |
All three tie. State this explicitly — it is not a computation error. Each feature splits the set the same way structurally: one row isolated, three rows left with a 2:1 mix.
Step 2 — choose a root and recurse. Take $x_2$ (any is valid):
- $x_2=0$ → row 2 → $y=2$. Pure leaf.
- $x_2=1$ → rows 1, 3, 4 → $y=\{1,2,1\}$, $H = 0.9183$.
Within that child, compute $IG$ for the remaining two features:
- Split on $x_3$: $x_3=1$ → row 3 → $y=2$, $H=0$; $x_3=0$ → rows 1,4 → $y=\{1,1\}$, $H=0$.
- Split of $x_1$ inside this subset: $x_1$ is constant (=1) for all three rows, so it has zero gain and cannot be used.
$$E_{\text{avg}} = \tfrac13(0)+\tfrac23(0) = 0 \qquad IG = 0.9183 - 0 = \mathbf{0.9183}$$
So $x_3$ is chosen, and both its children are pure.
Final tree
x2
/ \
=0 =1
| |
y=2 x3
/ \
=1 =0
| |
y=2 y=1
Verification, row by row
| Row | $(x_1,x_2,x_3)$ | Path | Predicted $y$ | True $y$ |
|---|---|---|---|---|
| 1 | (0,1,0) | $x_2{=}1 \to x_3{=}0$ | 1 | 1 ✓ |
| 2 | (1,0,0) | $x_2{=}0$ | 2 | 2 ✓ |
| 3 | (1,1,1) | $x_2{=}1 \to x_3{=}1$ | 2 | 2 ✓ |
| 4 | (1,1,0) | $x_2{=}1 \to x_3{=}0$ | 1 | 1 ✓ |
Training error $=0$. Two internal nodes, four leaves, two splits used.
Mark allocation, and how to hit it. Parent entropy (1) · weighted $E_{\text{avg}}$ with the $\frac{|S_v|}{|S|}$ factors visible (2) · $IG$ per attribute (2) · correct recursion to pure leaves, verified (2). Drawing only the tree loses five of seven marks. Write the table.
A4. Ensemble error with $\varepsilon = 0.4$, $n = 11$
> You are building an ensemble classifier using 11 independent base learners. Each individual learner has an error probability of $\varepsilon = 0.4$. The ensemble makes its final prediction based on a majority vote. Calculate the probability that the ensemble will make an incorrect prediction.
Worked answer
Translate the question. A majority vote of 11 fails when 6 or more learners are wrong. (Eleven voters cannot tie; 6 is the smallest losing majority.)
$$k = \left\lfloor \tfrac{n}{2}\right\rfloor + 1 = \left\lfloor \tfrac{11}{2}\right\rfloor + 1 = 5+1 = 6$$
Apply the binomial formula from the ensemble lecture:
$$\varepsilon_{\text{ensemble}} = P(\text{fail}) = \sum_{k=6}^{11}\binom{11}{k}\varepsilon^{k}(1-\varepsilon)^{11-k}$$
with $\varepsilon=0.4$ and $1-\varepsilon = 0.6$:
| $k$ | $\binom{11}{k}$ | $0.4^k$ | $0.6^{11-k}$ | term |
|---|---|---|---|---|
| 6 | 462 | 0.004096 | 0.007776 | 0.014719 |
| 7 | 330 | 0.001638 | 0.012960 | 0.007006 |
| 8 | 165 | 0.000655 | 0.021600 | 0.002335 |
| 9 | 55 | 0.000262 | 0.036000 | 0.000519 |
| 10 | 11 | 0.000105 | 0.060000 | 0.0000692 |
| 11 | 1 | 0.0000419 | 0.100000 | 0.0000042 |
$$\varepsilon_{\text{ensemble}} = 0.014719 + 0.007006 + 0.002335 + 0.000519 + 0.0000692 + 0.0000042 = \boxed{0.2465}$$
So the ensemble is wrong about 24.7% of the time — i.e. 75.35% accurate.
The point of the exercise. One learner at $\varepsilon=0.4$ is 60% accurate. Eleven of them, majority-voted, are 75.3% accurate. Compare the lecture's own reference case ($n=11$, $\varepsilon=0.25$ → $\varepsilon_{\text{ensemble}}=0.034$, i.e. 96.6% accurate): the improvement is dramatic when the base learner is already good, and much more modest at $\varepsilon=0.4$, because 0.4 is close to the 0.5 chance line.
Symmetry check (cheap and convincing): with $\varepsilon<0.5$, $P(\ge 6)$ must be less than $P(\ge 5)$ by the symmetric amount, and must be well below 0.5. 0.2465 satisfies both.
Three ways this gets marked wrong.
- Using $k=5$ instead of 6. A majority of 11 needs 6; 5 is not a majority.
- Summing the complement. Some write $P(\le 6)$ — that includes the case of exactly 6, which is already a loss, and it sums to more than 1.
- Assuming independence actually holds. The formula assumes the learners err independently. In practice members trained on the same data are positively correlated, so this is a lower bound on the true ensemble error. Saying that is worth a mark in a "discuss" part.
B. Math II — SVM, gradient descent, activations, neural networks
B1. Derive the margin formula for SVM
> Derive the margin formula for SVM.
Worked answer
Set-up. The decision boundary is the hyperplane
$$w_0 + w^Tx = 0$$
with normal vector $w$ and offset $w_0$. Because the problem is invariant to the scale of $(w,w_0)$, fix the scale by defining the two support hyperplanes as
$$w_0 + w^Tx_{pos} = +1 \qquad\text{(positive hyperplane)}$$ $$w_0 + w^Tx_{neg} = -1 \qquad\text{(negative hyperplane)}$$
Step 1 — subtract the second equation from the first. The bias cancels:
$$w^T(x_{pos}) - w^T(x_{neg}) = 1-(-1)$$ $$\boxed{\,w^T(x_{pos}-x_{neg}) = 2\,}$$
Step 2 — the length of the normal. For $w\in\mathbb{R}^m$,
$$\|w\| = \sqrt{\sum_{j=1}^{m} w_j^2}$$
Step 3 — project the gap onto the unit normal. The perpendicular distance between the two parallel hyperplanes is the component of $(x_{pos}-x_{neg})$ along $w/\|w\|$:
$$d = \frac{w^T(x_{pos}-x_{neg})}{\|w\|}$$
Step 4 — substitute step 1:
$$\boxed{\;\text{margin} = \gamma = \frac{2}{\|w\|}\;}$$
Step 5 — turn it into an optimisation. Maximising $\frac{2}{\|w\|}$ is equivalent to minimising $\|w\|$, and equivalent to minimising $\frac12\|w\|^2$ (the $\frac12$ and the square are monotone transformations chosen to make the derivative clean: $\frac{d}{dw}\frac12\|w\|^2 = w$).
$$\min_{w,w_0}\;\tfrac12\|w\|^2 \quad\text{s.t.}\quad y_i\big(w^Tx_i+w_0\big)\ge 1 \;\;\forall i$$
Interpretation. The margin is inversely proportional to the norm of the weight vector. A large margin means a small $\|w\|$. This is why the SVM objective is a minimisation of $\|w\|^2$ rather than a maximisation of the margin — and why $w$ appears in the denominator of the distance formula at all.
Do not skip step 3. Students routinely jump from $w^T(x_{pos}-x_{neg})=2$ straight to $\frac{2}{\|w\|}$ without saying why the division by $\|w\|$ is the right normalisation. One sentence — "dividing by $\|w\|$ converts the projected difference into a perpendicular distance" — is the difference between a derivation and an assertion.
B2. Zero-one loss versus hinge loss
> What is the difference between zero-one loss and hinge loss?
Worked answer
Definitions.
$$L_{0/1}(y, f(x)) = \mathbb{1}\big[y\,f(x) < 0\big] = \begin{cases}0 & y f(x) \ge 0 \;\;(\text{correct})\\ 1 & y f(x) < 0 \;\;(\text{wrong})\end{cases}$$
$$L_{\text{hinge}}(y, f(x)) = \max\big(0,\; 1 - y\,f(x)\big)$$
where $f(x)$ is the predicted score (not the label) and $y\in\{-1,+1\}$.
Where the hinge is zero and non-zero:
| Position of the point | $y f(x)$ | $L_{0/1}$ | $L_{\text{hinge}}$ |
|---|---|---|---|
| correct side, outside the margin | $\ge 1$ | 0 | 0 |
| correct side, exactly on the margin | $=1$ | 0 | 0 |
| correct side, inside the margin | $0| 0 | $1-yf \in (0,1)$ | |
| on the boundary | $=0$ | 0 | $1$ |
| wrong side | $<0$ | 1 | $>1$ |
The four differences that earn the marks:
- Range. 0-1 is $\{0,1\}$; hinge is $[0,\infty)$ and unbounded.
- Margin awareness. 0-1 counts a confident correct prediction and a barely-correct one identically. Hinge penalises a correct-but-inside-the-margin point — it cares how correct.
- Differentiability. 0-1 is piecewise constant with gradient 0 almost everywhere, so gradient descent cannot move on it. Hinge is continuous, convex, and piecewise linear, so it is sub-differentiable everywhere and optimisable.
- Learning-theoretic status. Hinge is the tightest convex upper bound on 0-1 loss, which makes minimising it a principled surrogate: any bound on hinge risk bounds 0-1 risk.
Why it is called a hinge: the loss graph is flat then bends down at $y f(x)=1$, like a door hinge. The hinge point is the margin — that is the geometric meaning.
Because hinge is an upper bound, SVM's training loss is pessimistic relative to the 0-1 quantity you actually care about. That is a feature, not a bug: it is exactly what makes the optimisation tractable and what links the margin to generalisation.
B3. Gradient descent; stochastic vs mini-batch
> What is gradient descent? What's the difference between Stochastic and Mini-batch gradient descent?
Worked answer
Definition. Gradient descent is an iterative first-order optimisation method. Starting from an initial parameter vector, it repeatedly steps in the direction of steepest decrease of the loss:
$$w^{(t+1)} = w^{(t)} - \alpha\,\nabla_w L\big(w^{(t)}\big)$$
where $\alpha>0$ is the learning rate. For a convex loss (linear regression with squared error, logistic regression with cross-entropy) it converges to the global minimum; for a non-convex loss (neural networks) it converges to a local minimum or saddle point.
The variants differ only in how much data $\nabla L$ is averaged over.
Let the empirical loss be $L(w)=\frac{1}{N}\sum_{n=1}^{N}\ell\big(w;x_n,y_n\big)$.
| Batch | Mini-batch | Stochastic (SGD) | |
|---|---|---|---|
| Gradient uses | all $N$ samples | a subset of size $B$ ($1 | one sample |
| Update frequency | once per epoch | $N/B$ per epoch | $N$ per epoch |
| Gradient quality | exact | noisy, variance $\propto 1/B$ | very noisy |
| Cost per update | $O(N)$ | $O(B)$ | $O(1)$ |
| Progress per epoch | slowest (fewest updates) | balanced | fastest |
| Converges to | the minimum, smoothly | the minimum, with noise | a neighbourhood of the minimum; noise can help escape bad minima |
| Memory | whole dataset | one batch | one sample |
Epoch versus iteration — a distinction the course asks for explicitly:
- Epoch — one full pass over the training set.
- Iteration — one parameter update.
So one epoch is 1 iteration for batch GD, $N/B$ iterations for mini-batch, and $N$ iterations for SGD.
Practical verdict. Mini-batch is the default in every deep-learning framework: it gets most of SGD's speed (many updates per epoch) with much lower gradient variance, and it maps efficiently onto GPU parallelism. Pure SGD is rarely used because per-sample updates waste vectorised hardware.
The one-line answer if time is short: "Gradient descent updates parameters along the negative gradient scaled by a learning rate. Batch uses all samples per update, stochastic uses one, mini-batch uses a subset — so they trade gradient accuracy against update frequency, with mini-batch being the practical default."
B4. Softmax of $z = [0.6,\,1.1,\,-1.5,\,3.2,\,-1.1]$
> Suppose in a 5-class classification NN model, a softmax activation takes the final feature vector as input: $z=[0.6,1.1,-1.5,3.2,-1.1]$. Calculate the resulting softmax and the final class prediction.
Worked answer
Formula:
$$\text{softmax}(z)_i = \frac{e^{z_i}}{\sum_{j=1}^{5} e^{z_j}}$$
Step 1 — exponentiate each logit.
| $i$ | $z_i$ | $e^{z_i}$ |
|---|---|---|
| 1 | 0.6 | 1.82212 |
| 2 | 1.1 | 3.00417 |
| 3 | −1.5 | 0.22313 |
| 4 | 3.2 | 24.53253 |
| 5 | −1.1 | 0.33287 |
Step 2 — normalising constant:
$$Z = \sum_j e^{z_j} = 1.82212+3.00417+0.22313+24.53253+0.33287 = 29.91482$$
Step 3 — divide.
| $i$ | $e^{z_i}$ | $p_i = e^{z_i}/Z$ |
|---|---|---|
| 1 | 1.82212 | 0.0609 |
| 2 | 3.00417 | 0.1004 |
| 3 | 0.22313 | 0.0075 |
| 4 | 24.53253 | 0.8201 |
| 5 | 0.33287 | 0.0111 |
| Σ = 1.0000 ✓ |
$$\text{softmax}(z) = [0.0609,\;0.1004,\;0.0075,\;\mathbf{0.8201},\;0.0111]$$
Final prediction: the class with the largest probability, i.e.
$$\hat y = \arg\max_i p_i = 4 \quad (\approx 82.0\%\ \text{confidence})$$
Two checks worth writing down. The outputs sum to 1 — if they do not, you divided wrong. And the largest logit gives the largest probability (softmax is strictly monotone), so you can identify the class before computing any exponentials: that is the fast way to answer the "which class?" half of the question under time pressure.
Numerical-stability remark that impresses. In code one subtracts $\max_i z_i$ from every logit before exponentiating: $\text{softmax}(z) = \text{softmax}(z - \max z)$. This leaves the result unchanged mathematically (the constant cancels numerator and denominator) but prevents overflow when logits are large. Here it would give $z'=[-2.6,-2.1,-4.7,0,-4.3]$, still yielding 0.8201 for class 4.
B5. A single neuron under three activations
> Suppose a neuron performs $z = wx$ followed by $a = g(z)$. If $w = [-1.2, 3.1, 2.5]$ and $x = [0.5, -1.6, 0.8]$, calculate and compare the output for (i) sigmoid, (ii) ReLU, (iii) tanh.
Worked answer
Step 1 — the linear score (common to all three).
$$z = w\cdot x = \sum_{j=1}^{3} w_j x_j$$
| $j$ | $w_j$ | $x_j$ | $w_jx_j$ |
|---|---|---|---|
| 1 | −1.2 | 0.5 | −0.60 |
| 2 | 3.1 | −1.6 | −4.96 |
| 3 | 2.5 | 0.8 | +2.00 |
| Σ = −3.56 |
$$z = -0.60 - 4.96 + 2.00 = \boxed{-3.56}$$
Note the sign: the dominant contribution is the second term, where a positive weight multiplies a negative input. A single feature can flip the whole neuron.
Step 2 — apply each activation.
(i) Sigmoid $\;\sigma(z)=\dfrac{1}{1+e^{-z}}$
$$\sigma(-3.56) = \frac{1}{1+e^{3.56}} = \frac{1}{1+35.16} = \frac{1}{36.16} = \boxed{0.0277}$$
(ii) ReLU $\;g(z)=\max(0,z)$
$$\max(0,\,-3.56) = \boxed{0}$$
(iii) Tanh $\;\tanh(z)=\dfrac{e^{z}-e^{-z}}{e^{z}+e^{-z}}$
With $2z = -7.12$, $e^{-7.12}=0.000807$:
$$\tanh(-3.56) = \frac{0.000807-1}{0.000807+1} = \frac{-0.999193}{1.000807} = \boxed{-0.9984}$$
Step 3 — compare.
| Activation | Output | Range | Behaviour at $z=-3.56$ |
|---|---|---|---|
| Sigmoid | 0.0277 | $(0,1)$ | near the lower asymptote — saturated |
| ReLU | 0 | $[0,\infty)$ | in the dead zone; gradient exactly 0 |
| Tanh | −0.9984 | $(-1,1)$ | near the lower asymptote — saturated |
What the comparison shows — this is the "compare" part of the marks:
- Sigmoid and tanh saturate together. Both are S-shaped and both flatten at $\lvert z\rvert \gtrsim 3$; both outputs are within 0.003 of their asymptote. Their derivatives are therefore near zero, so during backpropagation almost no gradient flows through this neuron — the vanishing gradient problem.
- Tanh is the zero-centred sigmoid. Note that $\tanh(z) = 2\sigma(2z)-1$, and here $2(0.0277)-1 = -0.9446$ at $2z=-7.12$ — the same family, recentred. Zero-centred outputs are why tanh trains faster than sigmoid in hidden layers.
- ReLU is qualitatively different. It does not squash the negative side, it kills it. Output 0 with derivative 0 means this neuron contributes nothing and receives no gradient — the dying ReLU problem, which Leaky ReLU exists to fix.
- Only ReLU is unbounded above, so it does not saturate for large positive $z$ — the reason it became the default in hidden layers.
The most common mistake is sign. $+3.1 \times (-1.6) = -4.96$, not $+4.96$. If you get $z = +2.44$ you will answer ReLU $= 2.44$ and sigmoid $= 0.919$, which is a completely different (and wrong) story. Recompute the sum before applying any activation.
B6. Describe a neural network and calculate its size
> Describe the following neural network. Calculate the size of the network. > (diagram: 3 input nodes → 4 nodes → 4 nodes → 1 node)
Worked answer
Description.
A fully-connected feed-forward multilayer perceptron (MLP). Data flows strictly left to right with no cycles; every unit in a layer is connected to every unit in the following layer (dense layers).
| Layer | Units | Role |
|---|---|---|
| Input | 3 | receives the feature vector $x\in\mathbb{R}^3$ |
| Hidden 1 | 4 | $h_1 = g(W_1x + b_1)$ |
| Hidden 2 | 4 | $h_2 = g(W_2h_1 + b_2)$ |
| Output | 1 | $\hat y = g(W_3h_2 + b_3)$ |
Depth. By the course convention — the input layer does not count — this is a 3-layer network with two hidden layers. (State the convention explicitly; it is the first mark.)
Output unit note. A single output suits binary classification with a sigmoid, or regression with a linear activation. For a 3-class problem you would need 3 output units with softmax.
Size — neurons. Hidden and output units only:
$$4 + 4 + 1 = \boxed{9 \text{ neurons}}$$
Size — learnable parameters. Per layer, parameters are weights $n_{\ell-1}\times n_\ell$ plus biases $n_\ell$:
$$W_1: 3\times4 + 4 = 16$$ $$W_2: 4\times4 + 4 = 20$$ $$W_3: 4\times1 + 1 = 5$$
$$\boxed{\#\text{params} = 16 + 20 + 5 = 41}$$
Compact formula for layers $n_0\to n_1\to\dots\to n_L$:
$$\#\text{params} = \sum_{\ell=1}^{L} n_\ell\big(n_{\ell-1}+1\big) = \sum_{\ell=1}^{L}\big(n_{\ell-1}n_\ell + n_\ell\big)$$
Check: $4(3+1) + 4(4+1) + 1(4+1) = 16+20+5 = 41$ ✓
Why the bias term matters. Weights alone give $12+16+4 = 32$; the correct answer is 41. The 9 bias parameters are 22% of the network and are the usual lost marks. If a question instead says "weights only", say so and give 32 — but do not silently omit them.
If asked for the forward pass: $h_1 = \mathrm{ReLU}(W_1x+b_1)$, $h_2=\mathrm{ReLU}(W_2h_1+b_2)$, $\hat y = \sigma(W_3h_2+b_3)$ for binary classification. Matrix shapes: $W_1\in\mathbb{R}^{4\times3}$, $W_2\in\mathbb{R}^{4\times4}$, $W_3\in\mathbb{R}^{1\times4}$.
C. Short answer I — linear models, k-NN, decision trees, neural networks
C1. What is Empirical Risk Minimisation? Why "empirical"? Its role in learning theory.
Answer. ERM is the principle of choosing, from a hypothesis class $\mathcal{H}$, the hypothesis that minimises the average loss on the training sample:
$$\hat h = \arg\min_{h\in\mathcal{H}} R_{\text{emp}}(h), \qquad R_{\text{emp}}(h)=\frac{1}{n}\sum_{i=1}^{n}L\big(h(x_i),y_i\big)$$
The word empirical is the crux. The quantity we would like to minimise is the true risk
$$R(h)=\mathbb{E}_{(x,y)\sim P}\big[L(h(x),y)\big]=\int L(h(x),y)\,dP(x,y)$$
but $P(x,y)$ is unknown — this is agnostic learning — so $R(h)$ is incomputable. $R_{\text{emp}}$ is the empirical estimate of it: a finite-sample average standing in for an expectation over a distribution we never observe.
Its role in learning theory is twofold. First, it turns "learn" into a well-posed optimisation problem with a computable objective. Second, it is the object that generalisation theory bounds: for a finite hypothesis class, PAC learning shows that with enough i.i.d. samples, ERM returns a hypothesis whose true risk is within $\epsilon$ of the best in $\mathcal{H}$ with probability at least $1-\delta$, with sample complexity
$$m_{\mathcal{H}}(\epsilon,\delta)\gtrsim\frac{\log|\mathcal{H}|+\log(1/\delta)}{\epsilon}$$
So ERM is justified not because it minimises risk — it cannot compute it — but because it is a uniformly convergent estimator of the risk minimiser.
Marks hinge on: the two formulas, the phrase "the distribution is unknown", and the PAC justification.
C2. Cross-validation; k-fold versus LOO
Answer. Cross-validation estimates generalisation performance by rotating which portion of the data is held out.
k-fold. Partition the training set into $k$ equal folds. For $i=1\ldots k$: train on the other $k-1$ folds, validate on fold $i$. Report the mean (and standard deviation) of the $k$ scores. Every point is used for validation exactly once, and for training $k-1$ times.
LOO. Leave-one-out is the $k=n$ extreme: $n$ models, each trained on $n-1$ samples and validated on the single held-out point.
| k-fold | LOO | |
|---|---|---|
| Fits required | $k$ | $n$ |
| Training size | $\frac{k-1}{k}n$ | $n-1$ |
| Bias | slightly pessimistic for small $k$ | nearly unbiased |
| Variance | lower | higher — the $n$ training sets differ by one point, so the estimates are highly correlated |
| Cost | cheap | prohibitive beyond a few thousand samples |
| Stratifiable | yes | trivially |
Why LOO has high variance despite low bias is the subtle mark: the $n$ models are almost identical, so their errors are strongly correlated, and averaging correlated estimates does not reduce variance much. High bias in small-$k$ folds comes from each model seeing only $(k-1)/k$ of the data.
Practical answer: $k=5$ or $10$, stratified. Use LOO only for very small datasets where the bias is unacceptable.
C3. The role of $C$ in SVM
Answer. $C$ is the regularisation hyperparameter of the soft-margin SVM, and it prices margin violations:
$$\min_{w,w_0,\xi}\;\tfrac12\|w\|^2 + C\sum_{i=1}^{N}\xi_i \quad\text{s.t.}\quad y_i(w^Tx_i+w_0)\ge 1-\xi_i,\;\; \xi_i\ge0$$
- Small $C$ — violations are cheap, so the optimiser trades them for a wide margin. More bias, less variance. Can underfit; a few outliers are simply tolerated.
- Large $C$ — violations are expensive, so the optimiser forces every point to the correct side, producing a narrow margin. More variance. Can overfit; sensitive to outliers and label noise.
- $C\to\infty$ recovers the hard-margin SVM, which is feasible only for separable data.
So $C$ is exactly the inverse of regularisation strength: larger $C$ = less regularisation. It is a hyperparameter, chosen by cross-validation, never learned by the optimiser.
C4. Hard versus soft margin
Answer. Hard margin requires every training point to be correctly classified and outside the margin:
$$\min_{w,w_0}\tfrac12\|w\|^2 \quad\text{s.t.}\quad y_i(w^Tx_i+w_0)\ge1\;\;\forall i$$
It exists only when the data is linearly separable; one mislabelled point makes the problem infeasible.
Soft margin introduces a slack variable $\xi_i\ge0$ per point and allows violations at a cost:
$$\min\;\tfrac12\|w\|^2 + C\sum_i\xi_i \quad\text{s.t.}\quad y_i(w^Tx_i+w_0)\ge1-\xi_i,\;\xi_i\ge0$$
The slack has a geometric reading:
| Situation | $\xi_i$ |
|---|---|
| correct side, outside the margin | 0 |
| correct side, exactly on the margin | 0 |
| correct side, inside the margin | $0<\xi_i<1$ |
| wrong side (misclassified) | $\xi_i>1$ |
Soft margin is always feasible, generalises better on noisy data, and reduces to hard margin as $C\to\infty$.
C5. Regularisation; L1 versus L2
Answer. Regularisation adds a penalty on the magnitude of the parameters to the loss:
$$J(w) = L_{\text{data}}(w) + \lambda\,\Omega(w)$$
It deliberately makes the model fit the training data less well in exchange for better generalisation — trading a little bias for a large reduction in variance.
| L1 — Lasso | L2 — Ridge | |
|---|---|---|
| Penalty | $\lambda\sum_i\lvert w_i\rvert$ | $\lambda\sum_i w_i^2$ |
| Effect | drives some weights exactly to 0 | shrinks all smoothly, rarely to 0 |
| Consequence | automatic feature selection, sparse model | keeps all features, small |
| Geometry | diamond constraint; optimum hits a corner | circular constraint; tangency at a generic point |
| Correlated features | picks one arbitrarily | shares weight between them |
| Closed form | none | $\hat w=(A^TA+\lambda I)^{-1}A^Tb$ |
| Good when | few features matter | many features matter a little; $d>N$ |
The geometric argument is the one that earns the extra mark: the L1 ball has vertices on the axes, so the loss contours touch it where some coordinates are zero.
Elastic net combines both: $\lambda_1\sum|w_i|+\lambda_2\sum w_i^2$.
C6. How does k-means work?
Answer. k-means partitions $N$ points into $K$ non-overlapping clusters by minimising the within-cluster sum of squares:
$$J = \sum_{k=1}^{K}\sum_{x\in C_k}\|x-\mu_k\|^2$$
Algorithm
- Initialise $K$ centroids (randomly, or with k-means++).
- Assign each point to its nearest centroid.
- Update each centroid to the mean of the points assigned to it.
- Repeat 2–3 until assignments stop changing.
Properties. $J$ decreases monotonically at every step, so the algorithm always converges — but only to a local optimum, which is why initialisation matters. It assumes spherical, similarly-sized, non-overlapping clusters, and it requires $K$ to be specified. It fails on non-convex shapes (two crescents get cut in half) and is sensitive to feature scaling.
C7. Overfitting versus underfitting
Answer.
| Underfitting | Overfitting | |
|---|---|---|
| Model | too simple | too complex |
| Training error | high | very low |
| Test error | high, close to train | much higher than train |
| Dominant term | high bias | high variance |
| Meaning | has not learned the pattern | has memorised the noise |
| Remedies | more features; more complex model; boosting | more data; simpler model; bagging; regularisation; early stopping; dropout |
The single diagnostic: look at the gap. A large train-test gap means overfitting. A large training error means underfitting. If both errors are high and similar, the model is too weak for the task — adding data will not help.
C8. Parametric versus non-parametric models
Answer.
| Parametric | Non-parametric | |
|---|---|---|
| Assumption | a fixed functional form is assumed | only "similar inputs → similar outputs" |
| Parameters | finite, fixed in number | effectively infinite; grows with $N$ |
| Data's role | all training instances shape one global model | only nearby instances shape a local prediction |
| Examples | linear regression, logistic regression | k-NN, decision trees |
| Advantages | simple; learning reduces to estimating a few $w$; fast at test time; compact | flexible; adapts to complex relationships; no strong assumption to violate |
| Disadvantages | the assumption may not hold → large error (bias) | memory and computation grow with the data; slow inference |
The distinguishing test in an exam: does the number of parameters grow with the training set size? If yes, non-parametric.
C9. Why a validation set; how it differs from the test set
Answer. A validation set exists so that model selection — choosing $k$, $C$, $\gamma$, the number of PCA components, the stopping epoch — happens on data the model was not fitted on, while the test set stays untouched for the final estimate.
- Training set — fits the parameters.
- Validation set — compares candidate hyperparameters and settings; may be looked at many times.
- Test set — used once, at the end, to report the unbiased generalisation estimate.
If you select on the test set, the test set has influenced the model: every comparison you made leaked a little information about it, and the reported accuracy becomes optimistically biased. It is no longer an estimate of performance on unseen data — it is an estimate of performance on data you tuned against.
In $k$-fold cross-validation the validation set is replaced by the folds, but the test set is still held out and still used once.
C10. Typical loss functions for classification and regression
Answer.
Classification
| Loss | Formula | Use |
|---|---|---|
| 0-1 | $\mathbb{1}[\hat y\neq y]$ | the quantity we actually care about; non-differentiable |
| Cross-entropy / logistic | $-[y\log\hat y+(1-y)\log(1-\hat y)]$ | binary; multiclass: $-\sum_c y_c\log\hat y_c$ |
| Hinge | $\max(0,1-yf(x))$ | SVM; convex upper bound on 0-1 |
Regression
| Loss | Formula | Use |
|---|---|---|
| Squared error (L2) | $(y-\hat y)^2$ | default; differentiable, closed form; sensitive to outliers |
| Absolute error (L1) | $\lvert y-\hat y\rvert$ | robust to outliers; non-differentiable at 0 |
| Huber | quadratic for small residuals, linear for large | compromise between the two |
| Negative log-likelihood | $-\log p(y\mid x)$ | probabilistic regression |
Why the surrogate: 0-1 loss has zero gradient almost everywhere, so it cannot be optimised directly. Cross-entropy is its smooth surrogate for probabilistic classifiers; hinge is its tightest convex upper bound for margin classifiers.
C11. Typical evaluation metrics
Answer.
Classification — from the confusion matrix (TP, FP, FN, TN):
- Accuracy $=\frac{TP+TN}{TP+TN+FP+FN}$
- Precision $=\frac{TP}{TP+FP}$
- Recall / sensitivity / TPR $=\frac{TP}{TP+FN}$
- Specificity / TNR $=\frac{TN}{TN+FP}$
- F1 $=\frac{2PR}{P+R}$
- ROC curve (TPR vs FPR), AUC
Regression: MSE, RMSE, MAE, percentage error, maximum error, $R^2=1-RSS/TSS$.
Which to choose: accuracy is misleading under class imbalance; precision matters when false positives are costly (spam filtering); recall matters when false negatives are costly (cancer screening); F1 balances the two; AUC measures ranking quality independent of threshold.
C12. What is ROC? How to interpret it?
Answer. The Receiver Operating Characteristic curve plots the true positive rate (sensitivity, recall) against the false positive rate ($1-$specificity) as the classification threshold is swept from 1 to 0.
- The point $(0,1)$ is perfect classification; the diagonal $y=x$ is random guessing.
- A curve bowed toward the top-left is better: it achieves high sensitivity at low false-positive cost.
- AUC (area under the curve) is the aggregate: the probability that the classifier ranks a randomly chosen positive above a randomly chosen negative. $0.5$ = chance, $1.0$ = perfect. It is threshold-independent.
Interpretation caveats. ROC requires a continuous score (predict_proba or decision_function). Feeding hard 0/1 labels collapses the curve to at most three points and the resulting "AUC" equals balanced accuracy at that single operating point. ROC is also optimistic under heavy class imbalance — precision-recall curves are preferred there.
C13. Supervised versus unsupervised learning, with examples
Answer.
| Supervised | Unsupervised | |
|---|---|---|
| Data | $D=\{(x_i,y_i)\}$ — labels present | $D=\{(x_i,?)\}$ — no labels |
| Goal | predict $y$ for unseen $x$ | discover structure in $x$ |
| Output | a label or a value | groups, a lower-dimensional representation, a density |
| Examples | logistic regression on the diabetes table predicting Diabetic; linear regression predicting disease progression | k-means on the same table with the label column deleted; PCA on the breast-cancer features |
| Evaluation | accuracy, F1, AUC, MSE, $R^2$ — direct comparison to ground truth | no ground truth; silhouette, within-cluster SSE, explained variance, downstream task performance |
Reinforcement learning is a third setting: a feedback loop between agent and environment, learning a policy that maximises cumulative reward from $(x_i, \text{action}, \text{reward})$ triples.
The sharpest way to state it: supervision is about the presence of a target, not about the algorithm. The same k-means code run with and without a label column is unsupervised and then supervised-adjacent.
C14. How does the k-NN algorithm work? Explain with an example
Answer. k-NN is a non-parametric, instance-based (lazy) classifier: it does no work at training time and all of its work at prediction time.
The four steps
- Store the training instances $\{(x_i,y_i),\dots\}$ — literally keep them in memory.
- Find the $k$ neighbours from the training set closest to the test instance $x^*$, using a distance metric (Euclidean, $p=2$, unless stated otherwise).
- Count how many of those $k$ neighbours fall in each class.
- Assign $x^*$ to the class with the maximum count — majority voting among the $k$ neighbours.
For regression the same four steps apply with step 4 replaced by the average of the neighbours' targets, $y^*=\operatorname{avg}(y_1,\dots,y_k)$.
Worked example. Take the Iris data restricted to petal length and petal width, and a query point $x^*=(5.0,\,2.0)$. Using $k=3$ and Euclidean distance, suppose the three nearest training points are
| Neighbour | Petal length | Petal width | Distance to $x^*$ | Class |
|---|---|---|---|---|
| A | 4.9 | 1.8 | 0.22 | versicolor |
| B | 5.1 | 2.1 | 0.14 | virginica |
| C | 4.8 | 2.2 | 0.28 | virginica |
Step 2 selected A, B, C because they have the three smallest distances. Step 3 counts 2 virginica, 1 versicolor. Step 4 assigns $x^*$ to virginica.
With $k=1$ the answer would be virginica (neighbour B). With $k=5$ the two next-closest points would join and could flip the vote — which is exactly why $k$ is a hyperparameter rather than a fixed constant.
Three properties an answer should carry:
- No training phase.
fitonly stores the data;predictdoes all the computation. Inference cost is $O(Nd)$ per query and memory is $O(Nd)$ — the "disadvantage" of non-parametric models. - Feature scaling is mandatory. Euclidean distance sums squared differences across features, so a feature measured in thousands drowns one measured in tenths. Standardise first.
- $k$ trades bias against variance. Small $k$ → the boundary follows noise (high variance, overfitting; $k=1$ has zero training error). Large $k$ → the boundary washes out (high bias, underfitting; $k=N$ predicts one class). Choose $k$ on validation data, and use an odd $k$ to avoid ties in binary problems.
The course's notebook sets n_neighbors=3, and on two Iris features reaches 71.05% accuracy — with setosa perfect and the versicolor/virginica overlap accounting for all the error.
D. Short answer II — clustering, dimensionality reduction, SVM, validation, ensembles
D1. How does k-means work? (long form)
See C6 for the algorithm. For the full-mark version add the two properties that show understanding: convergence is guaranteed because $J$ decreases monotonically, but only to a local optimum, so initialisation matters (k-means++ exists for this); and the model assumes spherical, non-overlapping, similarly-sized clusters, so it fails on non-convex shapes and requires $K$ in advance. Contrast with DBSCAN in one line to close.
D2. What is the $\epsilon$-neighbourhood? How is it used in DBSCAN?
Answer. For a real value $\epsilon>0$ and a point $p$, the $\epsilon$-neighbourhood of $p$ is the set of all data points at most $\epsilon$ away:
$$N_\epsilon(p)=\{\,q\in D \;:\; \operatorname{dist}(p,q)\le\epsilon\,\}$$
Use in DBSCAN. The neighbourhood size decides each point's label, and the labels drive the clustering:
- Core point — $\lvert N_\epsilon(p)\rvert \ge \text{minPts}$: enough density to seed a cluster.
- Border point — $\lvert N_\epsilon(p)\rvert < \text{minPts}$ but $p$ lies within $\epsilon$ of some core point: joins that core point's cluster.
- Noise point — neither: labelled $-1$.
The algorithm then forms one cluster per core point or connected group of core points, attaches the border points, and leaves the rest as noise. Because it works from local density rather than a global centroid, DBSCAN infers the number of clusters from the data and finds arbitrarily shaped clusters — its two advantages over k-means.
Parameters: $\epsilon$ sets the radius, minPts sets the density threshold. Both are hyperparameters; too small an $\epsilon$ fragments everything into noise, too large merges everything into one cluster.
D3. Purpose of PCA, and how it is performed
Answer. Purpose: reduce dimensionality while retaining as much information (variance) as possible — to avoid the curse of dimensionality, remove correlated and noisy features, reduce computation and storage, and enable 2-D visualisation.
Assumption: the data lies on (approximately) a lower-dimensional linear subspace.
Procedure — the six steps
- Standardise the $d$-dimensional dataset (zero mean, unit variance).
- Construct the $d\times d$ covariance matrix.
- Eigendecompose it into eigenvectors and eigenvalues.
- Select the $k$ eigenvectors with the $k$ largest eigenvalues ($k\ll d$).
- Build the $d\times k$ projection matrix $W$ from those eigenvectors.
- Transform: $Z=XW$, giving the $k$-dimensional representation.
Choosing $k$: the explained-variance ratio $\lambda_j/\sum_i\lambda_i$ gives each component's share; take the smallest $k$ whose cumulative sum crosses a threshold (commonly 90%). In the course's breast-cancer example, 5 of 30 components carry ~90% of the variance, and KNN accuracy improves from 0.93 to 0.97 after the reduction — fewer dimensions, less noise, better generalisation.
Key property: the components are orthogonal and ordered by variance, which is what distinguishes PCA from an arbitrary linear projection.
D4. PCA versus autoencoder
Answer.
| PCA | Autoencoder | |
|---|---|---|
| Type | linear projection | neural network |
| Encoder | a single fixed matrix | learned, possibly non-linear |
| Decoder | the transpose of the encoder | a separate learned network |
| Objective | maximise variance (equivalently, minimise reconstruction error) | minimise reconstruction error |
| Solution | closed form via eigendecomposition | iterative, gradient descent |
| Components | orthogonal, ordered by explained variance | not orthogonal, not ordered |
| Data needed | none beyond the covariance | many samples plus training |
| Captures | linear subspaces | curved manifolds |
The relationship the lecture states explicitly: if both encoder and decoder are linear, the autoencoder's optimum coincides with PCA — so an autoencoder is best understood as non-linear PCA.
How to characterise it: self-supervised. There are no external labels, but the targets are the inputs themselves, which is why it sits in the unsupervised half of the taxonomy while training with a supervised-style reconstruction loss.
D5. The kernel trick and its purpose
Answer. An SVM's dual formulation depends on the training points only through inner products $\langle x_i,x_j\rangle$. When the data is not linearly separable, one maps it into a higher-dimensional space $x\mapsto\phi(x)$ so that it becomes separable there — but computing $\phi$ explicitly is expensive or impossible (for an RBF kernel the feature space is infinite-dimensional).
The kernel trick replaces the inner product with a kernel function that computes it implicitly:
$$k(x,z)=\langle\phi(x),\phi(z)\rangle$$
without ever forming $\phi$. The decision function becomes
$$f(x)=\sum_{i}\alpha_i y_i\,k(x_i,x)+b$$
a weighted sum of similarities to the support vectors. Purpose: to obtain a non-linear classifier at the computational cost of a linear one — one kernel evaluation per pair instead of an explicit high-dimensional expansion.
D6. Common SVM kernels and their hyperparameters
Answer.
| Kernel | $k(x,z)$ | Hyperparameters | When |
|---|---|---|---|
| Linear | $x^Tz$ | $C$ | $d\gg N$, or already separable |
| Polynomial (degree $d$) | $(x^Tz)^d$ | $d$, $C$ | interactions of known order |
| Polynomial (up to degree $d$) | $(x^Tz+1)^d$ | $d$, $C$ | includes all lower-order terms |
| RBF — Radial Basis Function, or Gaussian | $\exp(-\gamma\|x-z\|^2)$ | $\gamma$, $C$ | default when nothing is known |
$C$ — inverse regularisation strength; small $C$ = wide margin, more tolerance of violations; large $C$ = narrow margin, fits training data hard.
$d$ — order of feature interaction; too low underfits, too high becomes unstable and overfits.
$\gamma$ — radius of influence of a single training point. Small $\gamma$ → slow decay, every point influences everything, boundary nearly linear (underfitting). Large $\gamma$ → fast decay, each point only affects its immediate neighbourhood, boundary becomes spiky and wraps individual points (overfitting).
Practical note: the RBF kernel is a function of Euclidean distance, so features must be scaled first.
D7. Bagging versus boosting
Answer.
| Bagging | Boosting | |
|---|---|---|
| Training | parallel, independent | sequential, each depends on the last |
| Data per member | bootstrap samples with replacement | subsets without replacement, or re-weighted samples |
| Member strength | strong, low-bias learners (deep trees) | weak learners (stumps) |
| Combining | equal-weight vote / average | weighted vote, weights from each learner's accuracy |
| Primary effect | reduces variance | reduces bias |
| Typical algorithm | random forest | AdaBoost |
| Risk | little gain if members correlated | can overfit with too many rounds or label noise |
The one-line distinction: bagging averages many independent strong models to cancel variance; boosting builds weak models one at a time, each correcting the previous one's mistakes, to reduce bias.
D8. The fundamental idea behind ensembles; why it is more accurate
Answer. An ensemble combines the predictions of multiple models so that their errors partially cancel. The requirement is stated as two conditions: the base learners must be accurate (better than chance) and diverse (they must make different errors).
The justification is binomial. For $n$ independent learners each erring with probability $\varepsilon$, a majority vote fails when at least $k=\lfloor n/2\rfloor+1$ are wrong:
$$\varepsilon_{\text{ensemble}}=\sum_{k}^{n}\binom{n}{k}\varepsilon^{k}(1-\varepsilon)^{n-k}$$
With $n=11$ and $\varepsilon=0.25$ this gives $0.034$ — an ensemble that is 96.6% accurate from members that are 75% accurate. The gain comes from independence, not from any member being good.
Caveat worth stating: real members are correlated because they share training data, so the formula is a lower bound on the true error. Bagging and random forests exist precisely to inject randomness and decorrelate the members, making the bound closer to true.
D9. Ensemble error with $\varepsilon=0.4$, $n=11$
Full working in A4. The answer is $P(\ge6 \text{ errors}) = 0.2465$, i.e. 24.7% ensemble error.
D10. Key steps in boosting for ensemble prediction
Answer. With AdaBoost as the concrete instance:
- Initialise sample weights uniformly: $w_n^0 = 1/N$.
- For $m=1\ldots M$:
- Fit weak learner $y_m$ on the weighted data.
- Compute its weighted error $\epsilon_m = \dfrac{\sum_n w_n^m\mathbb{1}[y_m(x^{(n)})\neq t^{(n)}]}{\sum_n w_n^m}$.
- Compute its vote weight $\alpha_m=\ln\!\Big(\dfrac{1-\epsilon_m}{\epsilon_m}\Big)$.
- Re-weight each sample $w_n^{m+1}=w_n^m\exp\!\big(-\tfrac12 t^{(n)}\alpha_m y_m(x^{(n)})\big)$, then renormalise so the weights sum to 1.
- Predict with a weighted vote: $H(x)=\operatorname{sign}\big(\sum_m\alpha_m y_m(x)\big)$.
Why it works: the exponential factor is $e^{-\alpha/2}<1$ for a correctly classified sample and $e^{+\alpha/2}>1$ for a misclassified one, so each round shifts attention onto the hard examples. $\alpha_m$ is large when $\epsilon_m$ is small, giving reliable learners more say.
D11. Stacking versus bagging; the key steps of stacking
Answer.
| Bagging | Stacking | |
|---|---|---|
| Base models | the same algorithm | usually different algorithms |
| Training data | bootstrap subsets | the full training set |
| Combination | fixed rule (vote/average), equal weights | a learned meta-model |
| What is learned | base models only | base models and the combiner |
Key steps
- Train the base classifiers on the training set.
- Generate meta-features — run the training data through each base model and record its predictions as a new feature matrix.
- Train the meta-classifier on the meta-features against the true labels.
Critical detail: the meta-features must be generated from out-of-fold predictions (stacking with cross-validation). If you predict on the same rows the base models were fitted on, those predictions are near-perfect and the meta-model learns to trust whichever base model overfits hardest — leakage that destroys the generalisation benefit.
D12. The role of gating in Mixture of Experts; how it is calculated
Answer. The gate decides which expert to trust for this particular input, and by how much. Unlike bagging or boosting, the expert weights are not constant — they are a function of $x$.
$$y(x)=\sum_{m}g_m(x)\,y_m(x), \qquad g_m(x)=\frac{\exp\!\big(z_m(x)\big)}{\sum_i\exp\!\big(z_i(x)\big)}$$
A small learned network produces one logit $z_m(x)$ per expert; the softmax over those logits gives the weights. Softmax guarantees $g_m\ge0$ and $\sum_m g_m=1$, so the weights read as a probability distribution over experts — the model softly selects a region of feature space.
Why softmax rather than argmax: softmax is differentiable, so the gate can be trained end-to-end with the experts by gradient descent. A hard argmax has zero gradient almost everywhere and cannot be trained this way.
Contrast with stacking: stacking feeds all inputs through all models globally and learns a fixed combiner; MoE assumes experts specialise in localised regions and lets the combiner vary with the input.
D13. What is an activation function? Its role
Answer. An activation function is a non-linear function applied to the weighted sum inside each neuron:
$$a = g(w^Tx+b)$$
Desired properties: non-linear, easy to compute, differentiable, bounded output.
Role
- Non-linear representational power. Without it, a stack of linear layers collapses: $W_2(W_1x)=(W_2W_1)x$ is just another linear map, so depth buys nothing. The activation is what makes deep networks strictly more expressive than linear models.
- Output shaping. Sigmoid/softmax turn unbounded scores into probabilities; tanh centres them; ReLU sparsifies.
- Gradient flow. Because backpropagation multiplies by $g'(z)$, the choice of activation determines whether gradients vanish (sigmoid, tanh) or pass cleanly (ReLU for positive inputs).
Common choices: sigmoid $\frac{1}{1+e^{-z}}$ (binary output), tanh (hidden layer, zero-centred), ReLU $\max(0,z)$ (default hidden), Leaky ReLU (fixes dying ReLU), softmax (multiclass output).
D14. Sigmoid versus softmax
Answer.
$$\sigma(z)=\frac{1}{1+e^{-z}} \qquad\qquad \text{softmax}(z)_i=\frac{e^{z_i}}{\sum_j e^{z_j}}$$
| Sigmoid | Softmax | |
|---|---|---|
| Classes | 2 (binary) | $>2$ (multiclass) |
| Units | 1 | $C$ |
| Output | independent probability | probabilities that sum to 1 |
| Interpretation | $P(y=1\mid x)$ | $P(y=c\mid x)$ |
| Pairs with | binary cross-entropy | categorical cross-entropy |
| Multi-label | yes — each label independent | no — classes are mutually exclusive, exactly one applies |
For $C=2$ they are equivalent: $\text{softmax}([z_0,z_1])_1=\sigma(z_1-z_0)$.
Which when: MNIST digit (0–9, one label per image) → softmax with 10 outputs. Chest X-ray "does this patient have COVID?" → sigmoid with 1 output. CIFAR-10 → softmax. Multiple simultaneous findings on one image → several independent sigmoids.
D15. Softmax computation
Full working in B4. Answer: $[0.0609, 0.1004, 0.0075, 0.8201, 0.0111]$, predicted class 4.
D16. Why do we care about model evaluation?
Answer. Three reasons, in the course's framing:
- To estimate generalisation performance — performance on future, unseen data. The training objective is only a proxy; low training error does not imply low test error.
- To increase predictive performance — evaluation lets you tune the learning algorithm and select the best-performing model from a hypothesis space.
- To identify the best algorithm for the problem — comparing candidate algorithms on a common, fair footing.
Practically, metrics also serve as a quantitative target to organise effort against, a way to measure progress over time, and a tool for interpreting why a model fails (which class is being confused with which).
E. Code — assignment notebooks
These two notebooks are the only assignment code in scope. The examiner's phrasing ("explain") means: what each block does, why it is written that way, and what the numbers mean.
E1. Assignment 1 — Linear classification on the diabetes screening dataset
Dataset. Kaggle diabetes_prediction_dataset (iammustafatz): 100,000 rows, 9 columns. The assignment strips gender and smoking_history, leaving 6 features (age, hypertension, heart_disease, bmi, HbA1c_level, blood_glucose_level) plus the binary target diabetes.
What the notebook does, block by block
1. Mount Drive and read the CSV
from google.colab import drive
drive.mount('/content/drive')
df = pd.read_csv('/content/drive/MyDrive/diabetes_prediction_dataset.csv')
2. Inspect before modelling — this is the graded part. The minimum inspection set the rubric expects:
df.shape
df.dtypes
df.isna().sum()
df.duplicated().sum()
df.describe().T
Then a written paragraph. On this dataset the facts are: 0 missing values, 3,854 duplicate rows, and a label split of 91,500 / 8,500 = 91.5% / 8.5%, an imbalance ratio of 10.76 : 1.
3. Label distribution — and the metric consequence. Because the majority class is 91.5%, a constant "no diabetes" predictor scores 0.9166 accuracy while being useless. That is why accuracy alone is the wrong metric here and the assignment grades F1 and ROC.
4. Scatter plot of two features. bmi versus HbA1c_level, coloured by label. The visible structure: positives cluster at high HbA1c, and BMI separates weakly within each HbA1c band. HbA1c means are 6.93 (positive) versus 5.40 (negative) — the single most informative feature.
5. Two-feature model. X = df[['bmi','HbA1c_level']], train_test_split(test_size=0.25, random_state=99), LogisticRegression(), fit, predict.
6. Decision boundary. DecisionBoundaryDisplay.from_estimator(...) on a grid derived from X_train, with both train and test points plotted in two panels.
7. Metrics. Confusion matrix → F1; ROC curve from predict_proba; then the same for all six features.
The verified numbers (random_state = 99)
| Metric | Baseline (majority) | 2 features | 6 features |
|---|---|---|---|
| Accuracy | 0.9166 | 0.9439 | 0.9616 |
| Precision (class 1) | 0.0000 | 0.9032 | 0.8628 |
| Recall (class 1) | 0.0000 | 0.3669 | 0.6422 |
| F1 (class 1) | 0.0000 | 0.5218 | 0.7363 |
| Macro F1 | 0.4782 | 0.7460 | 0.8578 |
| ROC-AUC (proba) | 0.5000 | 0.8843 | 0.9627 |
Confusion matrices: 2F [[22833, 82], [1320, 765]]; 6F [[22702, 213], [746, 1339]] (rows = actual negative/positive).
What the comparison means — this is the discussion the rubric wants:
- Adding four features raises accuracy by only 1.8 points but nearly doubles recall (0.367 → 0.642) and raises F1 from 0.52 to 0.74. Accuracy badly understates the improvement because the majority class dominates it.
- The 2-feature model has higher precision but far lower recall — it only fires when very confident. The 6-feature model trades a little precision (0.90 → 0.86) for 275 fewer false negatives. In a screening context that is the right trade.
- The decision boundary is linear, so with only
bmiandHbA1cthe model cannot express "high HbA1c matters only if BMI is also high". The six-feature model is still linear, but in a richer space.
The three bugs that cost marks in this notebook
1. The np.diag ordering bug. The lecture notebook computes
FP = conf.sum(axis=0) - np.diag(conf)
TP = np.diag(conf)
which assumes class 0 is positive. Here class 1 is, so np.diag returns [TN, TP] and the F1 array is [F1_class0, F1_class1], unlabelled. Worse, if the six-feature block reuses the two-feature conf variable, the reported numbers match neither model. Fix:
TN, FP, FN, TP = confusion_matrix(y, p, labels=[0,1]).ravel()
and cross-check against f1_score(y, p).
2. ROC from hard labels. roc_curve(y, y_pred) where y_pred is 0/1 gives a three-point curve. Use y_prob = model.predict_proba(X)[:,1]. Both can be plotted, but they must be labelled — the hard-label "AUC" is just balanced accuracy at one threshold.
3. Histogram of the wrong variable. A "label distribution" plot that histograms a feature is a named deduction. Plot Y_train and Y_test separately; if you also plot features, use density=True, alpha=0.5 and retitle the axes.
E2. Assignment 2 — MNIST digits with PCA + linear and RBF SVM
Task. Three objectives: (1) PCA to reduce dimensionality and select the top $k$ components by 3-way holdout and cross-validation; (2) linear (soft-margin) SVM, selecting $C$ by both protocols; (3) RBF SVM, selecting $C$ and $\gamma$ by both protocols.
What the notebook does
1. Load MNIST.
trainset = datasets.MNIST('./data', train=True, download=True)
X_train = np.array([np.array(img) for img, _ in trainset]).reshape(-1, 28*28)
y_train = np.array([label for _, label in trainset])
# (60000, 784) and (60000,)
Pixel values are 0–255; normalise to $[0,1]$ by dividing by 255.
2. PCA in pure NumPy — the assignment forbids sklearn.decomposition.PCA, so the eigen-decomposition is written out:
Xc = X_train - X_train.mean(axis=0) # centre
cov = np.cov(Xc, rowvar=False) # 784 x 784
eigvals, eigvecs = np.linalg.eigh(cov) # symmetric -> eigh
idx = np.argsort(eigvals)[::-1] # descending
eigvals, eigvecs = eigvals[idx], eigvecs[:, idx]
ratio = np.cumsum(eigvals) / eigvals.sum() # cumulative variance
k = int(np.searchsorted(ratio, 0.90) + 1) # first k crossing 90%
W = eigvecs[:, :k]
X_pca = Xc @ W
Verified: $k = \mathbf{87}$ components reach 90.01% of the variance. PC1 alone is 9.70%; the first ten together are 48.81%. On a 60,000×784 covariance, the covariance takes ~4.6 s and the eigendecomposition ~0.4 s.
3. The three-way split. From the 60,000 training images: train_test_split(X, y, test_size=0.10, stratify=y) → 54,000 train / 6,000 validation. The 10,000 MNIST test images stay untouched.
4. Model selection, two ways.
3-way holdout — fit on the 54,000, score on the 6,000 validation set, per candidate hyperparameter. 5-fold CV — KFold(n_splits=5) over the combined 60,000, cross_val_score averaging.
5. Final test evaluation, once.
The verified results
| Model | Selection | Best settings | Test accuracy | Errors |
|---|---|---|---|---|
| Linear SVM | 3-way holdout | $C=0.1$ | 94.37% | 563 |
| Linear SVM | 5-fold CV | $C=0.1$ | 94.27% | — |
| RBF SVM | 3-way holdout | $C=10$, $\gamma=0.01$ | 98.41% | 159 |
| RBF SVM | 5-fold CV | $C=10$, $\gamma=0.01$ | 98.40% | — |
Linear validation accuracies: 0.9335 / 0.9407 / 0.9407 for $C = 0.01 / 0.1 / 1$. CV accuracies: 0.9349 / 0.9384 / 0.9382 ($\pm\approx0.003$).
What to say about it in an exam
- PCA before SVM is doing two jobs: it removes the 784-dimensional redundancy (many pixels are near-constant) and it makes the kernel computation cheaper, since RBF cost scales with $d$. 87 of 784 dimensions retain 90% of the variance — a 9× reduction.
- Holdout and CV agree, which is the reassuring result: within ±0.1% for both models. That agreement is itself evidence that 6,000 validation points are enough here.
- The RBF kernel is worth 4 points of accuracy over linear (98.4 vs 94.4) because digit classes are not linearly separable in pixel space — the same argument as XOR in the kernel lecture.
- $\gamma$ matters more than $C$. The grid shows the corner $C=0.01$, $\gamma=0.1$ collapsing to ~31% accuracy (predicting almost everything as one class), while changing $C$ at fixed $\gamma$ moves accuracy by less than a point. That is the single most interesting sentence you can write about this experiment.
- Runtime is roughly 2 hours single-threaded if the notebook is run as written — worth mentioning as an honest limitation.
F. Code — practice / example notebooks
Nine practice notebooks, one per topic. For each: what the pipeline is, the numbers it produces, and the one thing an examiner would ask you to explain.
F1. Linear-Classification.ipynb — Iris, logistic regression
Pipeline. datasets.load_iris() → inspect keys/shapes → features = iris['data'], labels = iris['target'] → label histogram → scatter of two features → train_test_split(test_size=0.25) → LogisticRegression() → decision boundary → metrics.
Iris facts: 150 samples, 4 features, 3 classes, exactly 50 per class, labels already 0/1/2.
Verified results (first two features, sepal length/width, unseeded split):
- Accuracy 100% on the 38-sample test set
- Confusion matrix
[[14, 0], [0, 24]] - F1 array
[1.0, 1.0] - ROC-AUC
1.0
Note the confusion matrix has only 2×2 entries even though the data has 3 classes: the split happened to leave only setosa and versicolor in the test set. That is worth pointing out — a 3-class problem printed a 2-class matrix because one class was absent from the test fold, which is exactly the failure mode W5L3 warns about with unstratified splits.
The thing to explain: the ROC curve here is built from roc_curve(Y_test, Y_pred) with hard labels, so it is a three-point staircase. Its AUC of 1.0 is really "accuracy is 100% at the default threshold", not a threshold-independent ranking measure. If asked to improve it, use predict_proba.
F2. Linear-Regression.ipynb — diabetes progression, BMI only
Pipeline. np.loadtxt the raw .tab.txt → 10 features + target → X = features[:, 2].reshape(-1,1) (BMI only) → train_test_split(test_size=0.25, random_state=999) → LinearRegression() → metrics.
Verified results:
- Coefficient 9.942, intercept −106.475
- MSE 2976.43, $R^2$ 0.4197, max error 121.05
The thing to explain: $R^2 = 0.42$ means BMI alone explains 42% of the variance in disease progression. The slope says each +1 in the standardised BMI units moves the score by ~9.9. That is a real effect but a weak model — which is the motivation for adding the other nine features, and later for regularisation.
Code detail worth knowing: the target column is diab[:,10] because the file has 11 columns and the last one is the response; feature_names, diab = diab[0,:10], diab[1:].astype('float') strips the header row and converts the rest to float in one line.
F3. kNN-DecisionTree.ipynb — the comparison notebook
Pipeline. Same Iris load and split as F1, then two classifiers on the same two features, each with its own decision-boundary plot.
Verified results (default random split, 38 test samples):
| Model | Accuracy | Confusion matrix | F1 per class |
|---|---|---|---|
| kNN, $k=3$ | 71.05% | [[14,0,0],[0,7,7],[0,4,6]] | 1.00 / 0.56 / 0.52 |
| Decision tree (default) | 68.42% | [[14,0,0],[0,4,5],[0,7,8]] | 1.00 / 0.40 / 0.57 |
The thing to explain: both models nail setosa (F1 = 1.0) — that class is linearly separable on sepal length/width — and both struggle on versicolor-virginica, which overlap in this 2-D projection. The tree does slightly worse overall because a fully-grown unpruned tree overfits the 112 training points and produces axis-aligned rectangles that cut through the overlap region.
That is the entire pedagogical point: on a small dataset, a default unpruned decision tree is not automatically better than k-NN, and the decision boundary plot is how you see why.
F4. SVM-classification.ipynb — linear SVM, then kernels
Three parts.
Part 1 — binary (versicolor vs virginica, X[50:], random_state=9999): SVC(kernel='linear') gives 100% accuracy, confusion [[14,0],[0,11]], F1 [1.0, 1.0]. The decision-boundary plot also scatters SVM_Model.support_vectors_ with marker='+' — that is the visual proof that only the support vectors determine the boundary.
Part 2 — 3-class: same kernel on all 150 samples, 112/38 split. Accuracy drops because setosa-versicolor-virginica is not linearly separable in 2-D.
Part 3 — the XOR experiment, which is the part worth explaining. A synthetic 200-point XOR set, then:
SVC(kernel='linear', C=0.1/1/10/100)→ four decision surfaces, all straight lines regardless of $C$. Increasing $C$ only tilts the line; it cannot bend it. That is the demonstration that $C$ controls regularisation, not model complexity.SVC(kernel='poly', degree=2)→ a curved boundary that separates the quadrants.SVC(kernel='rbf', gamma=0.1)→ a smooth closed region per cluster.- The 3×3 grid of $(C,\gamma)\in\{0.01,1,100\}\times\{0.1,1,10\}$ → the visual proof that $\gamma$ dominates: at small $\gamma$ the boundary is almost linear; at large $\gamma$ it wraps individual points.
The thing to explain: why does C not fix XOR? Because $C$ penalises margin violations in the given feature space. If no straight line can separate the classes, a large $C$ just picks the least-bad straight line. Only a change of feature space — a kernel — can make the problem separable.
F5. model-evaluation.ipynb — every validation scheme, on one dataset
Pipeline. All four Iris features → SVM → then the same model under five different evaluation protocols.
Verified results:
| Protocol | Setting | Result |
|---|---|---|
| Single holdout | test_size=0.25, stratify=y | accuracy 0.9737 |
| Repeated holdout | $k=50$, test_size=0.5, stratified | mean 0.976 |
| 3-way holdout | train 106 / val 6 / test 38 | val 0.833, test 0.947 |
| 5-fold CV (kNN) | KFold(n_splits=5) | folds [1.0, 1.0, 0.833, 0.933, 0.8] |
| CV hyperparameter sweep | $k\in\{3,5,\dots,15\}$ | best 0.920 at $k=7$ and $k=9$ |
The thing to explain — and this is the best single example in the course: the 3-way holdout validation accuracy is 0.833 while the test accuracy is 0.947. The validation set had only 6 samples, so a single misclassification moves it by 16.7 points. That is not a broken model; it is a demonstration that a validation set can be too small to be informative, and it is why $k$-fold CV exists.
Also worth noting: the fold accuracies span 0.80 to 1.00, a spread of 20 points on a 150-sample dataset. Reporting only the mean (0.913) without the spread would overstate your confidence.
F6. Overfitting&Regularization.ipynb — ridge, lasso, and a PyTorch MLP
Three parts.
1. Ridge on the diabetes regression. 10 features, test_size=0.3, random_state=999.
| Model | MSE | $R^2$ |
|---|---|---|
LinearRegression() | 2537.22 | 0.5236 |
Ridge(alpha=0.05) | 2507.74 | 0.5291 |
The thing to explain: ridge improves test performance while (by construction) fitting the training data slightly worse. The gain is small — 1.2% on MSE — because the unregularised model was only mildly overfitting on 309 samples × 10 features. Regularisation helps in proportion to how much variance there is to remove; with $N \gg d$ there is little.
2. L2-regularised logistic regression under severe data scarcity. test_size=0.9 leaves only 15 training samples for 4 features and 3 classes.
| Model | Test accuracy |
|---|---|
LogisticRegression() | 95.56% |
LogisticRegression(C=10, penalty='l2') | 97.78% |
Note the direction: larger C here is less regularisation, and it does better — because with 15 samples the default $C=1$ is over-regularising.
3. A PyTorch MLP on the same regression task.
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(10, 20)
self.fc2 = nn.Linear(20, 1)
def forward(self, x):
return self.fc2(F.relu(self.fc1(x)))
batch_size=8, MSELoss, Adam(lr=0.01, weight_decay=1e-2), 100 epochs. Parameter count: $(10\times20+20) + (20\times1+1) = 220+21 = 241$.
Result: MSE 2473.15, $R^2$ 0.5356 — slightly better than ridge.
The thing to explain: weight_decay=1e-2 in Adam is L2 regularisation; it adds $\lambda\|w\|^2$ to the loss. So the three parts of this notebook are the same idea in three costumes: explicit penalty (ridge), implicit penalty via C (logistic), and implicit penalty via weight_decay (neural network).
F7. Clustering.ipynb — k-means, DBSCAN, agglomerative, segmentation
Pipeline. make_moons(n_samples=1000, noise=0.05, random_state=0) — two interleaving crescents, which is the standard non-convex test case.
| Method | Call | What happens |
|---|---|---|
| k-means | KMeans(n_clusters=2) | cuts both crescents in half — the classic failure |
| DBSCAN | DBSCAN(eps=0.2, min_samples=50) | recovers the two crescents correctly |
| Agglomerative | AgglomerativeClustering(metric='euclidean', linkage='complete') | also recovers them |
| Dendrogram | linkage(X[:10], method='centroid') | merge history for 10 points |
The thing to explain: this one figure set is the k-means-versus-DBSCAN answer. k-means assumes convex, spherical clusters and assigns every point to the nearest centroid, so a crescent — which is convex in neither direction — gets split. DBSCAN works from local density, so a crescent is one connected high-density region regardless of its shape.
Image segmentation part. skimage.data.astronaut() → slic(img, n_segments=20) (a k-means-based superpixel method) → and separately data.coins() reshaped to (-1,1) with KMeans(n_clusters=3), reshaped back to 303×384. The second is the clean demonstration that each pixel's intensity is a 1-D feature and clustering thresholds it — segmentation is clustering where the "samples" are pixels.
F8. dimensionality-reduction.ipynb — PCA on three different data types
Three parts, one method.
1. Breast cancer, 569×30. StandardScaler → PCA(n_components=5) → 569×5. KNN before: 0.93; after: 0.97. 5 of 30 components carry ~90% of the variance; about half the features are nearly uninformative.
Also implemented from scratch with np.cov + np.linalg.eig to show the explained-variance curve matches sklearn's.
The thing to explain: why does accuracy improve after throwing away 25 dimensions? Because those dimensions are mostly noise; KNN's Euclidean distance is diluted by 25 near-constant coordinates, so removing them sharpens the neighbourhood structure. Dimensionality reduction is not only compression — it is denoising.
2. 8×8 digits, 1797×64 → 2. PCA(n_components=2) then KNN. Scatter of the two components coloured by digit shows partial class separation; KNN accuracy is 0.61 with only two components — a useful lower bound that motivates increasing $k$.
3. MRI compression. nibabel example 4-D volume, shape (128, 96, 24), sliced to a 96×128 image. PCA(n_components=16) on one slice → 96×16, then inverse_transform and compare.
| Compression | MSE |
|---|---|
| One slice, 16 components (96×128 → 96×16) | 533.18 |
| Whole volume, 16 components (24×2304 → 24×16) | 180.98 |
The thing to explain — subtle and worth a mark: compressing the whole volume jointly does better than compressing one slice alone, because the components are shared across slices and each slice borrows structure from the others. Same latent dimension, more data to estimate it from.
F9. Ensemble-Methods.ipynb — every ensemble, on breast cancer
Pipeline. Breast cancer 569×30, train_test_split(test_size=0.25, stratify=y, random_state=9999) → 426/143.
| Method | Code | Note |
|---|---|---|
| Voting (hard) | VotingClassifier([DTree, MLP, kNN], voting='hard') on the first 2 features | decision boundaries in a 2×2 panel |
| Bagging | BaggingClassifier(SVC(kernel='linear'), n_estimators=20) | same learner, 20 bootstrap samples |
| Random forest | RandomForestClassifier(max_depth=5) | plus plot_tree(RF.estimators_[0]) |
| AdaBoost | AdaBoostClassifier(n_estimators=100) | sequential re-weighting |
| Stacking | mlxtend.StackingClassifier([kNN, DTree, SVC], meta=LogisticRegression) | 5-fold CV comparison |
| Mixture of experts | 5 SVCs on 80% subsamples, softmax gate | manual implementation |
Verified stacking result (features 2:4, 5-fold CV):
KNN 0.86 (±0.03)
Decision Tree 0.87 (±0.04)
SVM 0.89 (±0.04)
StackingClassifier 0.88 (±0.03)
The thing to explain: the stack did not beat the best base model (0.88 vs SVM's 0.89). That is not a failure of stacking — it is a demonstration that stacking only helps when the base models are individually strong and make different errors. With only 2 features and 426 samples, the three models are highly correlated, so there is little diversity to exploit. This is the same lesson as the binomial formula: without diversity there is no gain.
Also note the notebook contains a deliberate-looking NameError (accuracy_score used before import) and a ValueError in the decision-region plot (a classifier fitted on 30 features then plotted on 2). Those are real bugs in the practice notebook — if asked "what is wrong with this cell?", that is the answer.
Quick reference — the numbers to have memorised
| Quantity | Value |
|---|---|
| Confusion-matrix F1 (practice Q1) | Positive 0.829, Negative 0.821 |
Entropy of A A B C A A B C C A C A | 1.459 bits |
| IG on the 4-row table | 0.3113 for all three features (tie) |
| Ensemble error, $n=11$, $\varepsilon=0.4$ | 0.2465 (75.35% accurate) |
| Ensemble error, $n=11$, $\varepsilon=0.25$ (lecture) | 0.034 |
| Softmax of $[0.6,1.1,-1.5,3.2,-1.1]$ | [0.061, 0.100, 0.007, 0.820, 0.011], class 4 |
| Neuron output, $w\cdot x=-3.56$ | sigmoid 0.0277, ReLU 0, tanh −0.9984 |
| Parameters, 3→4→4→1 network | 41 (16 + 20 + 5), 9 neurons |
| Margin | $2/\|w\|$ |
| AdaBoost $\alpha_m$ | $\ln\big((1-\epsilon_m)/\epsilon_m\big)$ |
| MoE gate | softmax over expert logits |
Every formula on this page was read off the lecture slides themselves, not reconstructed. Where the slide gave a worked value (entropy 0.88, ensemble 0.034, network 26 parameters) it is quoted as given; where the practice sheet supplied its own numbers, the working is shown in full above.