After this chapter you will be able to
compute a neuron’s output, and choose an activation function knowing what each costs the gradient;
show that one neuron cannot compute XOR, and solve it with a hidden layer;
explain a hidden layer as a remapping of the input, on XOR and on words;
derive cross-entropy from maximum likelihood, and state why the gradient is prediction minus target;
carry out one forward pass, backward pass and update by hand;
say why low training cost is not the goal.
This chapter builds on Chapter 7, whose counting needed no learning.
The methods of Chapter 7 never had to learn anything, because they counted, reweighted and factored, and every step was a fixed recipe applied to data. Many problems yield to that style and many do not.
Nobody can write down the rules that tell a photograph of a cat from one of a dog. Nobody can write the rules that map an acoustic waveform to the sentence it encodes, or, to stay in this book, the rules that decide whether a film review is favourable. The knowledge is genuine but tacit, since we recognise the cat without being able to say what makes it one.
For such problems the way forward is to learn the mapping from examples, because the rule writing of Chapter 1 has nothing to write down. Show the machine thousands of labelled cases and let it adjust itself until it gets them right, in the hope that it captured the pattern and did not memorise the cases.
This chapter builds the machine that does the adjusting, and every model in the rest of this book is this machine enlarged, from the word2vec of Chapter 9 to the transformers of Part IV.
The atom of the machine is deliberately simple. A single artificial neuron takes an input vector , forms a weighted sum with learnable weights and a bias (a constant offset), then passes the result through a nonlinear activation function . The two steps are:
The weighted sum is called the pre-activation, and it is a linear function of the input. The activation is what lets the neuron represent anything more interesting than a line, because without it stacking neurons would be pointless, a composition of linear maps being just another linear map. The choice of is therefore not cosmetic but the thing that lets a network bend and curve and carve up its input space.
The historical first choice was a hard threshold, outputting if and otherwise. It captures the all-or-nothing firing of a biological neuron and it is also useless for learning, because its derivative is zero everywhere it is defined and so gives no signal about which way to nudge the weights. Learning by gradients demands a smooth activation.
The sigmoid was the classic smooth replacement, , which squashes any number into and is convenient when the output should read as a probability. Three values are worth knowing: , and .
It has two defects. Its outputs are not centred on zero, which slows learning, and more seriously it saturates, since for large the curve flattens and its derivative approaches zero.
That derivative is , whose maximum sits at and is only , so even at its best a sigmoid shrinks the gradient passing through it by a factor of four. Stack that across many layers and you have the vanishing gradient that cripples recurrent networks, the sequence models of Chapter 12.
The tanh function fixes half the problem, being zero-centred over with a derivative at the origin of and not . It preserves gradient better, so the recurrent networks of Chapter 12 and the gates of Chapter 13 use it.
The modern default fixes the other half. The rectified linear unit is , whose derivative for positive inputs is , so it does not saturate on that side at all, and it is trivially cheap to compute. It has its own flaw, since a neuron stuck at has zero gradient and can die, which leaky variants patch by allowing a small negative slope.
The through line is the same for all of them. An activation must be nonlinear enough to give the network expressive power and smooth enough to give learning a gradient to follow.
Before layers, meet a single neuron on its own, because what it can and cannot do is the reason every network after it has a middle. The perceptron is Equation (8.1) with a hard threshold. Frank Rosenblatt built one in 1958, in hardware, with motors adjusting potentiometers for weights, and it takes inputs, weights them, adds a bias, then fires if the total clears zero.
It also learns, by a rule so simple you can run it in your head. Show it an example. If it is right, change nothing. If it is wrong, nudge every weight in the direction that would have helped:
Rosenblatt proved this converges provided a solution exists, and that proviso is the story of this section. Hold on to it, because the next subsection shows a function for which no solution exists.
A perceptron computes , which is the equation of a line in two dimensions, a plane in three and a hyperplane in general, so a perceptron draws one straight boundary. It answers according to which side you fall on. Plenty of useful functions are that shape, and here are two of them with weights you can check by hand.
| output for | |||||
| function | weights | ||||
| AND | 0 | 0 | 0 | 1 | , |
| OR | 0 | 1 | 1 | 1 | , |
AND at gives , so it fires, while at it gives and does not. This is a single line, drawn between the single corner where both inputs are on and the three where they are not.
This is why perceptrons were exciting, because character recognition, simple sensor decisions and any judgement where the classes fall on opposite sides of a boundary all became learnable from examples and no longer had to be programmed.
Try exclusive or, which fires when one input is on and the other is off. It looks no harder than AND and OR.
| XOR | ||
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
Draw the four points and the trouble is visible. The two that should fire, and , sit on one diagonal, while the two that should not, and , sit on the other, so they interleave.
No single straight line separates one diagonal from the other, and the failure is not a lack of cleverness, since it can be proved in four lines. Suppose some computes XOR. Then:
| input | requirement | because XOR is |
|---|---|---|
| 0 | ||
| 1 | ||
| 1 | ||
| 0 |
Add the second and third requirements to get , then rearrange to . The first requirement says , so , and therefore , which contradicts the fourth requirement. No such weights exist.
Minsky and Papert published this in 1969 and the field’s funding and enthusiasm collapsed for a decade. The result is correct, while the conclusion drawn from it was not, because the fix was already known in principle: add a layer.
Here is the network, with two hidden units using ReLU and then one output unit. All weights are small integers, so you can verify every number.
Run all four inputs through it. The columns give each pre-activation and activation in turn.
| input | XOR | correct? | ||||||
| 0 | 0 | 0 | 0 | 0 | 0 | yes | ||
| 0 | 1 | 1 | 1 | 0 | 1 | yes | ||
| 1 | 0 | 1 | 1 | 0 | 1 | yes | ||
| 1 | 1 | 0 | 2 | 1 | 0 | yes | ||
It works, but how it works is the lesson, and that becomes visible if you throw away the input columns and look only at where each point landed.
| input in space | lands at | target |
|---|---|---|
| 0 | ||
| and | 1 | |
| 0 |
That table shows the central idea of deep learning. Four input points became three hidden points, because the two inputs that share a target, and , were mapped onto the same place, the hidden layer having decided they were the same kind of thing.
The problem is now linear. In hidden space the target-1 point sits at , between the two target-0 points at and , and the output unit computes , which scores them , and , so one threshold at separates them cleanly.
The output unit is still just a perceptron and still draws one straight line. What changed is the space it draws that line in.
A hidden layer does not classify. It moves the data to a place where classifying is easy.
The last layer of almost every network in this book is a linear map followed by a softmax, which is a perceptron with more outputs and was never made cleverer. Everything before it exists to hand it a representation where a straight line will do, and once you see that, the rest of the book is one idea in many costumes.
| model | what it remaps, and into what |
|---|---|
| Multilayer perceptron | a fixed input vector, into a space where classes separate |
| Word embeddings (Ch. 9) | one-hot words, into a space where similar words sit close |
| Recurrent network (Ch. 12) | a sequence, into a hidden state carrying its history |
| Transformer (Ch. 17) | each token, into a vector shaped by the tokens around it |
Every row is the XOR trick at a different scale. Chapter 6 made the same complaint about one-hot vectors, that every word is equidistant from every other, and the answer there was a better space too.
The word for what a hidden layer produces is a representation, and learning good representations is what the field means when it says deep learning. XOR is the smallest example where you can watch it happen and check every number by hand.
The XOR network remapped four points in a plane. The next step is the one this book cares about, which is the same remap applied to words. XOR is arithmetic, and words are the reason we are here, but the move is identical, and on a small enough vocabulary every number is still checkable by hand. The section runs the experiment to its end. It has a corpus, a one-hot input space that knows nothing, a hidden layer that groups the words, a trained version of that layer, and a payoff when part of the corpus is deleted. Here is the whole corpus, in eleven short sentences.
| feed the cat | the cat sleeps | |
| feed the dog | the dog sleeps | |
| feed the horse | the horse sleeps | ride the horse |
| drive the car | park the car | |
| drive the bus | ride the bus |
The corpus has five words and five contexts, so tally which word appears with which context and it becomes a grid.
| feed | sleeps | ride | drive | park | |
|---|---|---|---|---|---|
| cat | 1 | 1 | 0 | 0 | 0 |
| dog | 1 | 1 | 0 | 0 | 0 |
| horse | 1 | 1 | 1 | 0 | 0 |
| car | 0 | 0 | 0 | 1 | 1 |
| bus | 0 | 0 | 1 | 1 | 0 |
That grid is everything the model will ever be told, with no dictionary, no labels, and nobody anywhere saying that a cat is an animal.
Feed a word to a network and it must arrive as numbers, and the obvious encoding gives each word its own dimension.
| word | one-hot input |
|---|---|
| cat | |
| dog | |
| horse | |
| car | |
| bus |
Five words, five dimensions. Now measure the ten pairs.
| pair | distance | cosine |
|---|---|---|
| cat, dog | 0 | |
| cat, horse | 0 | |
| cat, car | 0 | |
| cat, bus | 0 | |
| and the six remaining pairs, all identical | ||
Ten pairs and one distance, so cat is as far from dog as it is from bus. This is the complaint of Chapter 6 with numbers attached.
One note before the fix, because the trouble with one-hot inputs is not the trouble XOR had. A single unit over five one-hot inputs carries five free weights, one per word, so it can fire for any subset you like and separability is not the problem. The problem is that every weight is private to a word, so nothing the model learns about cat can ever reach dog.
Insert a hidden layer of two units between the word and the answer. Its weights form a matrix , one row per word.
There is one output unit per context and each fires when its score is positive. Here are the weights, small integers again, so nothing is hidden in the arithmetic.
| hidden weights | output units | |||||
| word | row 1 | row 2 | context | |||
| cat | 2 | 0 | feed | 1 | ||
| dog | 2 | 0 | sleeps | 1 | ||
| horse | 2 | 1 | ride | 1 | 1 | |
| car | 0 | 2 | drive | 1 | ||
| bus | 1 | 2 | park | 1 | ||
The first step costs nothing, because a one-hot vector times simply selects a row of , so the multiplication is a lookup and the row it returns is the word’s embedding.
| word | ||
|---|---|---|
| cat | ||
| dog | ||
| horse | ||
| car | ||
| bus |
Score every context for every word, where each cell is one multiplication and one addition. Bus sits at , so its ride score is and its park score is .
| word | feed | sleeps | ride | drive | park | fires for |
|---|---|---|---|---|---|---|
| cat | feed, sleeps | |||||
| dog | feed, sleeps | |||||
| horse | feed, sleeps, ride | |||||
| car | drive, park | |||||
| bus | ride, drive |
Read the last column against the corpus grid and every cell agrees, so eleven sentences are reproduced by ten numbers in and fifteen in the output layer.
As with XOR, the lesson is where the points went, so throw away the score columns, keep the arrival, and group the words by the place they arrived at.
| lands at | arrived from | fires for |
|---|---|---|
| cat and dog | feed, sleeps | |
| horse | feed, sleeps, ride | |
| car | drive, park | |
| bus | ride, drive |
This is the XOR table again with words in it. Five input vectors became four hidden points, and two vectors that are orthogonal in the input, cat and dog, were mapped onto the same place because the corpus uses them identically. The hidden layer decided they were the same kind of thing, and the two tables say one thing at two scales.
| XOR | words | |
|---|---|---|
| input vectors | 4 corners of a square | 5 one-hot vectors |
| distances between them | 1 or | , every pair |
| hidden points | 3 | 4 |
| which two coincide | and | cat and dog |
| because they share | a target | every context |
Even XOR’s input space has some structure to work with, since two of its corners are closer than the other two, whereas one-hot inputs do not have that much. Every pair is apart, so every part of the arrangement in the table above was built by the hidden layer out of the corpus alone.
The other three did not collapse, and their spacing is the interesting part, so measure the pairs again in the hidden space. Dog repeats cat, so its rows are left out.
| pair | input distance | hidden distance | hidden cosine | moved |
|---|---|---|---|---|
| cat, dog | 1.4142 | 0.0000 | 1.00 | together |
| cat, horse | 1.4142 | 1.0000 | 0.89 | together |
| car, bus | 1.4142 | 1.0000 | 0.89 | together |
| horse, bus | 1.4142 | 1.4142 | 0.80 | stayed |
| cat, bus | 1.4142 | 2.2361 | 0.45 | apart |
| horse, car | 1.4142 | 2.2361 | 0.45 | apart |
| cat, car | 1.4142 | 2.8284 | 0.00 | apart |
One distance became several. Horse sits between the animals and the vehicles because the corpus both rides it and feeds it, and bus sits between car and horse for the same reason. Nobody put them there, and they landed where their contexts sent them.
Those weights were written down and not learned, so that the arithmetic stays checkable, whereas training finds its own. Run gradient descent on the same eleven sentences with two hidden units and one output unit per context, then read the arrivals as before.
| lands at | arrived from | fires for |
|---|---|---|
| cat and dog | feed, sleeps | |
| horse | feed, sleeps, ride | |
| car | drive, park | |
| bus | ride, drive |
Four groups again, and the same fires-for column, while the one-hot vectors on the left are the same five vectors, still apart and still carrying nothing. Only the coordinates differ, and there is no reason they should not, since nothing in the loss fixes which direction is which and an axis on its own means nothing. Read the distances instead, which no rotation can change.
| pair | learned distance | hand-set distance |
|---|---|---|
| cat, dog | 0.0000 | 0.0000 |
| cat, horse | 1.9065 | 1.0000 |
| car, bus | 2.6205 | 1.0000 |
| horse, bus | 2.7856 | 1.4142 |
| cat, car | 3.3511 | 2.8284 |
Cat and dog arrive at the same point, identical to every digit, from five different random starts. The four nearest pairs come out in the same order as the hand-set ones, and after that the two orderings part company. Cat and car is the fifth nearest pair once the vectors are learned, where the hand-set space makes it the furthest of all seven. That costs nothing, since by then the words are unrelated anyway, but only the near end of such a ranking is stable.
Collapsing cat onto dog is how a model answers a question it was never asked. Delete one cell from the grid, so that the corpus never says feed the dog and dog now appears in one sentence only, the dog sleeps. Train both models on what is left, then ask each of them whether a dog can be fed.
| model | reading | |
|---|---|---|
| one-hot lookup, no hidden layer | 0.50 | a coin toss |
| two hidden units | 0.92 | yes |
The reason is in the weights. The lookup keeps one weight per word per context, so deleting the cell leaves that weight with no gradient and it never moves, which makes the answer whatever the bias happened to be. The model has nothing to say.
The network with a hidden layer has no weight for that cell at all, because it has a place for dog instead. Four facts survive the deletion, namely that the dog sleeps and that it is never ridden, driven or parked, and one corner of the plane satisfies all four. That corner already holds cat and horse, the feed unit covers it, so feed comes back for free.
This is what a word embedding is, and every model in Chapter 9 is this network grown larger, with a bigger vocabulary, a bigger hidden layer and a full corpus. Word2vec uses three hundred hidden units instead of two and millions of sentences instead of eleven, and the mechanism on this page does not change.
Run it.
code/worked_examples/xor_to_words.pyprints every table above.--trainlearns the embedding instead of setting it, and--holdoutruns the deleted cell experiment. Change a sentence in the corpus, then watch which pair of words stops collapsing.
A single neuron is a weak learner, and the power comes from arranging many into layers and stacking the layers so that each layer’s activations feed the next. Such a network is called feed-forward, or a multilayer perceptron, and it applies an affine map (a matrix product plus a bias) and a nonlinearity at every layer. With enough hidden units it can approximate almost any function, which is what makes it a universal tool.
You will meet one such network again, because the lookup, mix and softmax stack of the neural language model in Chapter 11 is this network, and so is every architecture that follows it. To train a network we need a number saying how wrong it currently is. For a single training example the loss compares the prediction with the true target . For classification we do not have to invent one, because maximum likelihood produces it as soon as is read as a probability.
A binary target has two outcomes, so describes a Bernoulli draw. Its probability is:
The exponents do the selecting. At the second factor is one and the probability is , and at the first factor is one and it is . One expression therefore covers both outcomes.
Training wants the parameters that make the observed most likely. Take logs of Equation (8.4) and the product becomes a sum:
Negate it, for two reasons. A log likelihood is highest when the model fits best, and gradient descent only moves downhill, so we need a quantity to minimise. Negation is strictly decreasing, so it leaves the best parameters where they are and turns that maximum into a minimum. It also fixes the scale, because a probability is at most , so its log is at most and the negative never falls below zero.
Negating Equation (8.5) is the whole step, and what it leaves is the cross-entropy loss:
Equation (8.6) is therefore the negative log likelihood of a single Bernoulli observation, and nothing about it was chosen for convenience. It behaves as a good loss should, so take the truth to be .
| prediction | loss | reading |
|---|---|---|
| nearly right, small penalty | ||
| hedging, moderate penalty | ||
| confidently wrong, severe penalty |
Cross-entropy rewards confident correctness and punishes confident error, which is the same pressure that perplexity measures in Chapter 10, and that is no coincidence, because perplexity is the exponentiated cross-entropy of a language model. Chapter 11 runs the same argument over outcomes, which is the form every later classifier in this book uses.
The loss is defined for one example. What we minimise is the cost, the average loss over the whole training set seen as a function of all the parameters :
Learning is now a concrete goal: find the that makes as small as possible. Everything else in the chapter is a method for doing that.
We minimise the way you descend a hill in fog, by feeling which way is steepest downhill and then stepping that way. The direction of steepest increase is the gradient . We step the opposite way:
where the learning rate sets the step size, so that too small a value makes training crawl while too large a value overshoots and diverges. Repeat this for many steps, in practice on small random batches of examples, and gradient descent walks the parameters downhill towards a good fit.
Equation (8.8) needs one thing, the gradient, meaning the partial derivative of the cost with respect to every weight, often millions of them. Computing those efficiently is the job of backpropagation, and it is nothing more exotic than the chain rule of calculus applied to the network’s layered structure. The error at the output travels backwards layer by layer, and each layer multiplies the gradient arriving from above by its own local derivative.
One result recurs throughout the book and should be carried away. Pair a sigmoid or softmax output with the cross-entropy loss and the gradient of the loss with respect to the pre-activation collapses to
the prediction minus the target. A nearly correct neuron, against , gets a gentle push of , while a confidently wrong one, against , gets a hard shove of .
This prediction-minus-target signal drives the neural language model of Chapter 11 and the classifiers of Chapter 15, and it is why cross-entropy and the sigmoid or softmax are always found together.
Nothing makes this concrete like doing it once with numbers, so here is a tiny network with two inputs, two hidden ReLU units and one sigmoid output. The parameters start at these values:
| layer | weights | bias |
|---|---|---|
| hidden unit 1 | , | |
| hidden unit 2 | , | |
| output | , |
The training example is with target , and the learning rate is . Every number below can be checked with a pocket calculator.
Push the input through one layer at a time.
| quantity | arithmetic | value |
|---|---|---|
The network is barely better than a coin flip, which is what an untrained network should look like. The loss of is the starting point for the update.
Start at the output and use Equation (8.9), working back towards the input.
| gradient | arithmetic | value |
|---|---|---|
| , ReLU is open | ||
| , ReLU is open | ||
The ReLU derivative is a gate. Both units have , so both gates are open and multiply by , whereas had either been negative its gate would multiply by and every weight below it would get no signal at all on this example.
Look at the signs. They differ because and have opposite signs, so hidden unit 1 pushed the output up and gets rewarded while hidden unit 2 pushed it down and gets corrected.
Apply Equation (8.8) to every parameter, biases included, since a bias is a weight on a constant input. A negative gradient makes the parameter go up.
| parameter | old | gradient | new |
|---|---|---|---|
The last two rows matter. Both gradients are zero because and on this example, so a weight on an input that is off receives no signal and cannot move. The three biases do move, and leaving them out would give the wrong answer below.
Run the same example forward again with all nine parameters at their new values.
| before | after | ||
|---|---|---|---|
| gate now shut | |||
The prediction moved towards the target and the loss fell by nearly two thirds. This is the whole algorithm, and everything after this chapter is the same four steps run on larger networks, over more examples, many millions of times.
One step was large enough to change the network’s shape, and it deserves a note. Hidden unit 2 was pushing the output down, so the update drove negative, and the unit’s gate is now shut on this input. It contributes nothing to the next forward pass and will receive no gradient from this example again. This is the dying ReLU of Section 8.2.1 arriving in a worked example rather than as a warning, and a learning rate of is what made one step big enough to cause it.
Given enough capacity, a network trained by Equation (8.8) will drive its training cost towards zero, and that is not the goal. Mistaking it for the goal is the central hazard of the field.
The goal is generalisation, meaning low error on data the model has never seen. A model that memorised its training examples would score perfectly on the training set and uselessly on anything new. This is overfitting, fitting the noise and idiosyncrasy of the training sample instead of the pattern that also governs future data.
We detect it with a discipline that Chapter 15 makes concrete: hold out a test set the model never trains on, and judge the model only by its error there. Everything that combats overfitting serves that one end, whether regularisation, early stopping, dropout or, above all, more data. A neural network is valuable to the extent that what it learned transfers beyond its training data.
This is the entire apparatus: a neuron, a nonlinearity, a loss averaged into a cost, gradient descent to minimise it, backpropagation to supply the gradients, and a test set to keep the enterprise honest. The chapters ahead add mostly architecture, meaning particular wirings of neurons suited to particular data. They also add ideas of their own, notably the attention of Part IV, which is a new way of combining information, not a rewiring of these parts. Even so, the training loop stays the one in this chapter.
The first use is immediate. Turn this machine loose on the distributional hypothesis of Chapter 6 by training vectors to predict their contexts, and out come the word embeddings of Chapter 9. This is the same dense geometry the counting of Chapter 7 produced, now trained, not computed, and from there the story is one of ever cleverer architectures, recurrent, gated and attentional, built from these identical parts.
Summary
A neuron forms a weighted sum and passes it through a nonlinear activation, and the activation must be smooth for gradients to exist. A perceptron draws one straight boundary, so it cannot compute XOR, and a hidden layer solves the problem by remapping the inputs to where a line suffices. The same remap applied to words groups cat with dog because the corpus uses them alike, and it recovers a fact the corpus never stated. Cross-entropy is the negative log likelihood, and paired with a sigmoid or softmax it gives the gradient prediction minus target. Gradient descent steps against the gradient of the cost, backpropagation supplies the gradient by the chain rule, and one worked step shows the loss falling from to and a ReLU gate shutting. A network is judged by its error on held-out data, because fitting the training set is not the goal.
Key terms
activation function. the nonlinearity applied to a neuron’s weighted sum.
perceptron. a neuron with a hard threshold, which draws one straight boundary.
hidden layer. a layer between input and output that remaps the data into a representation.
embedding. the row of a weight matrix that a one-hot input selects, a dense vector for a word.
cross-entropy loss. the negative log likelihood of the observed target under the model’s prediction.
cost. the average loss over the training set, as a function of the parameters.
gradient descent. repeatedly moving the parameters against the gradient of the cost.
backpropagation. computing every gradient by applying the chain rule layer by layer from the output.
overfitting. fitting the noise of the training sample so that error on new data stays high.
Rumelhart et al. (1986) made backpropagation and gradient trained
multilayer networks widely known. For activations, loss functions,
optimisation and regularisation in full depth, go to Goodfellow et al.
(2016). Goldberg (2015) covers the same ground as a primer written for
natural language processing. On how initialisation and momentum shape
the optimisation this chapter only sketches, see Sutskever et al.
(2013). Every gradient in the worked step above is what
torch.autograd computes on your behalf, and the four steps
of this section are what the two lines loss.backward() and
optimizer.step() stand for in any modern training loop.
8.1 The sigmoid and its shrinking gradient. Compute , and . Then use to find the at which the derivative is largest, and state that maximum. In one sentence, relate the number to the vanishing gradient of Chapter 12.
8.2 What cross-entropy rewards. For a true label , evaluate Equation (8.6) at , and . Do the three numbers behave as a good loss should? Repeat for and confirm the symmetry.
8.3 Prediction minus target. Use Equation (8.9). Give for a neuron predicting when the truth is , and for one predicting when the truth is . Which gets the larger update? Why is that the behaviour you want?
8.4 One gradient step. A single weight has value and . Apply Equation (8.8) with and report the new . What happens to training if is set to instead?
8.5 One perceptron update. A perceptron has and . It sees with target and predicts . Apply Equation (8.2) with , treating the bias as a weight on a constant input of . Write the new and , then say whether the same example is now classified correctly.
8.6 A new word in the hidden space. In the word network of Section 8.4, give a sixth word, truck, the hidden row . Using the output weights in the table, compute its five scores and say which contexts it fires for. Which existing word does it most resemble, and does the answer agree with the corpus?
Build and measure
8.7 Redo the worked step with a shut gate. Repeat the four-step worked example, changing only from to . Show that is now negative, so and the ReLU gate is shut. Which gradients become zero? Which parameters do not move at all on this example, and why?
8.8 Let autograd check your
arithmetic. Build this chapter’s network in torch,
two inputs, two hidden ReLU units and one sigmoid output, starting from
the same weights and biases and using the same
with
.
Call backward() and compare what it reports against the
Step 2 table, then apply one step at
and confirm that
reaches
and
falls to
.
Now print the pre-activation of hidden unit 2 and say what has happened
to that unit, and which sentence of this chapter predicted it.
8.9 Predict, then train XOR. Before running anything, write down whether a network with a single hidden unit can learn XOR and whether one with two can, and say why. Then train both from ten random starts with gradient descent and report how many runs reach zero error. Account for every run that failed.
8.10 The learning rate sweep. Repeat the worked step of this chapter with , , and . For each, report and after one step and after ten steps on the same example. Say which are too slow, which are right, and what a too-large rate looks like in the loss.
In practice
8.11 Fitting is not the goal. A network reaches error on its training set and on held-out data. Name the phenomenon. Explain what went wrong, in terms of pattern against memorisation. List two things you could change to improve the held-out number. Why is the test set the only honest judge?
8.12 Why the lookup model answers 0.50. In the deleted-cell experiment, the one-hot lookup model gives and the hidden-layer model gives . Explain the first number from the gradient, and the second from the geometry. Then describe a corpus deletion for which the hidden layer would not recover the fact, and say why.
8.13 A deep sigmoid stack. A team stacks twenty sigmoid layers and finds that the first layers barely change during training. Use the maximum of to estimate how much the gradient can shrink, and propose two changes, one to the activation and one elsewhere, that would help.
8.14 Units that never fire. A team finds that of the hidden ReLU units in a trained network are zero on every training example. Say what this means for the gradients those units receive, how the learning rate could have caused it, and what you would change.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
xor_to_words.pyThe XOR remap, done on words
Five words, five contexts, two hidden units. Cat and dog land on the same point, and a deleted fact comes back.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.