Chapter 20 // Neural Networks

One Network, Many Jobs.

The network so far picks one class out of three. How does it predict a number, or answer yes or no?

Reading time
14 min

Everything built so far has served one task: choosing a class out of several. Part I and Part II covered two other tasks, predicting a number and answering yes or no. This chapter shows that the network handles all three with one small change, and then closes a loop that has been open since chapter 2.

Body and head

Think of a network in two parts.

The body is the stack of hidden layers. Its job is to turn the raw inputs into something useful: bends, creases, combinations of features. Nothing in it depends on what kind of answer is wanted.

The head is the together with the loss. It turns the body’s work into the answer and says how wrong that answer is. Changing the task means changing the head and leaving the body alone.

The answer isOutput neuronsFinal activationLoss
yes or no1SigmoidBinary cross-entropy
one class out of kkkkSoftmaxCross-entropy
a number1noneMean squared error

Each row pairs an activation with the loss that suits it. The pairs are not arbitrary: in every one, the gradient at the very end of the network works out to the same clean “prediction minus truth”.

A yes or no answer

For two classes there is no need for two output neurons. One is enough: its output, squashed by a sigmoid, is the probability of “yes”, and “no” is whatever remains.

The loss is the log loss from the logistic regression chapter, which in this setting is called :

L=−[ ylog⁡p+(1−y)log⁡(1−p) ]L = -\big[\,y \log p + (1 - y)\log(1 - p)\,\big]
Figure

One sigmoid output

6.44, 0.788.58, 3.774.86, 2.025.97, 1.518.12, 3.148.41, 2.176.52, 1.333.97, 3.497.39, 1.658.49, 4.334.19, 3.943.19, 5.756.9, 1.535.8, 1.15.32, 2.133.68, 5.375.48, 1.654.73, 2.635.79, 1.918.6, 3.354.5, 3.325.71, 1.238.1, 2.98.15, 1.958.93, 3.633.11, 4.278.82, 3.647, 0.94.39, 2.365.08, 1.918.46, 3.547.93, 2.629.35, 4.774.08, 35.76, 2.258.24, 3.543.5, 4.035.9, 1.755.07, 1.927.33, 1.512.89, 4.743.84, 5.864.13, 2.937.17, 1.825.11, 1.868.67, 5.178.88, 3.296.94, 1.647.12, 1.714.06, 4.180.93, 7.695.64, 6.933.2, 9.465.92, 7.853.36, 7.851.51, 6.872.27, 8.863.57, 8.576.6, 5.231.22, 5.393.78, 9.136.86, 5.912.37, 8.391.92, 4.456.43, 3.946.15, 5.815.11, 7.975.26, 8.256.15, 7.590.81, 5.931.17, 4.152.41, 84.68, 8.161.41, 6.535.53, 7.071.09, 5.453.47, 8.025.8, 4.024.11, 8.556.82, 5.854.05, 8.684.96, 7.685.67, 4.963.28, 8.236.65, 64.48, 8.126.91, 5.134.2, 9.52.32, 6.922.29, 8.554.22, 8.314.35, 8.22.73, 8.496.57, 5.031.58, 5.165.94, 6.435.35, 7.814.19, 7.784.08, 8.454.26, 9.16
  • Darker shading: output closer to 1
Output layer
1 neuron
Final activation
Sigmoid
Loss
Binary cross-entropy
Right on the points shown
100%
A network of 2 inputs → 16 ReLU neurons → 1 sigmoid output, trained when this figure appeared. The shading is its output: the probability of the filled kind. Try it: look at how sharp the change in shading is at the boundary, and how the boundary follows the two crescents.

This head has one more use. Give a network several sigmoid outputs, each trained with its own binary cross-entropy, and it can answer several independent yes/no questions at once: is there a cat in the picture, is there a dog, is it outdoors. Softmax could not do that, because it forces its outputs to compete for a total of 1.

One class out of several

This is the head we have been using all along: one output neuron per class, softmax to turn the scores into probabilities, and cross-entropy on the probability of the correct class.

Figure

Three softmax outputs

0, 00, 0.010, 0.020, 0.030, 0.040.04, 0.030.03, 0.050.04, 0.060.05, 0.070.08, 0.040.09, 0.040.11, 0.020.12, 0.030.1, 0.080.14, -0.020.14, 0.050.15, -0.050.17, -0.010.18, -0.020.19, 0.010.2, -0.030.2, -0.080.16, -0.150.22, -0.060.23, -0.090.22, -0.120.25, -0.070.16, -0.220.04, -0.28-0.03, -0.290.08, -0.290.04, -0.310.02, -0.32-0.08, -0.32-0.03, -0.34-0.1, -0.34-0.16, -0.330.04, -0.37-0.3, -0.24-0.22, -0.32-0.32, -0.25-0.05, -0.41-0.34, -0.25-0.26, -0.35-0.44, -0.07-0.31, -0.33-0.45, -0.12-0.46, 0.1-0.48, 0-0.49, -0.09-0.5, -0.07-0.51, -0.08-0.53, -0.01-0.53, -0.07-0.53, 0.12-0.56, -0.02-0.37, 0.43-0.4, 0.42-0.33, 0.48-0.27, 0.53-0.22, 0.57-0.29, 0.54-0.17, 0.6-0.23, 0.59-0.23, 0.6-0.03, 0.66-0.02, 0.670.32, 0.590.22, 0.650.14, 0.680.29, 0.650.62, 0.360.46, 0.560.35, 0.650.32, 0.670.71, 0.270.67, 0.380.78, 0.040.79, 0.020.79, 0.140.8, 0.140.81, 0.080.82, 0.070.82, 0.190.79, 0.30.84, 0.180.71, -0.50.88, 00.71, -0.530.49, -0.750.31, -0.860.89, -0.210.72, -0.590.46, -0.820.48, -0.82-0.06, -0.960.49, -0.830.46, -0.86-0.16, -0.98-0.36, -0.930, 00.01, -0.010.01, -0.010.02, -0.020.03, -0.020.04, -0.030.03, -0.050.04, -0.060.03, -0.070, -0.090.04, -0.090.05, -0.1-0.02, -0.12-0.07, -0.11-0.07, -0.12-0.01, -0.15-0.04, -0.16-0.07, -0.16-0.06, -0.17-0.15, -0.12-0.18, -0.1-0.12, -0.17-0.15, -0.17-0.21, -0.1-0.24, -0.06-0.25, -0.03-0.23, -0.13-0.26, -0.07-0.28, 0-0.29, -0.02-0.3, 0.06-0.31, 0.02-0.32, 0.06-0.24, 0.23-0.21, 0.27-0.31, 0.17-0.24, 0.27-0.32, 0.2-0.2, 0.32-0.19, 0.35-0.16, 0.37-0.02, 0.41-0.12, 0.41-0.17, 0.4-0.11, 0.43-0.05, 0.450.02, 0.460.04, 0.470.29, 0.390.27, 0.410.17, 0.480.4, 0.330.42, 0.310.33, 0.420.16, 0.520.5, 0.230.56, 0.090.47, 0.330.58, -0.070.59, -0.070.61, 00.61, 0.110.6, -0.160.59, -0.230.63, -0.150.64, -0.160.64, 0.20.67, -0.110.27, -0.630.4, -0.570.47, -0.520.44, -0.560.42, -0.590.29, -0.680.29, -0.69-0.1, -0.75-0.18, -0.75-0.04, -0.780.14, -0.77-0.4, -0.690.09, -0.8-0.46, -0.67-0.47, -0.68-0.69, -0.48-0.37, -0.76-0.77, -0.38-0.62, -0.61-0.6, -0.65-0.72, -0.53-0.85, -0.28-0.89, -0.16-0.83, -0.39-0.83, 0.41-0.93, 0.12-0.94, 0.16-0.91, 0.3-0.92, 0.31-0.93, 0.3-0.89, 0.43-0.99, 0.10, 0-0.01, 0-0.02, -0.01-0.03, 0-0.04, 0.01-0.05, -0.01-0.06, -0.01-0.07, 0-0.07, 0.04-0.03, 0.08-0.1, 0.03-0.11, 0.03-0.06, 0.11-0.12, 0.05-0.04, 0.14-0.1, 0.110.01, 0.160, 0.17-0.02, 0.18-0.03, 0.19-0.05, 0.20, 0.21-0.07, 0.21-0.03, 0.230.06, 0.23-0.01, 0.250.03, 0.260.15, 0.230, 0.280.18, 0.230.07, 0.290.24, 0.20.24, 0.220.32, 0.080.3, 0.170.35, 0.010.32, 0.170.37, 0.040.37, 0.090.39, -0.080.38, -0.140.4, -0.120.42, -0.060.42, -0.110.44, -0.080.09, -0.450.21, -0.410.42, -0.220.46, -0.160.27, -0.420.26, -0.430.05, -0.510.42, -0.320.03, -0.53-0.08, -0.540.22, -0.510.21, -0.53-0.29, -0.5-0.12, -0.57-0.41, -0.43-0.3, -0.53-0.27, -0.56-0.41, -0.47-0.49, -0.4-0.62, -0.18-0.58, -0.32-0.24, -0.62-0.68, 0.04-0.61, -0.32-0.7, -0.04-0.68, -0.18-0.71, 0.08-0.68, -0.26-0.74, -0.04-0.72, 0.19-0.72, 0.22-0.74, 0.22-0.49, 0.6-0.69, 0.39-0.39, 0.7-0.73, 0.34-0.68, 0.460.03, 0.83-0.45, 0.71-0.09, 0.84-0.21, 0.83-0.22, 0.84-0.44, 0.760.23, 0.86-0.39, 0.810.25, 0.870.22, 0.890.67, 0.650.32, 0.880.71, 0.630.83, 0.470.64, 0.730.34, 0.920.89, 0.430.76, 0.65
  • Class 1
  • Class 2
  • Class 3
Output layer
1 neuron per class (3)
Final activation
Softmax
Loss
Cross-entropy
Right on new points
95%
A network of 2 inputs → 32 ReLU neurons → 3 softmax outputs, trained with Adam for 600 steps when this figure appeared. Try it: compare this with the yes/no figure above. The hidden layers do the same kind of work; only the last layer differs.

The choice between this head and the previous one comes down to a question about the labels. If every example has exactly one correct class, use softmax. If an example can have several correct labels at once, or none, use one sigmoid per label.

A number

To predict a number, remove the final activation altogether. The output neuron’s weighted sum is the prediction, free to be any size, positive or negative. The loss is the mean squared error from .

Here is the sleep data from , where a straight line failed and we had to guess the right degree of polynomial.

Figure

No activation on the output

3 h, score 453.1 h, score 503.9 h, score 585 h, score 755.5 h, score 675.9 h, score 756.6 h, score 697.3 h, score 808.5 h, score 788.6 h, score 749.7 h, score 7010.2 h, score 65
  • Students
  • The network's prediction
Output layer
1 neuron
Final activation
None
Loss
Mean squared error
Mean squared error
5.1
A network of 1 input → 16 ReLU neurons → 1 output with no activation, trained on the twelve students. Try it: look closely at the curve: it is made of short straight pieces, one bend per hidden neuron, as in the chapter on activations.

The network found the rise and fall on its own. Nobody told it to use a curve with one bend, or any particular shape. Its mean squared error on these students is 5.1, against 66.2 for the best straight line.

That 5.1 deserves a second look. The noise in this data has a spread of about 5 points, so no model should do much better than a squared error of 25 on new students. A training error of 5.1 means the network has started to fit the noise in these twelve points. The lessons of the last chapter apply to this head exactly as they did to the other two.

Checkpoint

You want a network to predict tomorrow's temperature in degrees, which can be negative. Which output layer is right?

Old friends

Now take the idea to its limit. Remove the body entirely. No hidden layers: just the inputs wired straight to one output neuron.

With no activation and squared error, that network computes wx+bw x + b and is trained to minimise squared error. With a sigmoid and cross-entropy, it computes σ(wx+b)\sigma(w x + b) and is trained to minimise log loss. You have seen both before.

Figure

A network with one neuron

1, 481.5, 532, 503, 603.5, 574, 665, 685.5, 756, 717, 828, 839, 91
  • The neuron, at this step
  • Answer from the linear regression formula
Weight
0.00 (target 5.31)
Bias
52.00 (target 42.44)
Loss
402.83
0
The network is trained by the same forward pass, backward pass and update as every network in this part. The dashed line is the answer found in Part I or Part II. Try it: drag the training steps upward and watch the weight and bias approach their targets. Then switch the output layer and do it again.

On the exam data, the neuron with no activation settles at a weight of 5.31 and a bias of 42.44, with a loss of 6.13. Those are the numbers the least-squares formula gave in the linear regression chapter, to every digit shown.

On the pass/fail data, the sigmoid neuron settles at 1.56 and −6.03 with a loss of 0.259: the logistic regression model of chapter 6.

So linear regression and logistic regression were neural networks all along, the smallest possible ones. Everything since has been the same two ideas, a weighted sum and a loss to push down, with layers of bends added in between. That is a good thing to hold on to when networks start to look complicated.

Choosing a head

In practice the decision takes a few seconds, because the task dictates it.

Checkpoint

A network should tag photos with any that apply of: 'beach', 'people', 'sunset', 'food'. A photo can have several tags or none. Which output layer fits?

In code

The two new heads are four small classes. The full file, code/ch20_heads.py (run it in Colab), also trains the two one-neuron networks.

class Activation_Sigmoid:
    def forward(self, inputs):
        self.output = 1 / (1 + np.exp(-inputs))

    def backward(self, dvalues):
        self.dinputs = dvalues * self.output * (1 - self.output)

class Loss_BinaryCrossentropy:
    def forward(self, y_pred, y_true):
        clipped = np.clip(y_pred, 1e-7, 1 - 1e-7)
        return np.mean(-(y_true * np.log(clipped) + (1 - y_true) * np.log(1 - clipped)))

class Activation_Linear:                       # no activation: the output can be any number
    def forward(self, inputs):
        self.output = inputs

    def backward(self, dvalues):
        self.dinputs = dvalues.copy()

class Loss_MeanSquaredError:
    def forward(self, y_pred, y_true):
        return np.mean((y_true - y_pred) ** 2)

    def backward(self, y_pred, y_true):
        self.dinputs = -2 * (y_true - y_pred) / y_true.size

Trained on the exam data, the one-neuron network prints 5.31 42.44 6.13. On the pass/fail data it prints 1.56 -6.03 0.259.

Key Takeaways

  • A network is a body of hidden layers plus a head: the output layer and its loss.
  • Yes or no: one sigmoid output with binary cross-entropy.
  • One class out of several: softmax with cross-entropy. Several labels at once: one sigmoid per label.
  • A number: one output with no activation, with mean squared error.
  • With no hidden layers, these heads are linear regression and logistic regression.
You can now
  • Separate a network into its body and its head.
  • Choose the output layer and the loss for a given task.
  • Work out binary cross-entropy and mean squared error for a small example.
  • Explain how linear and logistic regression are networks with a single neuron.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exercisethink

For each task, say how many outputs the network needs, what activation goes on them, and which loss to use.

  1. Estimating the price of a house.
  2. Deciding whether an email is spam.
  3. Recognising a handwritten digit, 0 to 9.
  4. Tagging a photo with any of “beach”, “people” and “night”, in any combination.
  5. Locating an object in an image by its x and y coordinates.
Hint

Decide first whether the answer is a number, a yes or no, one class of several, or several yes-or-no answers at once.

Solution
  1. One output, no activation, mean squared error. It is a number.
  2. One output with a sigmoid, binary cross-entropy. It is a yes or no.
  3. Ten outputs with softmax, cross-entropy. Exactly one of ten classes is right.
  4. Three outputs, each with its own sigmoid, binary cross-entropy on each. The tags are three separate yes-or-no questions, and softmax would wrongly force them to compete.
  5. Two outputs, no activation, mean squared error. It is two numbers.
Exerciseby hand

A yes-or-no network outputs a probability of 0.8. What is the binary cross-entropy if the true answer is yes? What if it is no? In each case, what is the gradient for the score that went into the sigmoid?

Hint

The loss is minus the logarithm of the probability given to the true answer. The gradient is probability minus truth.

Solution

True answer yes. The loss is −ln⁡(0.8)≈0.22-\ln(0.8) \approx 0.22. The gradient is probability minus truth, 0.8−1=−0.20.8 - 1 = -0.2: raise the score a little.

True answer no. The probability given to “no” was 0.2, so the loss is −ln⁡(0.2)≈1.61-\ln(0.2) \approx 1.61. The gradient is 0.8−0=0.80.8 - 0 = 0.8: lower the score a lot.

The same “prediction minus truth” appears as for softmax. The more wrong the network is, the harder the push.

Exerciseby hand

A network predicts [2.5, 0, 2][2.5,\ 0,\ 2] for three examples whose targets are [3, −0.5, 2][3,\ -0.5,\ 2]. What is the mean squared error? What is its gradient for each prediction?

Hint

Square each miss and average. The gradient for each prediction is 2 times its miss, divided by 3.

Solution

The misses (prediction minus target) are −0.5-0.5, 0.50.5 and 00. Squared, they are 0.25, 0.25 and 0. The mean is 0.5/3≈0.1670.5 / 3 \approx 0.167.

The gradient for each prediction is 2 times its miss, divided by the number of examples: −0.33-0.33, 0.330.33 and 00.

The first prediction is too low and should rise. The second is too high and should fall. The third is exactly right and gets no push at all.

Exercisethink

A network has no hidden layers and one output with a sigmoid, trained with binary cross-entropy. Which model from earlier in the book is it? What does adding a hidden layer with ReLU change?

Hint

Write down what a single neuron followed by a sigmoid computes, and compare it with chapter 6.

Solution

It is logistic regression. One neuron computes a weighted sum plus a bias, the sigmoid turns it into a probability, and the loss is the log loss. Trained to convergence it finds the same weights.

Without a hidden layer the decision boundary must be a straight line. A hidden layer with ReLU lets the network bend its inputs into a new set of features first, and the final neuron then draws a straight line in that new space. Seen from the original inputs, the boundary can be curved. The crescents in this chapter’s first figure need exactly that.

Exercisewith the figure

In the figure “A network with one neuron”, choose the output with no activation and drag the training steps upward. What do the weight and bias approach? Then switch the output layer to the sigmoid and do it again. Which earlier models have you just trained?

Hint

The chapter on linear regression found a slope of 5.31 for the same students.

Solution

With no activation the neuron settles at a weight of 5.31 and a bias of 42.44, with a loss of 6.13. Those are the numbers the least-squares formula gave in chapter 2. A neuron with no activation trained on squared error is linear regression, found by gradient descent instead of by a formula.

With the sigmoid and cross-entropy the same neuron settles on the weights of the logistic regression model from chapter 6. The two oldest models in the book are the smallest possible neural networks.

Going further

Scaling the target

A regression network trains far more easily when its targets are of ordinary size, roughly between −2 and 2. Exam scores near 70 would start the loss in the thousands and make the first gradients enormous. The figure above subtracts a typical score and divides by a typical spread before training, and reverses that when reporting predictions. The same care applies to the inputs.

Several numbers at once

A regression head can have more than one output neuron. A network that predicts the position of an object in a picture outputs four numbers, the corners of a box, each compared with its target by squared error. One body can also carry two different heads at the same time, such as “what is it” and “where is it”.

References and further reading

  • H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 16 and 17, nnfs.io.
  • A. Zhang, Z. C. Lipton, M. Li and A. J. Smola, Dive into Deep Learning, chapters 3 and 4. Free at d2l.ai.
  • S. J. D. Prince, Understanding Deep Learning, chapter 5 (loss functions). Free at udlbook.github.io/udlbook.

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 20.1Body and head
  3. 20.2A yes or no answer
  4. 20.3One class out of several
  5. 20.4A number
  6. 20.5Old friends
  7. 20.6Choosing a head
  8. 20.7In code
  9. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in