Neurons, layers and MLPs

A neural network is a flexible regression model built from simple layers.

Outcome: Write a neuron as a weighted sum plus an activation; explain why a nonlinear activation is needed; build an MLP with nn.Module and count its parameters.

Builds on Fitting a response surface

In fitting a response surface the features were chosen by hand (α2,αΛ,…\alpha^2, \alpha\Lambda, \dots) and only their weights were fitted. A neural network also learns the features. Its building block is the neuron.

DefinitionNeuron

A weighted sum of its inputs plus a constant (the bias), passed through a fixed nonlinear function called the activation.
h=ϕ(w⋅x+b)h = \phi(w \cdot x + b)
(4-1)
xx: the inputs. ww: the weights. bb: the bias. ϕ\phi: the activation function. hh: the neuron’s output.

Many neurons side by side, all reading the same inputs, form a layer; in matrix form, h=ϕ(Wx+b)h = \phi(Wx + b), with one row of WW per neuron, hh and bb now vectors with one entry per neuron, and ϕ\phi applied to each entry on its own. The outputs of one layer are the inputs of the next. A stack of such layers is a multilayer perceptron (MLP). The number of neurons in a layer is its width, the number of layers its depth. The inner layers are called hidden layers; the last layer usually has no activation, so it can output any value.

The role of the activation

Without activations, each layer is a linear map plus a constant, and a stack of those is again one linear map plus a constant: a deep network would be no more capable than the plane of the regression lesson. The bend in the activation is what lets layers combine into curved surfaces.

-101234-4-2024input zoutput
ReLU: max(0, z)tanh(z)SiLU: z · sigmoid(z)
Figure 4-1. ReLU, tanh and SiLU: three common activations.

ReLU, max⁡(0,x)\max(0, x), is the default in many fields. tanh is smooth and bounded. SiLU (also called swish), x/(1+e−x)x / (1 + e^{-x}), is smooth like tanh but unbounded above like ReLU; the aircraft networks of this unit use it, since the functions they fit are smooth.

With at least one hidden layer, enough neurons and a non-polynomial activation, an MLP can approximate any continuous function on a closed, bounded set of inputs to any accuracy. This is the universal approximation theorem, first proved for sigmoid-shaped activations (Hornik et al. 1989) and stated here in the form of Leshno et al. 1993.

Counting weights

A layer from nn inputs to mm neurons has n×mn \times m weights and mm biases; activations add none. The MLP of Example 4-1 below holds 4,417; the surrogates in recent papers often have millions.

In PyTorch a model is an nn.Module: layers are created in __init__ and applied in forward. nn.Linear(n, m) is one layer of weighted sums, Wx+bWx + b; nn.Sequential chains layers. PyTorch stores all numbers in tensors: n-dimensional arrays, like NumPy’s, that can also live on a GPU (a graphics processor, the chip most neural networks are trained on) and can record the operations applied to them, so that gradients can be computed automatically: PyTorch’s autograd.

Example 4-1. An MLP with two hidden layers, as a PyTorch module, added to aircraft.py
# Add to aircraft.py, with its other imports at the top:
import torch
from torch import nn

class MLP(nn.Module):
    # 2 inputs (alpha, sweep), two hidden layers, 1 output (CL).
    def __init__(self, width=64):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(2, width), nn.SiLU(),1
            nn.Linear(width, width), nn.SiLU(),
            nn.Linear(width, 1),2
        )

    def forward(self, x):
        return self.net(x)

# Then, in a script:
import torch
from aircraft import MLP

torch.manual_seed(0)
model = MLP()
# One design, normalised. Untrained: the number means nothing yet.
print(model(torch.tensor([[0.2, -0.5]])))3
# 4417 weights and biases.
print(sum(p.numel() for p in model.parameters()))4
  1. The first layer reads the 2 inputs, so its weight matrix WW has the shape (64, 2), one row per neuron.
  2. The last layer has no activation, so the output can take any value.
  3. Layers expect a batch first: the shape (1, 2) is a batch of one design with two inputs.
  4. (2×64+64)+(64×64+64)+(64×1+1)=4417(2 \times 64 + 64) + (64 \times 64 + 64) + (64 \times 1 + 1) = 4417.

Example 4-1 prints tensor([[0.1143]], grad_fn=<AddmmBackward0>), then 4417. The first number comes from random starting weights, fixed here by the seed; grad_fn shows that autograd recorded the operations (loss, gradients and autograd). Fitting the weights to the runs needs a measure of the error and a way to reduce it.