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
| The answer is | Output neurons | Final activation | Loss |
|---|---|---|---|
| yes or no | 1 | Sigmoid | Binary cross-entropy |
| one class out of | Softmax | Cross-entropy | |
| a number | 1 | none | Mean 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
One sigmoid output
- Darker shading: output closer to 1
- Output layer
- 1 neuron
- Final activation
- Sigmoid
- Loss
- Binary cross-entropy
- Right on the points shown
- 100%
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.
Three softmax outputs
- Class 1
- Class 2
- Class 3
- Output layer
- 1 neuron per class (3)
- Final activation
- Softmax
- Loss
- Cross-entropy
- Right on new points
- 95%
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
No activation on the output
- Students
- The network's prediction
- Output layer
- 1 neuron
- Final activation
- None
- Loss
- Mean squared error
- Mean squared error
- 5.1
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.
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 and is trained to minimise squared error. With a sigmoid and cross-entropy, it computes and is trained to minimise log loss. You have seen both before.
A network with one neuron
- 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
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.
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.
- 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.
For each task, say how many outputs the network needs, what activation goes on them, and which loss to use.
- Estimating the price of a house.
- Deciding whether an email is spam.
- Recognising a handwritten digit, 0 to 9.
- Tagging a photo with any of “beach”, “people” and “night”, in any combination.
- 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
- One output, no activation, mean squared error. It is a number.
- One output with a sigmoid, binary cross-entropy. It is a yes or no.
- Ten outputs with softmax, cross-entropy. Exactly one of ten classes is right.
- 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.
- Two outputs, no activation, mean squared error. It is two numbers.
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 . The gradient is probability minus truth, : raise the score a little.
True answer no. The probability given to “no” was 0.2, so the loss is . The gradient is : lower the score a lot.
The same “prediction minus truth” appears as for softmax. The more wrong the network is, the harder the push.
A network predicts for three examples whose targets are . 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 , and . Squared, they are 0.25, 0.25 and 0. The mean is .
The gradient for each prediction is 2 times its miss, divided by the number of examples: , and .
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.
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.
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.