Stacking layers
The obvious fix is to stack layers. Feed the outputs of one layer into another as its inputs, and that one into a third.
A layer that sits between the inputs and the final output is called a
Running an input through every layer in turn, from first to last, is called a
Two straight lines make a straight line
Take the smallest possible stack: one neuron feeding another. The first computes , and the second computes .
Two neurons are connected in a row with nothing between them. Together they have four adjustable numbers. Can you set them so that the output bends?
Two neurons, still one line
- After the first neuron
- After the second neuron
- Two neurons
- -0.80 × (1.50·x + 1.00) + 2.00
- Same thing as one neuron
- -1.20·x + 1.20
It cannot be done. Substituting one formula into the other shows why:
Two neurons in a row are exactly one neuron with a different weight and bias. The same holds for whole layers, and for any number of them: a stack of a hundred linear layers computes nothing that a single layer could not. All that depth, and no gain.
A network has 50 dense layers with no activation functions. On data that needs a curved boundary, how will it compare with logistic regression?
A bend: the ReLU
To stop layers collapsing into one, something that is not a straight line has to go between them. That something is an
The most widely used is almost embarrassingly simple. The
keep the value if it is positive, otherwise output zero
Put a ReLU after a neuron and its straight line is cut off at zero. The result is a hinge: flat on one side of a kink, sloped on the other.
One neuron with a ReLU makes a hinge
- Before the ReLU: w·x + b
- After the ReLU, times the output weight
- Kink at x = −b / w
- -1.00
- Flat side
- left of the kink
- Slope on the other side
- 1.00
Three numbers give full control of the hinge. The weight and bias decide where the kink is, at . The sign of the weight decides which side is flat. The output weight decides how steeply the other side rises, or falls.
A single hinge is not impressive. Its value is as a building block.
Many bends make any curve
Add several hinges together and the sum is a line with several bends. Each hidden neuron contributes one bend. With enough of them, placed well, the sum can follow any curve as closely as you like.
Recall the sleep data from
A curve from straight pieces
- Target curve
- Sum of all the hinges
- Each hinge on its own
- Hidden neurons (hinges)
- 1
- Straight pieces
- 1
- Largest gap from the target
- 21.4 points
One neuron gives a straight line that misses by 21 points at its worst. Two give a single bend and a gap of 5.5. With eight the gap is down to a third of a point, and the pieces are hard to tell from a smooth curve.
This is the central fact about neural networks. A hidden layer with a simple non-linear activation can approximate any reasonable function, given enough neurons. The network does not need to be told the shape in advance, as polynomial regression did. It builds the shape out of bends.
Other activation functions
ReLU is the default, but it is one of a family. Any function with a bend will stop layers collapsing. The choices differ in how they behave during training.
Four activation functions
- The function
- Its slope
- Input
- 1.5
- Output
- 1.500
- Slope here
- 1.000
- Note
- The default for hidden layers.
| Function | Output range | Where it is used |
|---|---|---|
| ReLU | 0 and up | Hidden layers, by default |
| Sigmoid | 0 to 1 | The output of a yes/no network |
| Tanh | −1 to 1 | Hidden layers of some older and recurrent networks |
| Step | 0 or 1 | Historical. It cannot be trained by gradient descent |
The slope is what matters most. Training works by following slopes downhill, so an activation whose slope is zero gives the weights before it nothing to follow. The step function has a slope of zero everywhere, which rules it out. Sigmoid and tanh flatten out for large inputs, which slows learning in deep networks. ReLU keeps a slope of 1 for every positive input, and that is the main reason it took over.
Bending a boundary
The same idea works with two inputs. Each hidden ReLU neuron contributes one straight crease across the plane, and the output layer combines the creases into a boundary with corners.
Here are two interlocking crescents, a shape no straight line can separate. The network has one hidden layer, and it is trained from scratch every time you change a setting.
Enough neurons to separate the crescents
- Shaded: called the filled kind
- Filled and hollow: the two kinds
- Hidden neurons
- 1
- Right on the 100 shown
- 93%
- Right on 300 new points
- 90.7%
With ReLU, one or two hidden neurons manage 93%. Three are enough to fold the boundary around both crescents and get all 100 points right, and 99% of 300 new ones.
Without an activation, the network scores 91% whether it has one hidden neuron or twelve, and its boundary is always a straight line. That is the collapse from earlier in the chapter, seen in two dimensions. The extra neurons are there and doing nothing.
A network with ReLU hidden layers is underfitting: its boundary is too simple for the data. Which change gives it more ability to bend?
In code
The activation is a class with one method, and the network is the three objects called in order. The full file is code/ch15_activations.py (run it in Colab).
import numpy as np
class Activation_ReLU:
def forward(self, inputs):
self.output = np.maximum(0, inputs) # negatives become zero
rng = np.random.default_rng(0)
batch = rng.standard_normal((5, 2)) # 5 examples, 2 features
hidden = Layer_Dense(2, 8, rng) # Layer_Dense is from the last chapter
activation = Activation_ReLU()
output = Layer_Dense(8, 3, rng)
hidden.forward(batch) # the forward pass:
activation.forward(hidden.output) # layer, activation,
output.forward(activation.output) # layer
print(hidden.output.shape, output.output.shape) # (5, 8) (5, 3)
The output is three numbers per example, and at this point they are meaningless: the weights are random. The network has the right shape and no knowledge. The next chapter gives it a way to measure how wrong those three numbers are, which is the first step toward fixing them.
Key Takeaways
- Stacking linear layers gains nothing: any number of them collapse into one.
- An activation function between layers prevents the collapse. It must not be a straight line.
- ReLU keeps positives and zeroes negatives. One ReLU neuron makes a hinge with one bend.
- A hidden layer adds up many bends, and with enough of them can approximate any curve.
- Activations are judged by their slopes, because slopes are what training follows.
- Show that two linear layers in a row do the work of one.
- Apply a ReLU, and describe the hinge that a single ReLU neuron draws.
- Explain how a hidden layer builds a curve out of straight pieces.
- Say why an activation is judged by its slope.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
Apply the ReLU to each of these numbers: −2, 0, 3.5 and −0.1.
Hint
ReLU keeps positive numbers and turns everything else into zero.
Solution
ReLU keeps positive numbers and replaces everything else with zero: the results are 0, 0, 3.5 and 0.
A first layer computes . A second layer computes . There is no activation between them. Write directly in terms of . What does that tell you?
Hint
Put the first formula into the second and simplify.
Solution
Substitute: .
The two layers together are one straight line, with a weight of 6 and a bias of −1. A single layer could have computed it. The second layer added parameters and no new ability, and the same thing happens with layers of any width.
A small network computes . Work out at , 1, 2 and 3, and describe the shape.
Hint
Each ReLU is zero until its own kink (at 0, 1 and 2) and a straight line after it.
Solution
The function is zero up to 0, rises to a peak of 1 at , falls back to zero at and stays there. Three hinges make a tent. A row of such tents, of different heights, can follow any curve as closely as you like. That is the idea behind the figure with the sleep data.
The step function outputs 1 for positive inputs and 0 otherwise. It is not a straight line, so it prevents layers from collapsing. Why is it still a poor activation for a network trained by gradient descent?
Hint
Gradient descent needs to know how the output changes when a weight changes a little. What is the slope of a step?
Solution
Its slope is zero everywhere, except at the jump, where it has no slope at all. Gradient descent changes each weight in proportion to how the loss responds to a small change in that weight. With a step function, a small change in a weight almost never changes the output, so the response is zero and the weight is never updated. The network cannot learn.
ReLU has a slope of 1 for every positive input, so the signal for learning passes through. The sigmoid and tanh have useful slopes near zero and nearly none far from it, which is why very deep networks built on them train slowly.
In the figure “A curve from straight pieces”, step the number of hidden neurons from 1 to 2 to 8 and note the largest gap each time. Roughly how does the gap shrink as neurons are added, and why does each extra neuron help less than the one before?
Hint
Each neuron contributes one bend. Think about where the first bend is needed most.
Solution
With one neuron the fit is a straight line and the largest gap is 21 points. With two there is one bend, and the gap drops to 5.5. With eight it is about a third of a point.
The first bend fixes the biggest failure, a line trying to follow a curve that rises and falls. Each later bend only refines a fit that is already close, so it has less left to fix. This pattern, big gains first and small ones later, is typical when capacity is added to a model.
Going further
Wide or deep?
One hidden layer can approximate any function in principle, but it may need an impractical number of neurons. Several layers can build complicated shapes out of simpler ones: creases in the first layer, combinations of creases in the second, and so on. In practice, depth turns out to be a far more economical way to get expressive power than width.
Dead neurons
A ReLU neuron whose input is negative for every example outputs zero for all of them, has a slope of zero, and so receives no correction during training. It is stuck. Variants such as leaky ReLU, which gives negative inputs a small slope instead of none, were designed to avoid this.
References and further reading
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 3 and 4, nnfs.io.
- M. Nielsen, Neural Networks and Deep Learning, chapter 4: a visual proof that neural nets can compute any function.
- D. Smilkov and S. Carter, TensorFlow Playground, for experimenting with hidden layers in the browser.