Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Multilayer perceptrons and backpropagation

ProblemFit a flexible nonlinear function, built from layers of weighted sums and simple nonlinearities, to regression targets or class labels
Devised byWarren McCulloch and Walter Pitts (1943), the artificial neuron; Frank Rosenblatt (1958), the perceptron; Seppo Linnainmaa (1970), reverse-mode differentiation; Paul Werbos (1974) and David Rumelhart, Geoffrey Hinton and Ronald Williams (1986), backpropagation; George Cybenko (1989) and Kurt Hornik (1991), universal approximation; Diederik Kingma and Jimmy Ba (2014), Adam
AccuracyBackpropagation gives exact gradients, checked against finite differences in the tests; training finds a local minimum of a nonconvex loss
CostForward and backward passes each per mini-batch of rows, for layer widths
Read firstLogistic regression, Gradient descent and nonlinear conjugate gradients
APIMlpClassifier (predict_proba, training_loss), MlpRegressor, MlpParameters (hidden, activation, learning_rate, epochs, batch_size, weight_decay, seed), Activation

Overview

A multilayer perceptron (MLP) composes simple layers: each multiplies its input by a weight matrix, adds a bias, and applies a fixed nonlinear activation elementwise. The last layer gives a number for regression or class probabilities for classification. With enough hidden units, such networks can approximate any continuous function. The weights are learned by gradient descent on a loss, with the gradient computed by backpropagation, the chain rule applied layer by layer from the output back to the input. The MLP is the simplest neural network and the building block of deep learning. On small tabular problems it competes with, rather than beats, kernel machines and boosted trees.

Where it is used

Neural networks fit functions that are too complicated to write down.

  • Computer vision and speech. Image classification, object detection and speech recognition are done by deep versions of the networks in this entry.
  • Engineering surrogate models. A small network can replace an expensive simulation, such as a CFD or a circuit model, in design optimisation.
  • Control and forecasting. Learning nonlinear plant dynamics and predicting load, price or weather.
  • Backpropagation. The gradient algorithm that trains them is the chain rule applied systematically.

History

Warren McCulloch and Walter Pitts (1943) modelled neurons as threshold units, and Frank Rosenblatt’s perceptron (1958) learned the weights of one such layer. Marvin Minsky and Seymour Papert (1969) showed that a single layer cannot represent XOR, and interest faded. Reverse-mode automatic differentiation was described by Seppo Linnainmaa (1970) and applied to networks by Paul Werbos (1974). David Rumelhart, Geoffrey Hinton and Ronald Williams (1986) demonstrated that backpropagation trains hidden layers that learn useful features, which revived the field. George Cybenko (1989) and Kurt Hornik (1991) proved universal approximation. Better initialisation (Xavier Glorot and Yoshua Bengio, 2010; Kaiming He et al., 2015), ReLU activations (Vinod Nair and Hinton, 2010), and adaptive optimisers such as Adam (Diederik Kingma and Jimmy Ba, 2014) made deep networks trainable.

The idea

Layers and activations

A multilayer perceptron is a chain of layers. Each layer takes a vector, multiplies it by a matrix of weights, adds a vector of biases, and applies a simple nonlinear function to each component. With the input , layer computes

Each component of is called a unit; it computes a weighted sum of the previous layer’s outputs and passes it through the activation function . The layers between the input and the output are hidden layers. Common activations are ReLU, , tanh, and the sigmoid .

The last layer depends on the task. For regression its output is left linear and compared with the target by the squared error. For classification it is passed through a softmax, , which turns the outputs into probabilities, and the loss is the cross-entropy , exactly as in logistic regression. A network with no hidden layer is linear or logistic regression.

Why the nonlinearity is essential. A composition of linear maps is a linear map: without , any number of layers would collapse into a single matrix, and the network could represent nothing more than a linear model. With the nonlinearity, each hidden unit contributes a function that varies along one direction of the input space (a ridge), and the next layer adds these up. Enough of them can build curved decision boundaries of any shape:

Two hidden units give little more than a straight line. Eight already follow the moons. Two layers of 64 units, trained for 500 epochs, start to bend around individual points.

Backpropagation

Training adjusts the weights to reduce the loss by gradient descent, which needs the derivative of the loss with respect to every weight in every layer. Computing each derivative separately would be hopelessly slow. Backpropagation computes all of them together, by applying the chain rule in a well-chosen order.

The quantity to propagate. For each layer define

the sensitivity of the loss to the weighted sums of that layer. Everything else follows from these vectors.

Start at the output. For both standard pairings of output and loss (a linear output with squared error, and a softmax with cross-entropy), the derivative works out to the same simple form, the prediction error:

Step backwards. Suppose is known. Layer influences the loss only through layer , by two links: , whose derivative with respect to is , and , whose derivative is component by component. The chain rule multiplies them:

where is the componentwise product. The transpose appears because the sensitivities travel in the opposite direction to the signals: each unit collects the sensitivities of all the units it feeds, weighted by the connections.

Read off the gradients. Since depends on the weights of its own layer through ,

The gradient for a weight is the sensitivity of the unit it feeds times the activation of the unit it comes from.

So training alternates a forward pass, which computes and stores the activations layer by layer, with a backward pass, which computes the ’s from the last layer to the first. The backward pass costs a small multiple of the forward pass, whatever the number of weights. This is the point of reverse-mode differentiation, and the reason networks with millions of parameters can be trained. The derivatives of the activations are written in terms of the activation values themselves ( for tanh, for the sigmoid), so the stored activations are all the backward pass needs.

Adam and mini-batches

Mini-batches. The loss is an average over all the training points, and so is its gradient. Computing the full gradient for every step is wasteful when a rough estimate would do. Each step therefore uses the gradient of a small random subset of the data, a mini-batch (32 rows by default). The data are shuffled and divided into mini-batches, and one full pass through them is an epoch. The gradient is noisy but cheap, and many noisy steps make faster progress than a few exact ones. This is stochastic gradient descent.

Adam. Plain gradient descent uses the same step size for every weight, and choosing it is delicate. Adam adapts the step for each weight separately. It keeps two running averages for each weight: one of the gradient, , and one of its square, . They are exponentially decaying averages (with rates 0.9 and 0.999), which forget old gradients gradually. Both start at zero and so are biased towards zero during the first steps; a correction factor removes the bias, giving and . Each weight is then moved by

The numerator is a smoothed gradient, which damps the noise of the mini-batches. The denominator is the typical recent size of that weight’s gradient, so the ratio is of order 1 for every weight, and each moves by about per step regardless of the scale of its gradient. This makes the learning rate far less sensitive than in plain gradient descent, though it still matters:

Figure 13.1. Training loss for several learning rates.

At training is slow; at and it converges; at the steps are too large and the loss bounces around a value several times higher.

Initialisation and scaling

Weights start random and small, so that units differ and signals neither vanish nor explode through the layers: Glorot’s variance for tanh and sigmoid, He’s for ReLU. The library standardises the inputs, and for regression the targets, before training, because gradient-based training is sensitive to scales.

Activations and smoothness

Figure 13.2. MLP regression of a sine.

A ReLU network is piecewise linear, with kinks wherever a unit switches on. A tanh network is smooth. Both fit the sine where there are data. Beyond the data, on the right, both continue along straight lines, since every unit is saturated or linear there. What a network does outside the data is therefore decided by its activation function, not by the data: ReLU units continue linearly and saturating units flatten out, and neither continues the sine. On the two classification benchmarks:

Table 13.2. Activation functions compared.

activation (32 × 32, 200 epochs)moons: test accuracyfinal training losstraining timecircles: test accuracyfinal training loss
ReLU0.9240.13534 ms0.9980.004
tanh0.9310.17869 ms0.9980.005
sigmoid0.8610.30743 ms0.9980.023

The sigmoid converges slowest per epoch: its final training loss is the highest in both columns (tanh happens to take the most wall-clock time, because evaluating it costs more than a ReLU comparison). Its derivative is at most 1/4, so gradients shrink at every layer, the vanishing gradient problem that ReLU avoids.

Overfitting and weight decay

A network with thousands of weights can memorise 120 points. Weight decay adds to the loss, shrinking the weights towards zero as ridge regression does:

Table 13.3. Effect of weight decay on an over-parameterised network.

weight decay λ (64 × 64, 120 training points)training accuracytest accuracy
01.0000.909
0.0010.9670.932
0.010.7920.862
0.10.7920.861
10.5000.500

Without decay the network reaches 100% training accuracy and 91% on test data. A little decay trades training accuracy for test accuracy; too much flattens the network into a constant. Early stopping, dropout and more data are the other remedies.

Algorithm

Training.

  1. Prepare. Standardise the inputs, and for regression the targets. Initialise the weights at random (Glorot’s variance for tanh and sigmoid, He’s for ReLU) and the biases to zero.
  2. For each epoch: shuffle the rows of the training data, and divide them into mini-batches. For each mini-batch:
    • forward pass: compute and store and for every layer, for all the rows of the batch at once (as matrices with one row per sample);
    • loss: the mean squared error or cross-entropy over the batch;
    • backward pass: compute from the output and the targets, then for each earlier layer, and from them the gradients of the weights and biases, averaged over the batch; add to each weight gradient for weight decay;
    • Adam step: update the two running averages for every weight and bias, correct their bias, and move the parameter.
  3. Monitor. Record the mean training loss of the epoch. If it is infinite or NaN (the sign of a learning rate that is far too large), stop with an error.

One epoch costs a small multiple of (number of samples) × (number of weights).

Prediction. Standardise the input with the stored means and standard deviations, run the forward pass, and return the class of largest probability, or for regression the output transformed back to the original units of the target.

Implementation

    /// The mean loss over the batch (plus the weight penalty) and its gradients.
    fn loss_and_gradient(&self, x: &R2D, targets: &R2D, weight_decay: f64) -> (f64, Vec<R2D>, Vec<R1D>) {
        let a = self.forward(x);
        let batch = x.nrows() as f64;
        let output = a.last().expect("at least one layer");
        let data_loss = match self.output {
            Output::Linear => 0.5 * (output - targets).mapv(|v| v * v).sum() / batch,
            Output::Softmax => -(output.mapv(|p| p.max(1e-300).ln()) * targets).sum() / batch,
        };
        let penalty = 0.5 * weight_decay * self.w.iter().map(|w| w.mapv(|v| v * v).sum()).sum::<f64>();
        // For both pairings (linear + squared error, softmax + cross-entropy) δ_L = (ŷ − y)/B.
        let mut delta = (output - targets) / batch;
        let layers = self.w.len();
        let mut gw = vec![R2D::zeros((0, 0)); layers];
        let mut gb = vec![R1D::zeros(0); layers];
        for l in (0..layers).rev() {
            // Assigned into a row-major array: the product can come back column-major (for example
            // when an activation matrix has a single column), and the Adam step reads the gradient
            // as a flat slice in the same order as the weights.
            let mut g = R2D::zeros(self.w[l].dim());
            g.assign(&delta.t().dot(&a[l]));
            g.scaled_add(weight_decay, &self.w[l]);
            gw[l] = g;
            gb[l] = delta.sum_axis(Axis(0));
            if l > 0 {
                let back = delta.dot(&self.w[l]);
                delta = back * a[l].mapv(|v| self.activation.derivative(v));
            }
        }
        (data_loss + penalty, gw, gb)
    }
    fn step(&mut self, parameters: &mut [f64], gradient: &[f64], rate: f64, t: i32) {
        let (b1, b2, eps) = (0.9f64, 0.999f64, 1e-8);
        let (c1, c2) = (1.0 - b1.powi(t), 1.0 - b2.powi(t));
        for i in 0..parameters.len() {
            self.m[i] = b1 * self.m[i] + (1.0 - b1) * gradient[i];
            self.v[i] = b2 * self.v[i] + (1.0 - b2) * gradient[i] * gradient[i];
            parameters[i] -= rate * (self.m[i] / c1) / ((self.v[i] / c2).sqrt() + eps);
        }
    }
  • The weight gradient is assigned into a row-major array. The Adam step reads gradients and weights as flat slices, so a column-major matrix product (which can occur with a single input feature) would be read in the wrong order.
  • Predictions check the number of features, so a one-column input is not silently broadcast against two training features.
  • Training is deterministic for a given seed, which sets both the initial weights and the shuffling.

In practice

//! Multilayer perceptrons: classifying two moons and fitting a sine.

use lib_jsl_core::R2D;
use lib_jsl_machine_learning::common::{Classifier, Regressor};
use lib_jsl_machine_learning::datasets::{make_moons, make_sine};
use lib_jsl_machine_learning::metrics::{accuracy, mean_squared_error};
use lib_jsl_machine_learning::neural_network::{Activation, MlpClassifier, MlpParameters, MlpRegressor};

fn main() {
    let (x, labels) = make_moons(200, 0.2, 1);
    let (test, test_labels) = make_moons(500, 0.2, 2);
    let mut clf = MlpClassifier::new(MlpParameters { hidden: vec![32, 32], activation: Activation::Relu, epochs: 200, seed: 1, ..Default::default() });
    clf.fit(x.view(), &labels).unwrap();
    let loss = &clf.training_loss;
    println!("cross-entropy: epoch 1 {:.3}, epoch 50 {:.3}, epoch 200 {:.3}", loss[0], loss[49], loss[199]);
    println!("test accuracy {:.3}", accuracy(&test_labels, &clf.predict(test.view()).unwrap()).unwrap());
    let p = clf.predict_proba(ndarray::arr2(&[[0.5, 0.25], [-1.0, 0.5]]).view()).unwrap();
    println!("P(class 1) at (0.5, 0.25): {:.3}; at (-1, 0.5): {:.3}", p[[0, 1]], p[[1, 1]]);

    let (sx, sy) = make_sine(100, 0.1, 3);
    let mut reg = MlpRegressor::new(MlpParameters { hidden: vec![16, 16], epochs: 1000, batch_size: 16, seed: 2, ..Default::default() });
    reg.fit(sx.view(), sy.view()).unwrap();
    let grid = R2D::from_shape_fn((50, 1), |(i, _)| 0.3 + 5.6 * i as f64 / 49.0);
    let truth = grid.column(0).mapv(f64::sin);
    println!("sine: MSE against sin x {:.5}", mean_squared_error(truth.view(), reg.predict(grid.view()).unwrap().view()).unwrap());
}
cross-entropy: epoch 1 0.407, epoch 50 0.059, epoch 200 0.043
test accuracy 0.964
P(class 1) at (0.5, 0.25): 0.159; at (-1, 0.5): 0.000
sine: MSE against sin x 0.00377

Strengths

  • Universal approximators that learn their own features; one method for regression and multi-class classification.
  • Training scales linearly with the data, by mini-batches.

Weaknesses

  • Nonconvex training with many settings (architecture, learning rate, epochs, decay) that interact; results vary with the seed.
  • On small tabular data, usually no better than kernel machines or boosted trees, and slower to train.
  • No extrapolation, and probabilities that can be overconfident far from the data.

Exercises

  1. Show that a network with linear activations, of any depth, is a linear function of its input.
  2. Derive for softmax with cross-entropy.
  3. Construct a network with two hidden ReLU units that computes XOR exactly.
  4. Show that Adam’s bias correction makes an unbiased estimate of the mean gradient when the gradients are stationary.
  5. Train the same network with ten different seeds and report the spread of the test accuracy.
Hints and answers
  1. A composition of affine maps is affine: .
  2. For softmax outputs and cross-entropy , since .
  3. Take , and output : the inputs give .
  4. With and stationary , ; dividing by removes the bias.
  5. Report the mean and the standard deviation (or range) of the test accuracy over the ten seeds; the spread shows how much of any difference between two configurations is just initialisation noise.

Further reading

  • D. E. Rumelhart, G. E. Hinton and R. J. Williams, “Learning representations by back-propagating errors”, Nature 323 (1986) 533–536.
  • D. P. Kingma and J. Ba, “Adam: a method for stochastic optimization”, arXiv:1412.6980, 2014.
  • I. Goodfellow, Y. Bengio and A. Courville, Deep Learning, MIT Press, 2016, chapters 6–8.
  • X. Glorot and Y. Bengio, “Understanding the difficulty of training deep feedforward neural networks”, Proceedings of AISTATS (2010) 249–256.