Everything except CNNs

Review and practice

First the three long-answer problem types, because that is where the marks are. Then a fast revision sheet for every topic on the list, the traps hiding in the notes, a short-answer bank, and a 62-question MCQ drill.

What the exam will probably look like

The format is 12 multiple-choice questions plus 2 or 3 problems you solve by hand. The review sheet contained exactly three problems, and two of them are the same types as Quiz 2. Expect the same three with new numbers.

Likely problemSeen before inWhat earns the marks
1 · Computational graph and backpropQuiz 2, review sheet, MLP slidesA drawn graph, every forward value, every backward gradient, final numbers
2 · Weight-matrix shapesQuiz 2, review sheetCorrect shape for each layer, with the bias counted the way the question says
3 · Softmax and cross-entropyReview sheet, single-layer notesSoftmax probabilities, then the loss with natural log
From the Quiz 2 grading key

Any reasonable graph layout was accepted. Marks were lost when values were not shown, and partial credit was given for a correct method with a wrong number. So write every intermediate value, even the obvious ones.

Problem type 1 · Computational graph and backprop

The method, every time

  1. Break the expression into single operations. One node per operation, innermost first. Give each intermediate a name (a, b, c…).
  2. Forward pass, left to right. Write each value on its edge.
  3. Backward pass, right to left. Start with 1 at the output. At each node:
    gradient on an input = upstream gradient × local derivative.
  4. Add at branches. If a variable feeds several nodes, its gradient is the sum over all those paths.
  5. Sanity-check with algebra if you have a minute: simplify the function for the active branch and differentiate directly.

Local derivatives to know cold

NodeLocal derivativeHow to remember it
\(a + b\)1 to each inputDistributor: passes the gradient through unchanged
\(a - b\)\(+1\) to \(a\), \(-1\) to \(b\)Flips the sign on the subtracted input
\(a \cdot b\)\(b\) to \(a\), and \(a\) to \(b\)Swap: each input gets the other one’s value
\(a / b\)\(1/b\) to \(a\), and \(-a/b^2\) to \(b\)The denominator’s gradient is negative
\(\max(a, b)\), \(\min(a, b)\)1 to the selected input, 0 to the otherRouter: only the winner gets the gradient
\(\text{ReLU}(z)\)1 if \(z > 0\), else 0A gate that is open for positive inputs
\(\sigma(z)\)\(\sigma(z)\,(1 - \sigma(z))\)Uses the output you already computed
\(\tanh(z)\)\(1 - \tanh^2(z)\)
\(e^{x}\)\(e^{x}\)Its own output
\(1/x\)\(-1/x^2\)
\(x^2\)\(2x\)
\(\ln x\)\(1/x\)
\(c \cdot x\), \(x + c\)\(c\), and 1Constants

Worked example 1 · the review-sheet problem

Review sheet, Problem 1 \[ f(x, y) = (x \cdot y)\cdot \min\!\left(\frac{x}{y},\; x\right), \qquad x = 20,\; y = 2 \]

Draw the graph, show all forward values and backward gradients, and find \(\partial f/\partial x\) and \(\partial f/\partial y\).

Forward. Name the pieces: \(a = x\cdot y\), \(b = x/y\), \(c = \min(b, x)\), \(f = a \cdot c\).

NodeComputationValue
\(a = x \cdot y\)20 × 240
\(b = x / y\)20 ÷ 210
\(c = \min(b, x)\)min(10, 20), so b is selected10
\(f = a \cdot c\)40 × 10400

Backward. Start with \(\partial f/\partial f = 1\) and walk right to left.

GradientLocal derivative× upstreamValue
\(\partial f/\partial a\)multiply: the other input, \(c = 10\)× 110
\(\partial f/\partial c\)multiply: the other input, \(a = 40\)× 140
\(\partial f/\partial b\) (through min)1, because b was the smaller one× 4040
x through min0, because x was not selected× 400
x through \(a\)\(y = 2\)× 1020
y through \(a\)\(x = 20\)× 10200
x through \(b\)\(1/y = 0.5\)× 4020
y through \(b\)\(-x/y^2 = -5\)× 40−200

Add the branches.

\[ \frac{\partial f}{\partial x} = 20 + 20 + 0 = \mathbf{40} \qquad\qquad \frac{\partial f}{\partial y} = 200 + (-200) = \mathbf{0} \]
Algebra check

Here \(x/y < x\), so the min picks \(x/y\) and \(f = xy \cdot \frac{x}{y} = x^2\). Then \(\partial f/\partial x = 2x = 40\) and \(\partial f/\partial y = 0\). It matches. A zero answer is not a mistake here.

Worked example 2 · the Quiz 2 problem

Quiz 2, Exercise 1 \[ y = \text{ReLU}(w_1 x_1 + w_2 x_2 + b), \qquad x_1 = 2,\; x_2 = 1,\; w_1 = 1,\; w_2 = 0.5,\; b = 1 \]

Forward: \(1\cdot 2 = 2\), \(0.5 \cdot 1 = 0.5\), sum \(= 2.5\), plus bias \(= 3.5\), ReLU \(= 3.5\). Backward: ReLU passes 1 because \(3.5 > 0\); both add nodes pass 1 along; each multiply node hands every input the other input.

\[ \frac{\partial y}{\partial w_1} = x_1 = 2 \qquad \frac{\partial y}{\partial w_2} = x_2 = 1 \qquad \frac{\partial y}{\partial b} = 1 \qquad \frac{\partial y}{\partial x_1} = w_1 = 1 \qquad \frac{\partial y}{\partial x_2} = w_2 = 0.5 \]

Worked example 3 · the sigmoid graph from the MLP slides

The slides walk through \(f(x, w) = \dfrac{1}{1 + e^{-(w_0 x_0 + w_1 x_1 + w_2)}}\) with \(w_0 = 2,\; x_0 = -1,\; w_1 = -3,\; x_1 = -2,\; w_2 = -3\), one node at a time. Rework it once with the gradients hidden.

  • \(1/x\) node: local \(= -1/1.37^2 = -0.53\). So \(1.00 \times -0.53 = -0.53\).
  • \(+1\) node: local \(= 1\). Still \(-0.53\).
  • \(\exp\) node: local \(= e^{-1} = 0.37\). So \(-0.53 \times 0.37 = -0.20\).
  • \(\times(-1)\) node: local \(= -1\). So \(+0.20\).
  • Both add nodes pass \(0.20\) to every input, so \(\partial f/\partial w_2 = 0.20\).
  • Multiply nodes swap: \(w_0\) gets \(x_0 \times 0.20 = -0.20\), \(x_0\) gets \(w_0 \times 0.20 = 0.40\), \(w_1\) gets \(x_1 \times 0.20 = -0.40\), \(x_1\) gets \(w_1 \times 0.20 = -0.60\).
Shortcut

The four nodes \(\times(-1)\), exp, \(+1\), \(1/x\) together are just a sigmoid, and \(\sigma' = \sigma(1-\sigma) = 0.73 \times 0.27 \approx 0.20\). One step instead of four. Use the long way only if the question draws the graph that way.

Practice · do these on paper

Practice A · warm-up

\(f(x, y, z) = (x + y)\cdot z\) with \(x = -2,\; y = 5,\; z = -4\). Find all three partial derivatives.

Solution

Forward: \(q = x + y = 3\), \(f = q \cdot z = -12\).

Backward: \(\partial f/\partial q = z = -4\), \(\partial f/\partial z = q = 3\). The add node passes \(-4\) to both inputs.

\(\partial f/\partial x = -4\), \(\partial f/\partial y = -4\), \(\partial f/\partial z = 3\).

Practice B · same shape as the review problem, with max

\(f(x, y) = (x - y)\cdot \max\!\left(\dfrac{x}{y},\; y\right)\) with \(x = 10,\; y = 4\).

Solution

Forward: \(a = x - y = 6\); \(b = x/y = 2.5\); \(c = \max(2.5, 4) = 4\) (y is selected); \(f = a \cdot c = 24\).

Backward: \(\partial f/\partial a = c = 4\); \(\partial f/\partial c = a = 6\). The max sends 6 to \(y\) and 0 to \(b\), so nothing flows through the division.

  • x: through \(a\): \(4 \times 1 = 4\). Through \(b\): 0. Total 4.
  • y: through \(a\): \(4 \times (-1) = -4\). Through max: \(6\). Through \(b\): 0. Total 2.

Check: the active branch is \(f = (x - y)\,y = xy - y^2\), so \(\partial f/\partial x = y = 4\) and \(\partial f/\partial y = x - 2y = 2\).

Practice C · three inputs

\(f(x, y, z) = (x \cdot y + z)\cdot \max(y,\; z)\) with \(x = 3,\; y = -2,\; z = 4\).

Solution

Forward: \(a = xy = -6\); \(b = a + z = -2\); \(c = \max(-2, 4) = 4\) (z is selected); \(f = b \cdot c = -8\).

Backward: \(\partial f/\partial b = c = 4\); \(\partial f/\partial c = b = -2\). The add node passes 4 to both \(a\) and \(z\). The max sends \(-2\) to \(z\) and 0 to \(y\).

  • x: \(4 \times y = 4 \times (-2) =\) −8
  • y: \(4 \times x = 12\), plus 0 through max: 12
  • z: \(4\) through the add, plus \(-2\) through the max: 2
Practice D · a sigmoid neuron with a loss, then one update

\(z = w x + b\), \(a = \sigma(z)\), \(L = (a - y)^2\). Given \(x = 1,\; w = 2,\; b = -2,\; y = 1\). Find \(\partial L/\partial w\) and \(\partial L/\partial b\), then take one gradient-descent step with \(\alpha = 1\).

Solution

Forward: \(z = 2 - 2 = 0\); \(a = \sigma(0) = 0.5\); \(L = (0.5 - 1)^2 = 0.25\).

Backward:

  • \(\partial L/\partial a = 2(a - y) = -1\)
  • \(\partial a/\partial z = a(1 - a) = 0.25\), so \(\partial L/\partial z = -0.25\)
  • \(\partial L/\partial w = -0.25 \times x = \mathbf{-0.25}\) and \(\partial L/\partial b = -0.25 \times 1 = \mathbf{-0.25}\)

Update: \(w \leftarrow 2 - 1(-0.25) = 2.25\), \(b \leftarrow -2 - 1(-0.25) = -1.75\). Both move so that \(z\) grows and the output moves toward the target of 1.

Practice E · ReLU neuron with a squared loss

\(y = \text{ReLU}(w_1 x_1 + w_2 x_2 + b)\), \(L = (y - t)^2\). Given \(x_1 = 1,\; x_2 = 2,\; w_1 = 3,\; w_2 = -1,\; b = 0.5,\; t = 1\). Find the gradients of \(L\) with respect to \(w_1, w_2, b\), and the new weights after one step with \(\alpha = 0.1\).

Solution

Forward: \(z = 3 - 2 + 0.5 = 1.5\); \(y = 1.5\); \(L = 0.5^2 = 0.25\).

Backward: \(\partial L/\partial y = 2(y - t) = 1\). ReLU is open (\(z > 0\)), so \(\partial L/\partial z = 1\).

\(\partial L/\partial w_1 = x_1 = 1\), \(\partial L/\partial w_2 = x_2 = 2\), \(\partial L/\partial b = 1\).

Update: \(w_1 = 3 - 0.1 = 2.9\), \(w_2 = -1 - 0.2 = -1.2\), \(b = 0.5 - 0.1 = 0.4\).

Practice F · what if the ReLU is off?

Same neuron \(y = \text{ReLU}(w_1 x_1 + w_2 x_2 + b)\) with \(x_1 = 1,\; x_2 = 2,\; w_1 = 1,\; w_2 = -2,\; b = 1\). Find \(\partial y/\partial w_1\), \(\partial y/\partial w_2\), \(\partial y/\partial b\).

Solution

\(z = 1 - 4 + 1 = -2\), so \(y = \text{ReLU}(-2) = 0\). The local derivative of ReLU is 0 for a negative input, so the gradient is blocked: all three are 0.

This is the “dying neuron” problem. With zero gradient the weights do not update. Leaky ReLU keeps a small slope for negative inputs to avoid it.

Problem type 2 · Weight-matrix shapes

The rule

A weight matrix connects what comes into a layer to the neurons of that layer. One dimension is the number of inputs to the layer (plus 1 if the bias is folded in). The other is the number of neurons. The convention only decides which comes first. The number of training samples never appears in a weight shape.

ConventionShape of W for a layerBiasUsed in
\(\text{net} = XW\)(inputs + 1) × neuronsFirst row of W. X gets a column of 1s, so X is samples × (inputs + 1).Review sheet, Quiz 2
\(\text{net} = Wx + b\)neurons × inputsSeparate vector with one entry per neuronMLP slides (CIFAR-10), multi-layer handout

The check that catches mistakes: write the multiplication and make sure the inner dimensions agree. \((5 \times 8)(8 \times 9) \rightarrow 5 \times 9\).

Worked example · the review-sheet problem

Review sheet, Problem 2

Two-layer network. Layer 1: 9 neurons. Layer 2: 3 neurons. 5 training samples, each of dimension 7. \(\text{net} = XW\), bias in the first row of the weight matrix. Give the shape of each weight matrix.

LayerInputs + bias (rows)Neurons (columns)Weight matrixCheck
17 + 1 = 89W₁ : 8 × 9X (5×8) · W₁ (8×9) = 5×9
29 + 1 = 103W₂ : 10 × 3[1, H] (5×10) · W₂ (10×3) = 5×3

The input to layer 2 is the output of layer 1, which has 9 values per sample, plus the bias 1. The final output for the batch is 5 × 3. Total parameters: 72 + 30 = 102.

Worked example · the Quiz 2 problem

Three layers with 12, 8 and 4 neurons, 10 samples of dimension 6, \(\text{net} = XW\), bias at each layer.

LayerInputs + biasNeuronsAs (inputs+1) × neuronsAs written in the posted key
16 + 1 = 7127 × 1212 × 7
212 + 1 = 13813 × 88 × 13
38 + 1 = 949 × 44 × 9

Output for the whole batch: 10 × 4. ReLU and softmax change values, not dimensions. Each row holds 4 probabilities that sum to 1.

Trap: orientation

The Quiz 2 key printed the shapes neurons-first (12 × 7) even though the question said \(\text{net} = XW\), and the grading notes said either orientation was accepted. The review sheet is more specific: “bias is included in the first row”. A bias row has one entry per neuron, so rows = inputs + 1 and columns = neurons, which gives 8 × 9.

What to write: the shape, what the rows and columns mean, and the dimension check. For example: “W₁ is 8 × 9 (8 = 7 inputs + 1 bias row, 9 = neurons). X(5×8)·W₁(8×9) = 5×9.” That is correct under either reading.

Practice

Practice 1

Three-layer network: 16, 8 and 2 neurons. 32 samples, each of dimension 10. \(\text{net} = XW\), bias in the first row. (a) Shapes of W₁, W₂, W₃? (b) Shape of the output for the whole batch? (c) Total number of trainable parameters?

Solution
  • (a) W₁: (10 + 1) × 16 = 11 × 16. W₂: (16 + 1) × 8 = 17 × 8. W₃: (8 + 1) × 2 = 9 × 2.
  • (b) 32 × 2.
  • (c) 176 + 136 + 18 = 330.
Practice 2 · the other convention

A network uses \(a^{(l)} = f(W^{(l)} a^{(l-1)} + b^{(l)})\) with 4 inputs, one hidden layer of 5 neurons and 3 outputs. Give the shapes of W⁽¹⁾, b⁽¹⁾, W⁽²⁾, b⁽²⁾ and the total parameter count.

Solution

Here W is neurons × inputs and the bias is separate.

W⁽¹⁾: 5 × 4, b⁽¹⁾: 5. W⁽²⁾: 3 × 5, b⁽²⁾: 3. Total: 20 + 5 + 15 + 3 = 43.

Practice 3 · from the slides

CIFAR-10 images are 32×32×3. For the 3-layer network \(f(x) = W_3\,\text{act}(W_2\,\text{act}(W_1 x))\) with hidden sizes 512 and 128 and 10 classes, give the shape of each W.

Solution

Input dimension: 32 · 32 · 3 = 3072. The slides use \(Wx\) with no bias, so W is (this layer) × (previous layer).

W₁: 512 × 3072. W₂: 128 × 512. W₃: 10 × 128.

Practice 4 · backwards

Under \(\text{net} = XW\) with the bias in the first row, a network has W₁ of shape 6 × 4 and W₂ of shape 5 × 2. How many features does each sample have, and how many neurons are in each layer?

Solution

W₁ rows = features + 1 = 6, so 5 features. W₁ columns = 4 neurons in layer 1. W₂ rows = 4 + 1 = 5, which is consistent. W₂ columns = 2 neurons in layer 2.

Problem type 3 · Softmax and cross-entropy

The method

  1. Softmax turns the raw outputs \(z\) into probabilities: \[ \hat{y}_k = \frac{e^{z_k}}{\sum_j e^{z_j}} \]
  2. Cross-entropy compares them with the target \(y\): \[ L = -\sum_k y_k \,\ln(\hat{y}_k) \]
  3. If the target is one-hot, every term but one is multiplied by 0, so \(L = -\ln(\hat{y}_{\text{true class}})\).
Numbers and a shortcut

\(e \approx 2.718\), \(e^2 \approx 7.389\), \(e^3 \approx 20.09\), \(\ln 2 \approx 0.693\), \(\ln 3 \approx 1.099\).

Without a calculator, use \(\ln \hat{y}_k = z_k - \ln\!\big(\sum_j e^{z_j}\big)\). For two outputs that differ by 1, the probabilities are always \(\tfrac{1}{1+e} = 0.269\) and \(\tfrac{e}{1+e} = 0.731\).

Worked example · the review-sheet problem

Review sheet, Problem 3

The last layer has two nodes and its output is \(\begin{bmatrix}1\\2\end{bmatrix}\). Using softmax, compute the cross-entropy loss with the natural log.

Step 1, softmax. \(e^1 = 2.718\), \(e^2 = 7.389\), sum \(= 10.107\).

\[ \hat{y} = \left[\frac{2.718}{10.107},\; \frac{7.389}{10.107}\right] = [\,0.269,\; 0.731\,] \qquad \ln\hat{y} = [\,-1.313,\; -0.313\,] \]

Step 2, the loss. It depends on the desired output:

Desired outputLossValue
\([0, 1]\) (class 2 is correct)\(-\ln 0.731\)0.313
\([1, 0]\) (class 1 is correct)\(-\ln 0.269\)1.313
\([1, 2]\), exactly as printed on the sheet\(-(1\cdot\ln 0.269 + 2\cdot\ln 0.731) = 1.313 + 0.627\)1.940
Trap: the sheet’s target is not one-hot

The review sheet prints the desired output as \([1, 2]\), the same as the actual output. A real target for softmax is one-hot, so that looks like a placeholder. The method does not change: apply \(L = -\sum y_k \ln \hat{y}_k\) to whatever target the exam prints. If it is one-hot, only one term survives.

Practice

Practice 1

Network outputs \([2, 1, 0]\). The first class is the correct one. Find the softmax probabilities and the loss.

Solution

\(e^2 + e^1 + e^0 = 7.389 + 2.718 + 1 = 11.107\).

\(\hat{y} = [0.665,\; 0.245,\; 0.090]\). \(L = -\ln 0.665 =\) 0.408.

Shortcut: \(\ln \hat{y}_1 = 2 - \ln 11.107 = 2 - 2.408 = -0.408\).

Practice 2

Network outputs \([3, 1]\). The desired output is \([0, 1]\).

Solution

\(e^3 + e^1 = 20.086 + 2.718 = 22.804\). \(\hat{y} = [0.881,\; 0.119]\).

\(L = -\ln 0.119 =\) 2.127. The network was confident and wrong, so the loss is large. If the target had been \([1, 0]\), the loss would be only \(-\ln 0.881 = 0.127\).

Practice 3

A 3-class network outputs \([0, 0, 0]\). What is the loss, whichever class is correct?

Solution

Equal scores give equal probabilities, \(\tfrac13\) each. \(L = -\ln\tfrac13 = \ln 3 =\) 1.099. A network that knows nothing about \(K\) classes has loss \(\ln K\).

Practice 4 · no softmax needed

The predicted probabilities are \(\hat{y} = [0.6,\; 0.3,\; 0.1]\) and the true class is the first. Find the loss. Then find it for a binary classifier that outputs \(\hat{y} = 0.8\) when (a) \(y = 1\) and (b) \(y = 0\).

Solution

These already sum to 1, so do not apply softmax again. \(L = -\ln 0.6 =\) 0.511. This is the example in the single-layer notes.

Binary cross-entropy: \(L = -[\,y\ln\hat{y} + (1-y)\ln(1-\hat{y})\,]\).

  • (a) \(y = 1\): \(-\ln 0.8 =\) 0.223
  • (b) \(y = 0\): \(-\ln 0.2 =\) 1.609
If they ask for the gradient

For softmax followed by cross-entropy, \(\dfrac{\partial L}{\partial z} = \hat{y} - y\). In the review problem with target \([0, 1]\): \([0.269 - 0,\; 0.731 - 1] = [0.269,\; -0.269]\). The notes give the weight gradients as \(\dfrac{\partial L}{\partial W} = (\hat{y} - y)\,x^{\top}\) and \(\dfrac{\partial L}{\partial b} = \hat{y} - y\).

Other by-hand problems that could appear

Less likely than the three above, but each one is worked in the notes or was set as homework.

Perceptron update rule

\(\hat{y} = 1\) if \(z \ge 0\), else 0. For each example: \(w \leftarrow w + \eta\,(y - \hat{y})\,x\) and \(b \leftarrow b + \eta\,(y - \hat{y})\). Correct prediction means no change.

The notes train an AND gate from \(w = (0, 0),\; b = 0,\; \eta = 1\). Epoch 1:

InputTargetzŷResultw afterb after
(0, 0)001wrong, y − ŷ = −1(0, 0)−1
(0, 1)0−10correct(0, 0)−1
(1, 0)0−10correct(0, 0)−1
(1, 1)1−10wrong, y − ŷ = +1(1, 1)0

After epoch 1 the model is \(w = (1, 1),\; b = 0\). Test it: (0, 0) gives \(z = 0\), so ŷ = 1, which is wrong, so training continues. Note that \(z = 0\) counts as class 1.

The rest of the training (the “finish it” homework)
After epochwbUpdates made
1(1, 1)02
2(2, 1)−13
3(2, 1)−23
4(2, 2)−22
5(2, 1)−31
6(2, 1)−30, converged

Final model: \(z = 2x_1 + x_2 - 3\). Check: (0,0) → −3 → 0. (0,1) → −2 → 0. (1,0) → −1 → 0. (1,1) → 0 → 1. All four correct. It converges because AND is linearly separable.

One gradient-descent step for linear regression

Data from the notes: \((x, y) = (1, 2)\) and \((2, 4)\). Model \(z = wx + b\), start at \(w = 0,\; b = 0\), using the notes’ gradients \(\partial L/\partial w = \sum (z_i - y_i)\,x_i\) and \(\partial L/\partial b = \sum (z_i - y_i)\).

  • Predictions: \(z = 0, 0\). Errors: \(-2,\; -4\). Starting MSE \(= (4 + 16)/2 = 10\).
  • \(\partial L/\partial w = (-2)(1) + (-4)(2) = -10\). \(\partial L/\partial b = -6\).
  • With \(\alpha = 0.5\): \(w = 5,\; b = 3\). New predictions 8 and 13, MSE \(= 58.5\). The loss went up: overshoot.
  • With \(\alpha = 0.1\): \(w = 1,\; b = 0.6\). New predictions 1.6 and 2.6, MSE \(= 1.06\). The loss went down.
The lesson the notes draw

When you overshoot, the direction (the gradient) is fine and the step size is too large. The first thing to fix is the learning rate. Gradient descent has converged when the gradient is approximately 0.

Forward pass through a small network

A hidden layer lets a network solve XOR. One set of weights that works: \(h_1 = \text{ReLU}(x_1 + x_2)\), \(h_2 = \text{ReLU}(x_1 + x_2 - 1)\), \(y = h_1 - 2h_2\).

x₁x₂h₁h₂y = h₁ − 2h₂XOR
000000
011011
101011
112100

Single neuron with a step activation

The notebook exercises: design AND and OR, and evaluate a given neuron.

  • AND: \(w = (1, 1),\; b = -1.5\). Only (1, 1) gives \(z \ge 0\).
  • OR: \(w = (1, 1),\; b = -0.5\). Only (0, 0) gives \(z < 0\).
  • Evaluate \(z = 2x_1 - x_2 - 1\): (1, 0) → \(z = 1\) → 1.   (0, 2) → \(z = -3\) → 0.   (2, 1) → \(z = 2\) → 1.

Rewrite a loop with NumPy

Quiz 1 asked for this. The pattern is always: drop the index and apply the expression to the whole array.

# loop version
for i in range(len(A)):
    B[i] = A[i] ** 2 + 2 * A[i] + 1

# vectorized
B = A ** 2 + 2 * A + 1          # note ** for power, not ^
Loop that does…Vectorized form
sum of a[i] * b[i]np.dot(a, b)
sum of squaresnp.sum(A ** 2)
replace negatives with 0 (ReLU)np.maximum(0, A)
1 where A ≥ 0, else 0 (step)np.where(A >= 0, 1, 0)
sigmoid of every element1 / (1 + np.exp(-A))

For by-hand convolution and pooling problems, see the CNN page.

Revision · NumPy, broadcasting, ufuncs, vectorization

  • NumPy is an open-source Python package for multidimensional arrays, designed for scientific computing. Main class: ndarray.
  • All elements of an array must be the same type. An ndarray is not a Python list.
Attribute / functionGives
a.ndimnumber of dimensions
a.shapetuple with the size along each dimension
a.sizetotal number of elements
a.dtypetype of the elements
np.zeros((3,7)), np.ones((3,2))arrays of 0s or 1s with that shape
np.arange(0, 1.1, .2)like range, with a step: [0, 0.2, 0.4, 0.6, 0.8, 1.0]
np.linspace(.1, .7, 5)5 evenly spaced numbers including both ends
a.reshape(3, 2)same data, new shape
a.ravel()flattens to 1-D
Element-wise versus matrix product

Every arithmetic operator is element-wise, including * and /. The matrix product needs np.dot(a, b).

With a = [[1,2],[9,8]] and b = [[6,5],[2,4]]: a * b = [[6,10],[18,32]] but np.dot(a, b) = [[10,13],[70,77]]. And np.dot of two 2×3 arrays is an error, because the inner dimensions (3 and 2) do not match.

Universal functions (ufuncs) such as np.sin, np.cos, np.exp, np.sqrt operate element-wise on an array and return an array.

Broadcasting

Broadcasting is how NumPy does arithmetic between arrays of different shapes. Two rules:

  1. If the arrays have different numbers of dimensions, prepend 1s to the shape of the smaller one.
  2. An axis of size 1 is stretched (copied) to match the other array along that axis.

After that, every axis must match, otherwise it is an error. Line the shapes up from the right:

ShapesAfter rule 1Result
(2, 2, 3) + (3,)(2, 2, 3) + (1, 1, 3)(2, 2, 3), the notes’ example
(3, 1) * (3,)(3, 1) * (1, 3)(3, 3), the notes’ second example
(4, 3) + (3,)(4, 3) + (1, 3)(4, 3)
(4, 3) + (4,)(4, 3) + (1, 4)Error: 3 versus 4
(2, 1, 3) + (4, 1)(2, 1, 3) + (1, 4, 1)(2, 4, 3)
array + scalarthe scalar is applied to every element

Vectorization

Applying an operation to the whole array at once instead of looping. In the notes, np.dot on 10 million elements took about 9 ms and the Python loop about 3.2 s.

Trap: (5,) is not a column vector

np.random.randn(5) has shape (5,). Its transpose is the same thing, and np.dot(a, a.T) is a single number. Use np.random.randn(5, 1) to get a real 5×1 column: then a.T is 1×5, np.dot(a.T, a) is 1×1 and np.dot(a, a.T) is 5×5.

Revision · Measurement scales

Each scale keeps everything from the one before and adds one property.

ScaleIdentityOrderEqual intervalsTrue zeroValid operationsExamples from the notes
Nominal✓= ≠gender; red, green, blue; dog, cat, bird
Ordinal✓✓< >very unsatisfied … very satisfied; cold, warm, hot
Interval✓✓✓+ −temperature in °C; clock time (10:30 AM)
Ratio✓✓✓✓+ − × ÷height, weight, duration, age
  • Identity: each value has a unique meaning. Order: values can be ranked. Equal intervals: units along the scale are equal. True zero: zero means none of the quantity.
  • Nominal and ordinal are the two categorical types.
  • Interval has no true zero, so ratios mean nothing. Is 40 °C twice as hot as 20 °C? Convert to Fahrenheit (104 vs 68) and the “twice” is gone.
  • Why the scale matters: it decides which operations and statistics are valid. Pick the wrong one and you do arithmetic that has no meaning.
Quick drill: name the scale
ZIP code, jersey number, blood typeNominal (numbers used only as labels)
Letter grade A–F, shirt size S/M/L, finishing position in a race, education levelOrdinal
Calendar year, temperature in °F, time of dayInterval
Income, number of children, distance, temperature in kelvin, time taken to finishRatio

Revision · Machine learning and the neuron

  • AI ⊃ Machine learning ⊃ Deep learning. AI also includes rule-based systems, search and planning, and robotics.
  • Machine learning (Arthur Samuel, 1959): the ability to learn without being explicitly programmed. Machines learn patterns from data and make decisions on their own.
The four key components of any ML task

1. Data to learn from. 2. A model that transforms the data. 3. An objective function that measures how well the model is doing. 4. An optimization algorithm that adjusts the parameters to optimise the objective.

Kind of learningDataGoalExamples
SupervisedLabeled: features and an output labelPredict the correct output for new dataClassification, regression (house prices, medical imaging)
UnsupervisedUnlabeled: features onlyDiscover hidden patterns or groupingsClustering, customer segmentation, market-basket analysis
ReinforcementFeedback from an environmentAn agent learns a sequence of decisions from rewards and penaltiesGame playing, control
TaskWhat it does
ClassificationAssigns an input to one of k categories
RegressionPredicts a real-valued label
ClusteringGroups similar points without labels
Anomaly detectionFlags unusual events, such as credit-card fraud
Association rulesFinds “if X then Y” patterns among items

Biological neuron ↔ artificial neuron

BiologicalFunctionArtificial
Dendritesreceive signalsInputs
Synapsesconnection strengthWeights
Cell body (soma)integrates the signalsSummation
Axon hillockdecides whether to fireActivation function
Axontransmits the outputOutput

Anatomy of one neuron: inputs \(x_i\), weights \(w_i\) (importance of each input), bias \(b\) (shifts the activation), weighted sum \(z = w_1x_1 + \dots + w_nx_n + b\), activation function \(f\), output \(y = f(z)\).

TermMeansExamples
ArchitectureHow layers and neurons are organisedSingle-layer, two-layer, multi-layer / deep
TopologyHow neurons are connected and how data flowsFeed-forward, recurrent, convolutional
TypeCategory based on bothFNN, RNN, CNN, RBFN, GAN, autoencoder, ResNet

Revision · Single-layer networks

One layer of neurons connected directly to the inputs, feed-forward. They all compute \(z = w^{\top}x + b\) and differ only in the activation and the loss.

ModelActivationOutputLossTrained by
Linear regressionIdentity\(\hat{y} = z\), any real numberMSEGradient descent
PerceptronStep: 1 if \(z \ge 0\)0 or 1none (not differentiable)Perceptron update rule
Logistic regressionSigmoid\(P(y = 1 \mid x)\) in (0, 1)Binary cross-entropyGradient descent
Multiclass logisticSoftmaxK probabilities summing to 1Cross-entropyGradient descent

Key formulas

\[ \text{MSE: } L = \frac{1}{m}\sum_i (z_i - y_i)^2 \qquad \text{Binary CE: } L = -\big[\,y\ln\hat{y} + (1-y)\ln(1-\hat{y})\,\big] \qquad \text{CE: } L = -\sum_k y_k \ln\hat{y}_k \] \[ \text{Gradient descent: } w \leftarrow w - \alpha\,\nabla L(w) \qquad \text{Perceptron: } w \leftarrow w + \eta\,(y - \hat{y})\,x,\;\; b \leftarrow b + \eta\,(y - \hat{y}) \]
  • Decision boundary is \(z = 0\): a line for 2 inputs, a plane for 3. The bias shifts it; with no bias it must pass through the origin.
  • Gradients: linear regression uses \((z - y)\,x\); logistic regression uses \((\hat{y} - y)\,x\) with \(\hat{y} = \sigma(z)\). Same form, different prediction.
  • Logistic decision rule: class 1 if \(\hat{y} \ge 0.5\), which is the same as \(z \ge 0\).
  • Perceptron: the step function is not differentiable, so no gradient descent. It converges only if the data is linearly separable. An epoch is one full pass over the training set.
  • Why softmax for multiclass: K separate sigmoids do not sum to 1, which makes no sense when exactly one class is true. Softmax makes the outputs positive, summing to 1, and competing.
  • One-hot encoding: class k of K becomes a vector of 0s with a 1 in position k. Then \(L = -\ln(\hat{y}_{\text{true}})\). It punishes confident wrong predictions heavily.
  • Prediction for multiclass: compute softmax, take the argmax.
  • Chain rule: \(\dfrac{dy}{dx} = \dfrac{df}{dg}\cdot\dfrac{dg}{dx}\). Example: \(y = \sin(x^2) \Rightarrow \cos(x^2)\cdot 2x\).
  • Can solve: linearly separable problems (AND, OR, linear and logistic regression). Cannot solve: XOR.

Revision · Multi-layer networks and activations

Five limitations of a single-layer network

  1. It can only model linear functions (works for AND and OR, fails for XOR).
  2. It cannot capture complex patterns: no curves, clusters or complex boundaries.
  3. Limited feature extraction: no hidden layers, so no intermediate representations.
  4. Limited capacity: few parameters.
  5. Sensitive to noisy data: generalises poorly on noisy or overlapping data.

Hidden layers

A hidden layer is any layer between the input and the output layer. It contains inputs, weights, a bias and an activation function, and performs intermediate computations. Hidden layers matter because they introduce non-linearity, learn hierarchical features, increase expressiveness, enable complex decision boundaries and make deep learning possible.

\[ a^{(l)} = f\big(W^{(l)} a^{(l-1)} + b^{(l)}\big) \qquad \text{stacking layers} = \text{composing functions} \]

Activation functions

FunctionFormulaRangeDerivativeRemember
Sigmoid\(\dfrac{1}{1+e^{-z}}\)(0, 1)\(\sigma(1-\sigma)\), at most 0.25Smooth; vanishing gradients; not zero-centred; slow in deep nets; used in the output layer for binary classification
Tanh\(\dfrac{e^{z}-e^{-z}}{e^{z}+e^{-z}}\)(−1, 1)\(1-\tanh^2\)Zero-centred; better than sigmoid for hidden layers; still has vanishing gradients
ReLU\(\max(0, z)\)[0, ∞)1 if \(z>0\), else 0Cheap; reduces vanishing gradients; most common in hidden layers; can suffer from dying neurons
Leaky ReLU\(z\) if \(z \ge 0\), else \(\alpha z\)(−∞, ∞)1 or \(\alpha\)Small gradient for negatives, so it prevents dying neurons
Softmax\(\dfrac{e^{z_k}}{\sum_j e^{z_j}}\)(0, 1), sums to 1Output layer for multi-class
Step / identity1 if \(z \ge 0\); or \(z\){0, 1}; anyPerceptron; linear regression
Why non-linearity is essential

Without an activation, \(W_2(W_1 x) = (W_2 W_1)x = Wx\). Any stack of linear layers collapses into one linear layer, however deep. The activation is what lets a network learn curves and solve XOR.

Vanishing gradient: backprop multiplies one local derivative per layer. Sigmoid and tanh are flat for large \(|z|\), so those derivatives are close to 0, and after many layers the product is almost nothing. The early layers stop learning. ReLU’s derivative is exactly 1 for positive inputs, so the gradient survives.

From the MLP slides

  • Linear classifier: \(f(x) = Wx\). 2-layer network: \(f(x) = W_2\,\text{act}(W_1 x)\). 3-layer: \(f(x) = W_3\,\text{act}(W_2\,\text{act}(W_1x))\). “2-layer” means two layers of weights.
  • CIFAR-10: \(32\times32\times3 = 3072\) inputs, 10 classes. 2-layer: 3072 → 128 → 10, “learn 128 shared templates instead of 10 separate ones”. 3-layer: 3072 → 512 → 128 → 10.
  • MLP = fully connected network.
  • Traditional vision pipeline: hand-designed features (such as a histogram of gradients), then a linear classifier. Neural networks learn the features automatically, and learn features and classifier end-to-end, using multiple layers.

Types of layered architectures

ArchitectureKey points
Single-layerNo hidden layers; linear boundaries only; cannot solve XOR
MLPFully connected layers; non-linear activations; universal function approximator
CNNDesigned for images; local receptive fields; shared weights; Input → Conv → Activation → Pool → Fully connected → Output
RNNFeedback loops; hidden-state memory; sequential data; trained by backpropagation through time
TransformerStacked attention blocks: multi-head attention, feed-forward sub-layer, residual connections, layer normalization

Revision · Back-propagation theory

  • Training updates each layer with SGD: \(W_k \leftarrow W_k - \alpha\,\dfrac{\partial e}{\partial W_k}\). Backprop is how you get \(\partial e/\partial W_k\) for every layer.
  • It is the chain rule, applied from the output back to the input.
  • For any layer: \(\dfrac{\partial e}{\partial W_k} = \underbrace{\dfrac{\partial e}{\partial h_k}}_{\text{from the higher layer}} \cdot \underbrace{\dfrac{\partial h_k}{\partial W_k}}_{\text{current layer}}\)
  • Each layer does two jobs: compute \(\partial h_k/\partial W_k\) to update its own weights, and compute \(\partial h_k/\partial h_{k-1}\) to pass the gradient down: \(\dfrac{\partial e}{\partial h_{k-1}} = \dfrac{\partial e}{\partial h_k}\cdot\dfrac{\partial h_k}{\partial h_{k-1}}\).
  • If a layer’s output feeds two places, the incoming gradients are added.
Case on the slidesResult with L2 loss \(e = (y - h)^2\)
1 layer, \(h_1 = W_1 x\)\(\dfrac{\partial e}{\partial W_1} = -2\,(y - h_1)\,x\)
2 layers, \(h_2 = W_2 h_1\)\(\dfrac{\partial e}{\partial W_2} = -2\,(y - h_2)\,h_1\)  and  \(\dfrac{\partial e}{\partial W_1} = -2\,(y - h_2)\,W_2\,x\)
1 layer + sigmoid, \(h_2 = \sigma(h_1)\)\(\dfrac{\partial e}{\partial W_1} = -2\,(y - h_2)\;\sigma(h_1)\,(1 - \sigma(h_1))\;x\)

The slides end with “derive the 2-layer case yourself”. The middle row is that derivation: \(\partial e/\partial h_2 = -2(y - h_2)\), \(\partial h_2/\partial h_1 = W_2\), \(\partial h_1/\partial W_1 = x\), and you multiply the three.

Traps: where the notes can mislead you

I checked every worked number in the course files. These are the places where a note and the correct answer disagree, or where two parts of the course use different conventions.

WhereWhat the file saysWhat to do
Multi-layer handout, tanhOutput range (0, 1)Tanh is really (−1, 1). If an option says (−1, 1), choose it.
Review sheet, Problem 3Desired output [1, 2]Not one-hot. Apply \(-\sum y_k\ln\hat{y}_k\) to whatever target is printed. See type 3.
Quiz 2 key vs review sheetShapes written 12 × 7 while net = XWWith the bias in the first row and net = XW, write (inputs + 1) × neurons and show the dimension check. See type 2.
CNN notebook, 1-D code cellPrints [2, −2, −1, 4, −1]The formula gives [−2, 2, 1, −4, 1]. The code flips the filter. Slide without flipping unless told otherwise. See the CNN page.
Single-layer notes, linear-regression example\(w = 0 - 0.1(-10) = 0.1\), and a prediction of 10 for \(5(2) + 3\)Arithmetic slips: those are 1.0 and 13. The method and the conclusion (overshoot → lower α) are what matter.
Single-layer notes, gradientsLinear regression omits the \(1/m\); logistic regression includes itUse the formula printed in the question. If none is given, state the one you use.
PerceptronStep outputs 1 when \(z \ge 0\)\(z = 0\) is class 1. That is why (0, 0) is misclassified at the start of the AND example.
Layer counting“2-layer network”Two layers of weights: one hidden and one output. The input is not counted.
Cross-entropy“log”Natural log (ln), as the review sheet states.

Short-answer bank

Quiz 1 was ten 3-point short answers, and its grading key gave marks for specific key ideas. Say the answer out loud, then open it. The words in bold are the ones that earn the marks.

Asked on Quiz 1

Supervised vs unsupervised learning, by the data they use

Supervised learning uses labeled data: input features and an output label, and the model learns the relationship so it can predict outputs for new data (house prices, medical imaging). Unsupervised learning uses unlabeled data: features only, and the algorithm discovers hidden patterns or groupings (customer segmentation, market-basket analysis).

Why does data matter in machine learning?

Data is the first of the four key components. The model learns from data instead of being explicitly programmed, each observation is a set of feature values in which the model finds relationships, and the quality and nature of the data determine what the model can do.

Purpose of activation functions, and what happens without them

An activation function is applied to a neuron’s weighted sum and introduces non-linearity, which lets the network learn complex patterns and curved boundaries. It also shapes the output (sigmoid gives a probability). Without it the whole network collapses to a single linear model, however many layers it has.

What problems can a single-layer network solve?

Linearly separable problems, where one straight line (or plane) separates the classes, and linear input-output relationships. Examples: linear regression, logistic regression, AND and OR with a perceptron.

Main limitation of a single-layer perceptron

It can only produce a linear decision boundary, so it only works on linearly separable data. It handles AND and OR but fails on XOR. Supporting points: no hidden layers, the step function is not differentiable, and limited capacity.

Single-layer vs multi-layer network

A multi-layer network has one or more hidden layers with non-linear activations between input and output. That lets it learn non-linear decision boundaries and hierarchical features, and solve XOR. A single-layer network goes straight from input to output and is limited to linear boundaries.

Why choose the right measurement scale?

The scale determines which properties the values have (identity, order, equal intervals, true zero) and therefore which operations and statistics are valid. With the wrong scale you do meaningless arithmetic, such as saying 40 °C is twice as hot as 20 °C.

Which scale for height, weight and age, and why?

The ratio scale. These satisfy all four properties, including a true zero, so ratios, multiplication and division are meaningful (20 kg is twice 10 kg).

Why are NumPy arrays faster than Python lists?

Vectorization: operations are applied to the whole array at once by built-in universal functions instead of element by element in a Python loop. This works because all elements have the same type, so the data is stored and processed uniformly.

Likely new ones

Why can’t the perceptron be trained with gradient descent?

Its step activation is not differentiable, so there is no gradient to follow. It uses the perceptron update rule \(w \leftarrow w + \eta(y - \hat{y})x\) instead, which only changes the weights on a mistake.

Why softmax and not sigmoid for multi-class classification?

Separate sigmoids give independent outputs that do not sum to 1, which makes no sense when exactly one class is true. Softmax gives positive outputs that sum to 1, so they are a valid probability distribution over the classes.

What is the vanishing gradient problem and how does ReLU help?

During backprop the gradient is a product of local derivatives. Sigmoid and tanh saturate, so their derivatives are near 0 for large inputs, and the gradient shrinks toward zero in the early layers, which stop learning. ReLU’s derivative is 1 for positive inputs, so the gradient passes through undiminished.

What is a dying ReLU and how does Leaky ReLU fix it?

If a ReLU neuron’s input stays negative, its output and its gradient are both 0, so its weights never update again. Leaky ReLU keeps a small non-zero slope for negative inputs, so some gradient always flows.

What is back-propagation?

The algorithm that computes the gradient of the loss with respect to every weight by applying the chain rule from the output layer back to the input. Each layer multiplies the gradient from the higher layer by its own local gradient. Gradient descent then uses those gradients to update the weights.

What does the bias do?

It is a constant added to the weighted sum that shifts the decision boundary (shifts the activation). Without it the boundary must pass through the origin.

What does the learning rate control? Too large? Too small?

The step size of each weight update. Too large: the update overshoots the minimum and the loss can increase. Too small: training is very slow.

What is a hidden layer and why is it important?

Any layer between the input and output layers. It transforms the input into intermediate representations, and with a non-linear activation it lets the network learn hierarchical features and complex decision boundaries.

What is a convolution in a CNN?

Sliding a small filter of learnable weights over the input and taking a local dot product at each position. The result is an activation map that is large wherever the filter’s pattern appears.

Why use a CNN instead of an MLP for images?

A filter is small and shared across all positions, so a CNN needs far fewer parameters, keeps the spatial structure of the image, and detects a feature wherever it appears. It also learns its own features instead of relying on hand-crafted ones.

What is pooling and why is it used?

A fixed operation (max or average) applied over small regions of each activation map, with no learnable weights. It reduces the spatial size and gives slight translation invariance, so the exact position of a feature is not critical.

What is deep learning, and what are its challenges?

A modern evolution of neural networks that emphasises very deep networks, large unstructured datasets and modern compute (GPUs). Challenges: vanishing gradients (use BatchNorm, skip connections), overfitting (regularization, data augmentation) and needing a lot of data (transfer learning).

MCQ drill

62 questions across every topic except CNNs (those are on the CNN page). Each one shows the reason as soon as you answer. Your progress is saved in this browser.

Answer key for the review sheet’s 15 MCQs

You said you got nearly all of these. Use this to confirm the ones you were unsure about.

#AboutAnswerWhy
1Bias termCShifts the decision boundary
2Logistic regression outputCA probability
3What a perceptron can solveCLinearly separable problems
4MSE lossBRegression
5Cross-entropy pairingCSoftmax or sigmoid
6Boundary with 2 inputsCA line
7Adding hidden layersBLearn non-linear functions
8ReLU reducesBThe vanishing gradient problem
9CNNs mainly forBImage processing
10Computation graphCA sequence of mathematical operations
11Backprop computesBGradients of the loss
12Backprop is based onCThe chain rule
13Direction of gradientsCFrom output to input
1410 stacked linear layersCEquivalent to one linear layer
15Removing the biasBBoundary must pass through the origin