Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Multi-Layer Perceptrons (MLPs)

KTH JupyterHub Open In Colab Binder

A Multi-Layer Perceptron (MLP) is a class of feedforward artificial neural network. An MLP consists of at least three layers: an input layer, one or more hidden layers, and an output layer. Each layer is fully connected to the next, and the network is trained using backpropagation to adjust the weights based on the error.

MLPs are widely used in supervised learning tasks such as classification and regression. They can model complex, non-linear relationships between input and output by stacking multiple layers of neurons.

Artificial Neuron

An artificial neuron is a fundamental building block of neural networks. It is inspired by the biological neuron and functions as a mathematical model that takes multiple inputs, processes them, and produces an output. The artificial neuron makes a linear combination of its input that is forwarded to a non-linear activation function. This can be expressed as:

f(x;w,b)=g(∑i=1nwixi+b)f(\mathbf{x};\mathbf{w},b) = g(\sum_{i=1}^n w_i x_i + b)

This expression can be broken down into these two steps:

  1. Linear combination: Each input is multiplied by a weight, and then all the weighted inputs are summed together. Additionally, a bias term is added to the sum. Mathematically, this can be represented as:

    z=∑i=1nwixi+bz = \sum_{i=1}^n w_i x_i + b

    Where:

    • xix_i are the inputs

    • wiw_i are the weights

    • bb is the bias term

  2. Activation Function: The weighted sum is passed through an activation function, g(z)g(z), to introduce non-linearity. Common activation functions include:

    • Sigmoid: Maps the input to a value between 0 and 1.

    • ReLU (Rectified Linear Unit): Sets all negative values to zero and passes positive values unchanged.

    • Tanh: Maps the input to a value between -1 and 1.

The output of the activation function becomes the output of the neuron, which can then be used as input to other neurons.

Components of an MLP

An example MLP with an input layer, two hidden layers and an output layer.

Figure 1:An example MLP with an input layer, two hidden layers and an output layer.

  1. Input Layer: The input layer consists of neurons that receive the raw data. Each neuron in the input layer represents a feature of the input data.

  2. Hidden Layers: Between the input and output layers are one or more hidden layers. Neurons in the hidden layers receive input from the previous layer, process it, and pass the output to the next layer. Adding more hidden layers allows the network to learn more complex relationships in the data.

  3. Output Layer: The output layer produces the final prediction or classification. The number of neurons in this layer depends on the type of task (e.g., a single neuron for binary classification or multiple neurons for multi-class classification).

Neurons in each layer are fully connected to neurons in the subsequent layer, meaning each neuron receives input from all neurons in the previous layer. The strength of these connections is determined by the weights, which are adjusted during training to minimize the error between the predicted output and the actual output.

Training an MLP

MLPs are trained using backpropagation and gradient descent. The process involves the following steps:

  1. Forward Pass: Input data passes through the network, and predictions are generated.

  2. Loss Calculation: A loss function (e.g., mean squared error for regression or cross-entropy for classification) is used to measure the error between the predictions and true labels.

  3. Backward Pass: Gradients of the loss with respect to the weights are computed, using the chain rule. Weights are then updated using optimization techniques, often gradient descent-based techniques. A more detailed description can be found in the Wikipedia entry.

Example: Training an MLP on Artificial Data

In this example, we’ll use scikit-learn’s make_moons to generate artificial data from two classes, shaped as two interleaving half-moons that are not linearly separable, and train an MLP to classify them.

Notebook Cell
Epoch 0, Loss: 0.7422
Epoch 100, Loss: 0.3153
Epoch 200, Loss: 0.3069
Epoch 300, Loss: 0.2944
Epoch 400, Loss: 0.2535
Epoch 500, Loss: 0.1821
Epoch 600, Loss: 0.1342
Epoch 700, Loss: 0.1112
Epoch 800, Loss: 0.0996
Epoch 900, Loss: 0.0931
Accuracy: 0.97
<Figure size 800x600 with 1 Axes>

The code builds an MLP with two inputs, two hidden layers of 10 and 5 sigmoid neurons, and a single sigmoid output neuron that gives the probability that a point belongs to class 1. In each of the 1,000 epochs, it carries out the four training steps on all 700 training points:

  1. Forward pass: z1, z2 and z_out are the linear combinations computed by each layer, and a1, a2 and y_pred the corresponding sigmoid activations.

  2. Loss: the binary cross-entropy between the predictions y_pred and the true labels y_train, averaged over the training points.

  3. Backward pass: starting from the derivative of the loss with respect to y_pred, the chain rule is applied layer by layer, by multiplying with the derivative of the sigmoid (sigmoid_derivative) and with the transposed weight matrix of the layer above, which gives the gradients of the loss with respect to all weights (d_loss_weights_*) and biases (d_loss_bias_*).

  4. Update: each weight and bias takes a gradient descent step, the gradient multiplied by the learning rate, here 1.0. A learning rate that is too high makes the updates overshoot and the loss oscillate or diverge, while one that is too low makes training slow.

The loss falls from 0.74 to 0.09, and the trained network classifies 97% of the test points correctly, with a curved decision boundary that follows the gap between the two half-moons. The number and size of the hidden layers set the capacity of the network: more neurons allow more complex decision boundaries, but also make it easier to overfit the training data.

We could have simplified the task by using the MLPClassifier from sklearn (but then without seeing the inner workings of the classifier). For those of you interested, see below.

Notebook Cell
Accuracy: 0.97
<Figure size 800x600 with 1 Axes>

A workbench for MLPs

The TensorFlow Playground is a nice workbench for MLPs, where you can investigate interactively how the choice of input features, architecture, and regularization affects the performance on different datasets.

What you should know after reading this chapter

You should be able to:

  1. Write down the output of an artificial neuron, f(x;w,b)=g(∑i=1nwixi+b)f(\mathbf{x};\mathbf{w},b) = g(\sum_{i=1}^n w_i x_i + b), and calculate it by hand for given inputs, weights, bias and activation function.

  2. Describe the sigmoid, ReLU and tanh activation functions, including the range of values each one outputs, and explain that the activation function is what makes a neuron non-linear.

  3. Describe the structure of an MLP: an input layer with one neuron per feature, one or more fully connected hidden layers, and an output layer whose number of neurons depends on the task.

  4. Describe the steps of training an MLP: the forward pass, the loss calculation, the backward pass where backpropagation uses the chain rule to compute the gradients of the loss with respect to the weights, and the gradient descent update of the weights.

  5. Explain how the number and size of the hidden layers affect the capacity of an MLP and its risk of overfitting, and what happens when the learning rate is too high or too low.

  6. Explain why an MLP, unlike a linear classifier, can find a curved decision boundary that separates classes that are not linearly separable, such as the two half-moons in the example.