Exercise: neural networks
Before this unit: Day 33: Random forests.
See also: Day 12: Thresholding; Day 27: Graph cuts.
Goal
By the end of this exercise you should be able to:
- compute the output and draw the decision line of a single neuron, and give weights for AND and OR,
- explain why one neuron cannot do XOR and check that two hidden units can,
- turn class scores into probabilities with softmax,
- push a small input through a network (matrix, ReLU, matrix) by hand,
- explain why a network without a bend is just one matrix,
- predict how many bends a one-input network can make, and where,
- take a gradient-descent step by hand and say what the learning rate does.
The questions under By hand and Explore are for everyone. The Math questions (derive, prove) are for students who want the full treatment.
Background
| Word | Meaning |
|---|---|
| Neuron | \varphi(w_1x_1 + \dots + w_nx_n + b): weighted sum, bias, activation \varphi (step, sigmoid 1/(1+e^{-s}), ReLU) |
| Decision line | where w_1x_1 + w_2x_2 + b = 0; \mathbf w points to the positive side |
| Softmax | p_k = e^{z_k}/\sum_j e^{z_j}: scores → probabilities |
| Layer | \mathbf h = \text{ReLU}(A\mathbf x + \mathbf b): a matrix, a shift, then the bend on each entry |
| ReLU | \max(0, s): negatives become 0 |
| Hidden unit | one entry of \mathbf h; with one input, one hinge |
| Weights | all numbers in the matrices and shifts |
| Loss | how wrong the output is, e.g. the mean squared error over the data |
| Gradient descent | \mathbf w \leftarrow \mathbf w - \eta\,\nabla L, repeated; \eta is the learning rate |
By hand
Part A — forward pass
Use A = \begin{pmatrix} 2 & -1 \\ 1 & -1 \\ -1 & 1 \end{pmatrix}, \mathbf b = (0,\ 1,\ 0), C = \begin{pmatrix} 1 & -1 & 2 \end{pmatrix}, d = 1.
B1. Compute the output for \mathbf x = (2,\ 1): first A\mathbf x + \mathbf b, then the ReLU, then C\mathbf h + d. Then compute it again without the ReLU.
B2. Compute the single matrix CA and the shift C\mathbf b + d. Check that (CA)\mathbf x + C\mathbf b + d gives your “no bend” answer of B1.
B3. Compute the output for \mathbf x = (1,\ 2), with and without the ReLU. Why are the two answers the same this time?
Part B — hinges
A network with one input x, two hidden units and output \text{out} = h_1 + h_2, where h_1 = \max(0,\ x - 1) and h_2 = \max(0,\ -2x + 1).
B4. Where does each unit bend? Give the output at x = -1, 0, 0.5, 1, 2, 3 and sketch it.
B5. Which numbers would you change to (a) move the first bend to x = 2, (b) make the output rise twice as fast for large x?
Part C — one gradient step
One weight, one data point: L(w) = (y - wx)^2 with x = 2, y = 3.
B6. What is the best w? Compute L'(w) and its value at w = 0.
B7. Start at w = 0. Take one step w \leftarrow w - \eta L'(w) with \eta = 0.1, 0.125, 0.25 and 0.5. Give the new w and the new loss each time. Which step sizes are too large?
Part D — counting
B8. An encoder takes a 28\times28 image to 192 hidden units and those to 2 numbers. How many weights and shifts does it have? Compare with the number of pixels in one image.
Part E — neurons, XOR and classes
B9. A neuron with \mathbf w = (2, 1), b = -4. (a) Compute w_1x_1 + w_2x_2 + b for the points (1, 1), (2, 1), (0, 3) and (3, 0). Which are on the positive side? (b) Draw the decision line. Where does it cross the axes? In which direction does \mathbf w point? (c) With a sigmoid activation, what are the outputs for (1, 1) and (2, 1)? What happens to them if you double \mathbf w and b?
B10. Inputs x_1, x_2 \in \{0, 1\} and a step activation (output 1 if the sum is > 0). Find weights and a bias for (a) AND, (b) OR. (c) Draw the four corners and explain why no weights work for XOR.
B11. The network h_1 = \text{ReLU}(x_1 + x_2), h_2 = \text{ReLU}(x_1 + x_2 - 1), \text{out} = h_1 - 2h_2. Compute h_1, h_2 and the output for the four corners. Which logical function is it? Where in the plane (for any real x_1, x_2) is the output above \tfrac12?
B12. Softmax. (a) Compute the probabilities for the scores (2, 1, 0). (b) The same for (102, 101, 100). Explain. (c) Two classes with scores (0, s): show that p_1 is the sigmoid of s.
B13. A classifier for 28 \times 28 digit images: 784 inputs → 100 hidden units → 10 class scores. How many weights and biases? Why is this a poor design for images (think of a digit shifted by one pixel)?
B1. A\mathbf x + \mathbf b = (4 - 1,\ 2 - 1 + 1,\ -2 + 1) = (3,\ 2,\ -1). ReLU: (3,\ 2,\ 0). Output = 3 - 2 + 0 + 1 = 2. Without the ReLU: 3 - 2 - 2 + 1 = 0.
B2. CA = (2 - 1 - 2,\ -1 + 1 + 2) = (-1,\ 2) and C\mathbf b + d = (0 - 1 + 0) + 1 = 0. Check: (-1)\cdot 2 + 2 \cdot 1 + 0 = 0, the “no bend” answer.
B3. A\mathbf x + \mathbf b = (2 - 2,\ 1 - 2 + 1,\ -1 + 2) = (0,\ 0,\ 1): no negative entry, so the ReLU changes nothing. Output = 0 - 0 + 2 + 1 = 3 both ways (and (CA)\mathbf x = -1 + 4 = 3). A ReLU network is a straight-line map within each region where no unit switches; it only bends at the borders.
B4. h_1 bends at x = 1 (where x - 1 = 0), h_2 at x = 0.5 (where -2x + 1 = 0).
| x | -1 | 0 | 0.5 | 1 | 2 | 3 |
|---|---|---|---|---|---|---|
| h_1 | 0 | 0 | 0 | 0 | 1 | 2 |
| h_2 | 3 | 1 | 0 | 0 | 0 | 0 |
| out | 3 | 1 | 0 | 0 | 1 | 2 |
The output falls with slope -2 until x = 0.5, is flat at 0 between 0.5 and 1, and rises with slope 1 after: a “bathtub” of three straight pieces.
B5. (a) The shift: h_1 = \max(0,\ x - 2) (bend at minus shift / slope). (b) Double the slope: h_1 = \max(0,\ 2x - 2) (bend stays at 1), or give h_1 the output weight 2.
B6. The best w makes wx = y: w = 1.5, L = 0. L'(w) = -2x(y - wx) = -4(3 - 2w), so L'(0) = -12.
B7. w_\text{new} = 0 + 12\eta.
| \eta | 0.1 | 0.125 | 0.25 | 0.5 |
|---|---|---|---|---|
| new w | 1.2 | 1.5 | 3 | 6 |
| new L | 0.36 | 0 | 9 | 81 |
\eta = 0.125 lands exactly on the best w. \eta = 0.25 jumps over the valley to the same height on the other side (the loss stays 9). \eta = 0.5 overshoots so far that the loss grows from 9 to 81. Both 0.25 and 0.5 are too large.
B8. First layer 784 \cdot 192 + 192 = 150{,}720, second 192 \cdot 2 + 2 = 386: in total 151{,}106, about 190 times the 784 pixels of one image. (The VAE encoder of the VAE units has a second output of the same size for the spread, 151,492 in total.)
B9. (a) (1,1): 2 + 1 - 4 = -1; (2,1): +1; (0,3): -1; (3,0): +2. Positive: (2, 1) and (3, 0). (b) 2x_1 + x_2 = 4 crosses the x_1-axis at 2 and the x_2-axis at 4. \mathbf w = (2, 1) is perpendicular to the line and points to the positive side (away from the origin). The line is 4/\sqrt5 = 1.79 from the origin. (c) 1/(1 + e^{1}) = 0.269 and 1/(1 + e^{-1}) = 0.731. Doubling \mathbf w and b keeps the line (2\cdot0 = 0) but doubles the sums (-2, +2): the outputs become 0.119 and 0.881, more confident.
B10. (a) AND: w_1 = w_2 = 1, b = -1.5 (only (1,1) gives 0.5 > 0). (b) OR: w_1 = w_2 = 1, b = -0.5. (Any line with the right corners on each side works.) (c) XOR needs (1,0), (0,1) on one side and (0,0), (1,1) on the other. The two pairs lie on the two diagonals of the square, which cross; a line that has both ends of one diagonal on one side contains the whole diagonal there (a half-plane is convex), so it also contains the crossing point, which lies on the other diagonal. Contradiction: no line works.
B11.
| (x_1, x_2) | (0,0) | (1,0) | (0,1) | (1,1) |
|---|---|---|---|---|
| h_1, h_2 | 0, 0 | 1, 0 | 1, 0 | 2, 1 |
| out | 0 | 1 | 1 | 0 |
It is XOR. With s = x_1 + x_2: out = s for 0 \le s \le 1, 2 - s for s \ge 1, and 0 for s < 0. So out > \tfrac12 exactly where \tfrac12 < x_1 + x_2 < \tfrac32: a band between two parallel lines, one per hidden unit.
B12. (a) e^2 = 7.389, e^1 = 2.718, e^0 = 1, sum 11.107: p = (0.665, 0.245, 0.090). (b) The same, (0.665, 0.245, 0.090): every e^{z_k} gets the factor e^{100}, which cancels. (Computed directly, e^{102} would overflow in many programs, which is why software subtracts the largest score first.) (c) p_1 = e^s/(e^0 + e^s) = 1/(e^{-s} + 1), the sigmoid of s.
B13. 784 \cdot 100 + 100 = 78{,}500 and 100 \cdot 10 + 10 = 1{,}010: 79,510 numbers. Every hidden unit has its own weight for every pixel, so nothing it learns about a stroke at one position carries over to the same stroke one pixel to the right: shifting the digit changes almost every input, and the network must learn each position separately, from many examples. Convolutional layers (unit 3 of this day) share the same small kernel across all positions.
Math questions
B14. (math) Show that a network with ReLU hidden units and a linear output is a continuous, piecewise linear function of its input: the input space splits into regions in which the network is an affine map \mathbf x \mapsto M\mathbf x + \mathbf c.
B15. (math) A network with one input x, one hidden layer of n ReLU units and a linear output. Show that its output, as a function of x, has at most n kinks. Can two units give the same kink position?
B16. (math) Show that after one step w_\text{new} - 1.5 = (1 - 8\eta)(w - 1.5). For which \eta does every step bring w closer to the best value?
B14. (math) Fix an input \mathbf x and record which hidden units are on (z > 0). In the set of inputs with the same on/off pattern, each ReLU is either the identity or zero, so every layer is an affine map (a matrix times the input plus a shift, with some rows zeroed), and a composition of affine maps is affine. The patterns split the input space into finitely many regions bounded by the hyperplanes z_j = 0 (for deeper layers, pieces of such hyperplanes). Continuity: every layer is continuous (ReLU is continuous), so the composition is.
B15. (math) Unit k computes \max(0, a_kx + b_k), which bends only at x = -b_k/a_k (and not at all if a_k = 0). The output \sum_k c_k\max(0, a_kx + b_k) + d is linear between consecutive bend points, so it can only change slope at these at most n positions. Two units can have the same bend position; then the network has fewer than n distinct kinks (and a kink disappears if the slope changes cancel).
B16. (math) w_\text{new} = w + 4\eta(3 - 2w) = w + 8\eta(1.5 - w), so w_\text{new} - 1.5 = (w - 1.5) - 8\eta(w - 1.5) = (1 - 8\eta)(w - 1.5). The distance shrinks at every step when |1 - 8\eta| < 1, i.e. 0 < \eta < 0.25. For 0.125 < \eta < 0.25 it zigzags across the valley but still converges.
Explore
The demo fits a small network (1 \to H \to 1) to a line scan across two nuclei of different brightness (synthetic data with noise). Grey dots are the pixels, the red curve is the network, the faint orange curves are the hidden units’ hinges (each times its output weight) and the orange triangles mark where they bend. Below: the loss against the training step. train 500 steps runs gradient descent; new start puts the hinges back at their (fixed-seed) starting positions.
E1. With 3 hidden units, press train 500 steps six times. Where do the three hinges end up? Which features of the profile does the network get, and which does it miss?
E2. Compare the presets one hinge, 3 hinges and 12 hinges: read the final loss of each. The noise in the data has variance 0.03^2 = 0.0009. Which network is close to the best you can hope for? Can a network do better than the noise level on these data, and would that be good?
E3. Preset no bend: 12 hidden units, but no ReLU. Describe the fit and compare its loss with a flat line at the mean intensity (loss 0.0728). Explain with the collapse argument from the lecture.
E4. Preset learning rate too large. What happens to the loss, and to the hinges at the end? What does the fit look like?
E1. After 3000 steps the three hinges sit at about 0.04, 0.27 and 0.47 on the 0–1 axis: the left foot, the top and the right foot of the bright nucleus. The network makes a tent over the bright nucleus and a flat line (about 0.33) to the right of it: the dimmer nucleus is missed. Three hinges are not enough for two plateaus with four edges. Loss 0.0203.
E2. Final losses after 3000 steps: one hinge 0.0588, 3 hinges 0.0203, 12 hinges 0.00186. Only the 12-hinge network is close to the noise variance 0.0009. A network with very many units could push the loss below 0.0009 by following the noise from pixel to pixel; that would be overfitting: it would fit these 100 pixels better but a new line scan of the same nuclei worse.
E3. The fit stays a straight, slightly tilted line, loss 0.0652, barely better than the flat line at the mean (0.0728). Without the bend, twelve hidden units and the output layer collapse to one matrix: \text{out} = (CA)x + \text{shift}, a straight line, however many units there are.
E4. The loss jumps around instead of falling smoothly, and after 500 steps it sits at 0.0728, exactly the loss of the flat mean line: every hinge has been thrown off the data (no unit is switched on anywhere between 0 and 1), so the network outputs a constant. The steps were so large that they overshot into a region where the ReLUs are off and the gradient is zero, and the network can no longer recover (“dead units”). A smaller learning rate avoids this.
Explore: classifying points
The demo trains a small network to classify points in the plane. The points are coloured by class; the background shows the network’s decision (colour = predicted class, stronger = more confident). Choose the number of hidden layers (0–2), the units per layer and the activation \varphi. Each thumbnail shows one hidden unit: orange where it is active (strong = large output). play trains, step takes one gradient step, reset goes back to the start weights, new start draws other start weights. Click to add points of the chosen class, drag points to move them. With no hidden layer and two classes the network is one neuron: drag the round handle to move its line and the dark tip to turn it (the arrow is \mathbf w).
P1. Preset one neuron, by hand. The line starts vertical through the centre (\mathbf w = (1, 0), b = 0). Read the loss and accuracy. Turn and move the line so that it separates the two blobs as well as possible. Then drag the tip further out without moving the line: what happens to the loss, and why? Finally press play: where does training put the line, and what happens to \|\mathbf w\|?
P2. Preset one neuron on XOR fails. Press play. What loss and accuracy does the neuron reach? Compare the loss with \ln 2 = 0.693.
P3. Preset 2 hidden units solve XOR. Press play and watch the two thumbnails. What does each hidden unit do, and what does the output region look like? Then press new start a few times (play each time). Does training always succeed?
P4. Preset no nonlinearity: still a line: 8 hidden units, but no bend, on a circle inside a ring. Train. What does the boundary look like and what accuracy is reached? Explain with the collapse argument.
P5. Preset circle: 3 ReLU units. Train and describe the shape of the region inside. Why 3 units at least? Try 2 units.
P6. Preset spiral needs depth (two layers of 8). Train and compare the thumbnails of layer 1 with those of layer 2. Then set hidden layers to 1 and train again.
P7. Preset 3 classes with softmax, no hidden layer. What do the boundaries between the regions look like? Why?
P1. The start line splits the blobs fairly well already: loss 0.535, accuracy 98 %. A line between the blobs, perpendicular to the line joining their centres, does about as well in accuracy. Making \mathbf w longer without moving the line makes every probability more confident: the loss falls while all points are on the right side (for example \mathbf w = (1, 1): 0.461, (4, 4): 0.154, (8, 8): 0.070, same line through the centre), but a point on the wrong side is punished harder and harder, so with overlapping classes the loss eventually rises again. Training puts the line between the blobs (accuracy 98 %, loss 0.032 after 1000 steps) and keeps growing \mathbf w, to about (16.8, 6.5) after 1000 steps: the few points in the overlap stay wrong, and the rest become ever more certain.
P2. The loss drops to 0.691 and stays; accuracy 50 %. 0.693 = \ln 2 is the loss of always answering “50 : 50”. The best a single line can do here is to give up: whatever line it draws, half of each class is on the wrong side.
P3. After about 50 steps the loss is below 0.03 and the accuracy 100 % (0.002 after 1000 steps). Each hidden unit is a half-plane (a ReLU of one line); the output region of one class is the band between the two lines (as in B11), which contains the two corners of that class. With other start weights (new start: start seeds 2 to 6) the network gets stuck at 75 % every time: one corner stays wrong. With the second start, one hidden unit is off on every point (“dead”: its gradient is zero, so it never comes back); with the others, both units are active but their lines sit where they can only fix three of the four corners, and no small step improves the loss. Small networks are sensitive to the start; larger ones much less (try 4 units).
P4. The boundary stays a straight line; accuracy 74 % (the line cuts off part of the ring), loss 0.569. Without a bend, W^{(2)}(W^{(1)}\mathbf x + \mathbf b^{(1)}) + \mathbf b^{(2)} is a single affine function of \mathbf x, however many units: one line.
P5. The inner region is a rounded triangle: three lines, one per hidden unit, cut off the corners; accuracy 100 % after about 200 steps (loss 0.016). A bounded region needs at least 3 lines in the plane (two lines give a wedge or a band, which is open on one side). With 2 units the accuracy stays around 74 %.
P6. Layer-1 thumbnails are half-planes (one line each). Layer-2 units combine them: their thumbnails are polygons and stripes. Together they follow the spiral: 100 % after about 500 steps. With a single layer of 8 units the network needs much longer and stays around 75–90 % (it oscillates between these values for thousands of steps): 8 lines are too few to cut the spiral into the right pieces.
P7. The boundaries are straight lines meeting in a point: with no hidden layer each class score is linear, z_k = \mathbf w_k^\top\mathbf x + b_k, and the boundary between classes k and j is where z_k = z_j, a line. Softmax only turns the scores into probabilities; it does not bend the boundaries.
Code
Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in neuralnets/src/neuralnet/exercise.rs.
C1. weighted_sum(w, b, x), sigmoid(s) and relu(s): one neuron is a weighted sum w_1x_1 + \dots + w_nx_n + b followed by a bend. The check is your answer to B9.
C2. layer(a, b, x, bend) and network(a, b, c, d, x, bend): matrix, bend, matrix. Every row of A is one neuron; bend switches the ReLU on or off.
for every row i of A:
s = b[i]
for every input j:
s = s + A[i][j] · x[j]
h[i] = max(0, s) # without the bend: h[i] = s
out = d + sum over i of C[i] · h[i]
The checks are your answers to B1, B3 and B11, and the lecture’s example (6 with the bend, 4 without).
C3. softmax(z): subtract the largest score first, then p_k = e^{z_k}/\sum_j e^{z_j}. The check is B12: the scores (2, 1, 0) and (102, 101, 100) must give the same probabilities.
C4. train_neuron(points, labels, eta, steps): train one sigmoid neuron by gradient descent on the mean cross-entropy, starting from \mathbf w = 0, b = 0. For one point the gradient is (p - y)\,\mathbf x for the weights and p - y for the bias.
w = 0, b = 0
repeat steps times:
gw = 0, gb = 0
for every point x with label y:
p = sigmoid(w · x + b)
gw = gw + (p − y) · x / n
gb = gb + (p − y) / n
w = w − eta · gw
b = b − eta · gb
The checks: two groups of points separated by a line are classified correctly, and on XOR the loss stays at \ln 2 = 0.693 (demo question P2).
Then cargo run -p neuralnets -- neuralnet and open the pictures in out/neuralnet/. The program trains one neuron to tell nucleus pixels from background in a synthetic fluorescence image, with two measurements per pixel: its intensity and the mean of its 15 \times 15 neighbourhood. feature-space.png shows the training pixels in the plane of the two measurements (blue background, orange nucleus), tinted by the neuron’s decision; probability.png is the neuron’s output for every pixel.
C5. Read the trained weights \mathbf w = (w_1, w_2) and look at the line in feature-space.png. Which of the two measurements does the neuron rely on?
C6. Between step 1000 and step 5000 the loss still falls, although the line hardly moves. What happens to \mathbf w and b, and why does that lower the loss?
C7. Compare the pixel accuracy with the accuracy of always answering “background”. Where in the image do you expect the remaining errors? Compare probability.png with truth.png.
The model solution is neuralnets/src/neuralnet/solution.rs in the download.
C5. After 5000 steps \mathbf w = (26.6, 4.6), b = -12.4. The weight of the intensity is almost six times that of the neighbourhood mean, so the line is almost vertical: the neuron is essentially a threshold on the intensity, between about 0.36 and 0.45 depending on the neighbourhood. Here the nuclei are much brighter than the background everywhere, so one measurement is enough; the neuron has learned the threshold of the thresholding day from examples.
C6. The loss falls from 0.018 to 0.012 while \mathbf w grows from (17.3, 7.7) to (26.6, 4.6) and b from -9.9 to -12.4. Longer weights make the sigmoid steeper: every pixel that is already on the right side gets a probability closer to 0 or 1, which lowers its cross-entropy (as in demo question P1). Only the few pixels on the wrong side push back.
C7. The neuron gets 99.5 % of the pixels right; always answering “background” gets 81.2 % (18 % of the training pixels are nucleus). The remaining 334 wrong pixels are almost all (332) on the outlines of the nuclei, where the blurred edge lies between the two intensities and even the truth is a matter of half pixels.
Where this leads
The next unit opens the black box of training: losses for classes, gradient descent with mini-batches, and backpropagation, which computes all the gradients in one backward pass. The rest of the neural-networks day uses the same “matrix, bend, matrix” with whole images as input (a 784-number vector for a 28\times28 image), many layers and many training examples: losses for classification, backpropagation, and convolutional networks that segment images. Later, the autoencoder units squeeze an image through a few numbers and rebuild it; without the bend such a network is exactly PCA. How to train such networks well in practice (better step rules than plain gradient descent, sensible initial weights, normalisation layers, augmentation, and reading the training curves) is the day after this one, Training networks in practice.