Linear Layers
What a neuron computes, how neurons combine into layers, and how layers stack into a network.
The previous article showed that activation functions must be applied to something. That something is the output of a linear layer: a learned affine transformation of the layer's input. Linear layers are the primary mechanism by which a network combines information — they are where the trainable weights live.
The Single Neuron
The most basic unit is a single neuron (also called a unit or perceptron). It takes input values , computes a weighted sum, adds a scalar bias, and passes the result through an activation function:
The weights and the bias are the neuron's trainable parameters. The activation introduces non-linearity. Without , this is just a linear function of the inputs, and stacking such units would not extend the network's expressive power.
Why bias matters. Without the bias term, every neuron's pre-activation is zero whenever . The bias shifts the activation threshold, allowing the neuron to fire even with zero input. Concretely, for ReLU: without bias, any neuron connected to an all-zero input is permanently inactive. With bias, the threshold is tunable.
A Layer of Neurons
A single neuron produces one output. A layer groups neurons that all receive the same input and each produce one output, giving an output vector .
Writing the neurons' weight vectors as rows of a matrix , the entire layer computes:
where stacks the individual biases. This is exactly the matrix-vector product from the Matrices article. The layer applies linear transformations simultaneously, one per output neuron.
Parameter count. A linear layer with inputs and outputs has weight parameters plus bias parameters, for a total of .
Example. A layer mapping inputs to outputs has parameters.
For a batch of examples packed into a matrix (one example per row), the layer processes all examples simultaneously:
giving where each row holds the pre-activations for example .
Stacking Layers
A multilayer perceptron (MLP), also called a feedforward network, chains linear layers with activations:
Each hidden layer is a new representation of the input. The activation after each layer prevents collapse to a single affine transformation. The final layer typically has no activation (for regression) or is followed by a sigmoid or softmax (for classification).
Numerical example. A 3 → 2 → 1 network with ReLU hidden layer:
Each layer transforms the representation. Layer 1 mixes the three raw inputs into two hidden features; layer 2 combines those features into a single prediction.
Width and Depth
Two knobs control the capacity of an MLP: width (neurons per layer) and depth (number of layers).
Width adds more neurons to a layer. More neurons means more parameters and a richer per-layer transformation. A sufficiently wide single hidden layer can theoretically approximate any function (the universal approximation theorem), but the required width can be enormous.
Depth adds more layers. Deeper networks learn hierarchical representations: early layers detect simple patterns, later layers combine them into abstract concepts. For the same total parameter budget, deeper networks often generalize better because each layer builds on the features extracted by the previous one. This is the empirical observation that motivates architectures with many layers.
In practice, a 2–4 layer MLP handles most tabular data tasks. Image and sequence models require more depth, but they also introduce specialized layers beyond the fully connected design.
Backpropagation Through a Linear Layer
The chain rule applies cleanly to linear layers. For the layer , given the upstream gradient :
The gradient with respect to has the same shape as and is used by the optimizer to update the weights. The gradient with respect to propagates the signal to earlier layers. The autograd engine builds this backward function automatically when the layer is applied during the forward pass.
In Code
import torch
import torch.nn as nn
import torch.nn.functional as F
# ── Numerical example: explicit weights matching the article text ───────────
W1 = torch.tensor([[0.5, 0.3, 0.1],
[0.2, 0.8, 0.4]], requires_grad=True) # (2, 3)
b1 = torch.tensor([0.1, -0.2], requires_grad=True) # (2,)
x = torch.tensor([1.0, 2.0, 3.0])
z1 = x @ W1.T + b1 # (3,) @ (3, 2) + (2,) → (2,)
h1 = F.relu(z1)
print(z1) # tensor([1.5000, 2.8000], grad_fn=...)
print(h1) # tensor([1.5000, 2.8000], grad_fn=...)
W2 = torch.tensor([[0.3, 0.7]], requires_grad=True) # (1, 2)
b2 = torch.tensor([0.5], requires_grad=True) # (1,)
y_hat = h1 @ W2.T + b2
print(y_hat) # tensor([2.9100], grad_fn=...)
target = torch.tensor([3.0])
loss = F.mse_loss(y_hat, target)
loss.backward()
print(W1.grad) # (2, 3) — ∂L/∂W1
print(W2.grad) # (1, 2) — ∂L/∂W2
# ── Clean approach: nn.Linear ───────────────────────────────────────────────
# nn.Linear(in, out) initialises the weights U(−1/√in, 1/√in) and computes x @ W.T + b.
# Weight shape is (out_features, in_features).
layer1 = nn.Linear(3, 2) # 3 inputs → 2 outputs
layer2 = nn.Linear(2, 1) # 2 inputs → 1 output
print(layer1.weight.shape) # torch.Size([2, 3])
print(layer1.bias.shape) # torch.Size([2])
x = torch.tensor([1.0, 2.0, 3.0])
h = F.relu(layer1(x)) # layer1(x) computes x @ W.T + b
y_hat = layer2(h)
loss = F.mse_loss(y_hat, torch.tensor([0.0]))
loss.backward()
print(layer1.weight.grad.shape) # torch.Size([2, 3]) — gradient flows to W1 automatically
print(layer2.weight.grad.shape) # torch.Size([1, 2]) — gradient flows to W2 automatically
# ── MLP: Sequential + cross-entropy + Adam ──────────────────────────────────
# 3-class classification: 4 input features → 8 hidden → 3 output logits.
# nn.Sequential stacks layers and exposes all their parameters as one model,
# so model.parameters() gives the optimizer every weight and bias at once.
model = nn.Sequential(
nn.Linear(4, 8),
nn.ReLU(),
nn.Linear(8, 3),
)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
# Four training examples (a batch), with their class index
X = torch.tensor([
[ 1.0, 0.5, -0.2, 0.8], # class 0
[-0.5, 1.2, 0.3, -0.1], # class 1
[ 0.2, -0.8, 1.0, 0.4], # class 2
[-0.3, 0.1, -0.7, 1.1], # class 0
])
Y = torch.tensor([0, 1, 2, 0])
for step in range(20):
optimizer.zero_grad()
logits = model(X) # (4, 4) → (4, 3) through the two linear layers
loss = F.cross_entropy(logits, Y) # scalar: mean cross-entropy over the 4 examples
loss.backward()
optimizer.step()
if step % 5 == 0:
print(f"step {step:2d} loss={loss.item():.4f}")
# loss decreases from ~1.1 (near random) toward 0 as the model fits the batch
Linear layers are the workhorses of any neural network: they combine and transform information, and their weights encode everything the network has learned. Activation functions introduce non-linearity between them; the next article covers two further operations that help networks train reliably — regularization techniques that prevent overfitting and stabilize learning.