Chapter 15 // Neural Networks

Layers and Activations.

If one neuron can only draw a straight line, how does a network draw anything else?

Reading time
17 min
Data
Read first
A Single Neuron

ended with a limit: a neuron draws one straight line, and a layer of neurons draws several. This chapter removes the limit with a single small addition, and it is worth seeing first why the obvious fix does not work.

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 . “Hidden” only means that nobody tells it what its values should be. The data fixes the inputs and the correct outputs. What happens in between is left for the network to work out during training.

Running an input through every layer in turn, from first to last, is called a . That much is easy. The question is whether stacking buys us anything.

Two straight lines make a straight line

Take the smallest possible stack: one neuron feeding another. The first computes h=w1x+b1h = w_1 x + b_1, and the second computes w2h+b2w_2 h + b_2.

Predict firstCommit to a guess, then use the figure below to check it.

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?

Figure

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
1.5
1.0
-0.8
2.0
The dashed line is the value after the first neuron. The solid line is the final output. Try it: move all four sliders as wildly as you like and try to make the solid line bend.

It cannot be done. Substituting one formula into the other shows why:

w2 (w1x+b1)+b2  =  (w2w1)⏟one weight x  +  (w2b1+b2)⏟one biasw_2\,(w_1 x + b_1) + b_2 \;=\; \underbrace{(w_2 w_1)}_{\text{one weight}}\,x \;+\; \underbrace{(w_2 b_1 + b_2)}_{\text{one bias}}

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.

Checkpoint

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 , applied to each neuron’s output before it is passed on.

The most widely used is almost embarrassingly simple. The , short for rectified linear unit, replaces negative numbers with zero and leaves positive numbers alone.

ReLU(z)=max⁡(0, z)\text{ReLU}(z) = \max(0,\ z)

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.

Figure

One neuron with a ReLU makes a hinge

-1, 0kink
  • 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
1.0
1.0
1.0
The dashed line is the neuron before the ReLU. The solid line is after the ReLU and one output weight. Try it: use the bias to slide the kink left and right. Use the weight to change the slope, and make it negative to flip which side is flat. Then make the output weight negative.

Three numbers give full control of the hinge. The weight and bias decide where the kink is, at x=−b/wx = -b / w. 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 , where scores rise with sleep and then fall. A straight line could not follow it. Here is the same shape, approximated by a hidden layer of ReLU neurons.

Figure

A curve from straight pieces

2, 51.02
  • 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
1
The dashed curve is the target. The orange line is the sum of the hinges. For clarity the kinks are spaced evenly and each hinge's slope is then chosen by least squares; a trained network would place the kinks itself. Try it: step the number of hidden neurons from 1 up to 12. Watch the largest gap shrink, and look at how the faint single hinges add up.

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.

Figure

Four activation functions

1.5, 1.5
  • The function
  • Its slope
Input
1.5
Output
1.500
Slope here
1.000
Note
The default for hidden layers.
1.5
The solid line is the function. The dashed line is its slope, which is what training uses. Try it: switch between the four and compare their slopes far from zero. Then look at the step function's slope.
FunctionOutput rangeWhere it is used
ReLU0 and upHidden layers, by default
Sigmoid0 to 1The output of a yes/no network
Tanh−1 to 1Hidden layers of some older and recurrent networks
Step0 or 1Historical. 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.

Figure

Enough neurons to separate the crescents

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
  • 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%
1
Shaded areas are classified as the filled kind. The network is 2 inputs → hidden neurons → 2 outputs. Try it: with ReLU on, raise the hidden neurons from 1 to 3 and watch the boundary fold. Then switch the activation off and move the slider again.

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.

Checkpoint

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.
You can now
  • 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.

Exerciseby hand

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.

Exerciseby hand

A first layer computes h=2x+1h = 2x + 1. A second layer computes y=3h−4y = 3h - 4. There is no activation between them. Write yy directly in terms of xx. What does that tell you?

Hint

Put the first formula into the second and simplify.

Solution

Substitute: y=3(2x+1)−4=6x+3−4=6x−1y = 3(2x + 1) - 4 = 6x + 3 - 4 = 6x - 1.

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.

Exerciseby hand

A small network computes f(x)=ReLU(x)−2 ReLU(x−1)+ReLU(x−2)f(x) = \text{ReLU}(x) - 2\,\text{ReLU}(x - 1) + \text{ReLU}(x - 2). Work out ff at x=0x = 0, 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
  • f(0)=0−0+0=0f(0) = 0 - 0 + 0 = 0
  • f(1)=1−0+0=1f(1) = 1 - 0 + 0 = 1
  • f(2)=2−2+0=0f(2) = 2 - 2 + 0 = 0
  • f(3)=3−4+1=0f(3) = 3 - 4 + 1 = 0

The function is zero up to 0, rises to a peak of 1 at x=1x = 1, falls back to zero at x=2x = 2 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.

Exercisethink

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.

Exercisewith the figure

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

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 15.1Stacking layers
  3. 15.2Two straight lines make a straight line
  4. 15.3A bend: the ReLU
  5. 15.4Many bends make any curve
  6. 15.5Other activation functions
  7. 15.6Bending a boundary
  8. 15.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