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 () and only their weights were fitted. A neural network also learns the features. Its building block is the neuron.
DefinitionNeuron
Many neurons side by side, all reading the same inputs, form a layer; in matrix form, , with one row of per neuron, and now vectors with one entry per neuron, and 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.
ReLU, , is the default in many fields. tanh is smooth and bounded. SiLU (also called swish), , 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 inputs to neurons has weights and 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, ; 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.
# 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
- The first layer reads the 2 inputs, so its weight matrix has the shape
(64, 2), one row per neuron. - The last layer has no activation, so the output can take any value.
- Layers expect a batch first: the shape
(1, 2)is a batch of one design with two inputs. - .
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.