Skip to content
Building Blocks

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 nn input values x1,…,xnx_1, \ldots, x_n, computes a weighted sum, adds a scalar bias, and passes the result through an activation function:

z=w1x1+w2x2+⋯+wnxn+b=w⋅x+bz = w_1 x_1 + w_2 x_2 + \cdots + w_n x_n + b = \mathbf{w} \cdot \mathbf{x} + b y=σ(z)y = \sigma(z)

The weights w∈Rn\mathbf{w} \in \mathbb{R}^n and the bias b∈Rb \in \mathbb{R} are the neuron's trainable parameters. The activation σ\sigma introduces non-linearity. Without σ\sigma, this is just a linear function of the inputs, and stacking such units would not extend the network's expressive power.

x₁x₂x₃zw₁w₂w₃+ bσ(z)z = w₁x₁ + w₂x₂ + w₃x₃ + b, output y = σ(z)

Why bias matters. Without the bias term, every neuron's pre-activation z=w⋅xz = \mathbf{w} \cdot \mathbf{x} is zero whenever x=0\mathbf{x} = \mathbf{0}. 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 mm neurons that all receive the same input x∈Rn\mathbf{x} \in \mathbb{R}^n and each produce one output, giving an output vector z∈Rm\mathbf{z} \in \mathbb{R}^m.

Writing the mm neurons' weight vectors as rows of a matrix W∈Rm×n\mathbf{W} \in \mathbb{R}^{m \times n}, the entire layer computes:

z=Wx+b\mathbf{z} = \mathbf{W}\mathbf{x} + \mathbf{b}

where b∈Rm\mathbf{b} \in \mathbb{R}^m stacks the individual biases. This is exactly the matrix-vector product from the Matrices article. The layer applies mm linear transformations simultaneously, one per output neuron.

Parameter count. A linear layer with nn inputs and mm outputs has m×nm \times n weight parameters plus mm bias parameters, for a total of m(n+1)m(n + 1).

Example. A layer mapping 33 inputs to 44 outputs has 4×3+4=164 \times 3 + 4 = 16 parameters.

For a batch of BB examples packed into a matrix X∈RB×n\mathbf{X} \in \mathbb{R}^{B \times n} (one example per row), the layer processes all examples simultaneously:

Z=XW⊤+b\mathbf{Z} = \mathbf{X}\mathbf{W}^\top + \mathbf{b}

giving Z∈RB×m\mathbf{Z} \in \mathbb{R}^{B \times m} where each row ii holds the pre-activations for example ii.

Stacking Layers

A multilayer perceptron (MLP), also called a feedforward network, chains linear layers with activations:

h1=σ(W1x+b1)\mathbf{h}_1 = \sigma(\mathbf{W}_1 \mathbf{x} + \mathbf{b}_1) h2=σ(W2h1+b2)\mathbf{h}_2 = \sigma(\mathbf{W}_2 \mathbf{h}_1 + \mathbf{b}_2) y^=W3h2+b3\hat{\mathbf{y}} = \mathbf{W}_3 \mathbf{h}_2 + \mathbf{b}_3

Each hidden layer hk\mathbf{h}_k 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).

inputhiddenσ(Wx + b)output3 → 4 → 2 fully connected network (16 + 10 = 26 parameters)

Numerical example. A 3 → 2 → 1 network with ReLU hidden layer:

W1=(0.50.30.10.20.80.4),b1=(0.1−0.2),x=(123)\mathbf{W}_1 = \begin{pmatrix} 0.5 & 0.3 & 0.1 \\ 0.2 & 0.8 & 0.4 \end{pmatrix}, \quad \mathbf{b}_1 = \begin{pmatrix} 0.1 \\ -0.2 \end{pmatrix}, \quad \mathbf{x} = \begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix} z1=W1x+b1=(1.52.8),h1=ReLU(z1)=(1.52.8)\mathbf{z}_1 = \mathbf{W}_1\mathbf{x} + \mathbf{b}_1 = \begin{pmatrix} 1.5 \\ 2.8 \end{pmatrix}, \quad \mathbf{h}_1 = \text{ReLU}(\mathbf{z}_1) = \begin{pmatrix} 1.5 \\ 2.8 \end{pmatrix} W2=(0.30.7),b2=(0.5)\mathbf{W}_2 = \begin{pmatrix} 0.3 & 0.7 \end{pmatrix}, \quad \mathbf{b}_2 = \begin{pmatrix} 0.5 \end{pmatrix} y^=W2h1+b2=0.3×1.5+0.7×2.8+0.5=2.91\hat{y} = \mathbf{W}_2\mathbf{h}_1 + \mathbf{b}_2 = 0.3 \times 1.5 + 0.7 \times 2.8 + 0.5 = 2.91

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 z=Wx+b\mathbf{z} = \mathbf{W}\mathbf{x} + \mathbf{b}, given the upstream gradient ∂L∂z\frac{\partial L}{\partial \mathbf{z}}:

∂L∂W=∂L∂z⋅x⊤∂L∂b=∂L∂z∂L∂x=W⊤∂L∂z\frac{\partial L}{\partial \mathbf{W}} = \frac{\partial L}{\partial \mathbf{z}} \cdot \mathbf{x}^\top \qquad \frac{\partial L}{\partial \mathbf{b}} = \frac{\partial L}{\partial \mathbf{z}} \qquad \frac{\partial L}{\partial \mathbf{x}} = \mathbf{W}^\top \frac{\partial L}{\partial \mathbf{z}}

The gradient with respect to W\mathbf{W} has the same shape as W\mathbf{W} and is used by the optimizer to update the weights. The gradient with respect to x\mathbf{x} 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.