Sign in

Multilayer perceptron (MLP)

Multilayer Perceptron

A multilayer perceptron: a stack of fully connected layers with a non-linear function between them, trained by backpropagation.

Overview

A linear model can only draw a flat boundary. A multilayer perceptron first passes the input through a hidden layer of units, each of which computes its own weighted sum and then bends it with a non-linear function such as ReLU. The next layer works on those bent values instead of the raw input. Stacking a few such layers lets the network build curved boundaries out of simple pieces. Training sends the output error backward through the layers to work out how each weight should change. This template is a small NumPy version with manual gradients, meant for learning and for small tabular problems.

A short history

Frank Rosenblatt's perceptron of 1958 had a single trainable layer, and in 1969 Marvin Minsky and Seymour Papert showed that such a layer cannot represent functions like exclusive or. Adding hidden layers solves this, and in 1986 Rumelhart, Hinton and Williams showed how to train them with backpropagation. In 1989 George Cybenko proved that one hidden layer can approximate any continuous function, given enough units.

How it works

  1. Initialise each weight matrix at random, scaled by the layer's input width: He scaling for relu, Xavier scaling for tanh. Biases start at zero.
  2. Forward pass: each hidden layer computes ai=ϕ(ai−1Wi+bi)\mathbf{a}_i = \phi(\mathbf{a}_{i-1} W_i + \mathbf{b}_i). The last layer has no activation.
  3. Compute the loss: softmax cross-entropy for classification, half squared error for regression, plus the l2 term on the weight matrices.
  4. Backward pass: start from the output error and move it back one layer at a time, multiplying by the layer's weights and by the slope of its activation.
  5. Read off the gradient of each weight matrix as the layer's input times the error arriving at its output.
  6. Update all parameters with Adam on shuffled mini-batches, and record the mean loss per epoch in loss_history_.

Watch out for

  • With ReLU, a unit whose input is negative for every row gets zero gradient and stops learning. A large lr makes this more likely.
  • Features on very different scales make training slow or unstable, because one weight matrix has to serve all of them. Standardise the inputs first.
  • A wide network can memorise a small training set and still do badly on new rows. Watch a held-out loss and use l2 or fewer units.
  • The loss surface is not convex, so different seeds give different weights and slightly different scores. Compare runs across seeds before drawing conclusions.

Use cases

When to use it

Tabular or vector data where the relationship is non-linear and a linear model underfits. It is also the building block inside larger networks such as transformer feed-forward layers and recommendation towers.

In industry

Recommendation and ads
The dense tower that turns concatenated embeddings into a click or relevance score in most ranking models.
Engineering
Surrogate models: a network trained on simulation results that gives fast approximate answers for design search.
Insurance and finance
Predicting a number such as claim cost from a fixed set of scaled features, often compared against boosted trees.

Choosing it: what must hold

  • A fixed-length numeric input; categorical columns must be encoded or embedded first.
  • Scaled features and a sensible weight initialisation.
  • Enough data to justify the extra capacity over a linear model.

When to choose something else

IfUse instead
A plain table with limited rowsXGBoost, LightGBM or a random forest
Inputs have spatial structureA convolutional network (CNN)
Inputs are sequences of varying lengthA GRU, an LSTM or a Transformer
A linear model already fits wellLinear regression or logistic regression

Math foundations

  1. One layer

    ai=ϕ ⁣(ai−1Wi+bi),a0=x\mathbf{a}_i = \phi\!\left(\mathbf{a}_{i-1} W_i + \mathbf{b}_i\right), \qquad \mathbf{a}_0 = \mathbf{x}

    Each layer takes the previous layer's output as a row vector, applies a linear map and then the activation ϕ\phi. Without ϕ\phi the whole stack would collapse into a single linear map.

  2. Softmax output

    pk=eok∑j=1Ceojp_k = \frac{e^{o_k}}{\sum_{j=1}^{C} e^{o_j}}

    Turns the final scores o\mathbf{o} into class probabilities that are positive and sum to 1.

  3. The loss

    L=−1n∑i=1nlog⁡pi,yi+λ2∑l∥Wl∥2L = -\frac{1}{n}\sum_{i=1}^{n} \log p_{i, y_i} + \frac{\lambda}{2}\sum_{l} \lVert W_l \rVert^2

    Mean cross-entropy: the negative log of the probability given to the true class, plus the l2 penalty. For regression the first term is replaced by 12n∑i∥oi−yi∥2\frac{1}{2n}\sum_i \lVert \mathbf{o}_i - \mathbf{y}_i \rVert^2.

  4. Error at the output

    δout=1n(p−ey)\boldsymbol{\delta}_{\text{out}} = \frac{1}{n}\left(\mathbf{p} - \mathbf{e}_{y}\right)

    The gradient of the loss with respect to the output scores: predicted probabilities minus the one-hot target. For regression it is (o−y)/n(\mathbf{o} - \mathbf{y})/n. This is where backpropagation starts.

  5. Backpropagating one layer

    δi−1=(δiWi⊤)⊙ϕ′(zi−1)\boldsymbol{\delta}_{i-1} = \left(\boldsymbol{\delta}_{i} W_i^\top\right) \odot \phi'(\mathbf{z}_{i-1})

    The chain rule. The error at a layer's output goes back through its weights, then is scaled by the activation's slope: 0 or 1 for ReLU, 1−a21 - a^2 for tanh.

  6. Weight gradients

    ∂L∂Wi=ai−1⊤δi+λWi,∂L∂bi=∑rowsδi\frac{\partial L}{\partial W_i} = \mathbf{a}_{i-1}^\top \boldsymbol{\delta}_i + \lambda W_i, \qquad \frac{\partial L}{\partial \mathbf{b}_i} = \sum_{\text{rows}} \boldsymbol{\delta}_i

    Each weight's gradient is its input activation times the error at its output, summed over the batch. These are the values handed to the optimiser.

Symbols

x\mathbf{x}
input row
ai\mathbf{a}_i
output (activation) of layer i
zi\mathbf{z}_i
weighted sum of layer i before the activation
Wi,biW_i, \mathbf{b}_i
weight matrix (fan-in by fan-out) and bias of layer i
ϕ\phi
hidden activation: ReLU or tanh
o\mathbf{o}
final layer output (scores)
pkp_k
predicted probability of class k
ey\mathbf{e}_y
one-hot vector of the true class
δi\boldsymbol{\delta}_i
gradient of the loss with respect to the weighted sum of layer i
λ\lambda
L2 strength
⊙\odot
element-wise product

Worked by hand

A regression network with one input, one hidden ReLU unit and one output, no biases. Take x=2x = 2, W0=0.5W_0 = 0.5, W1=3W_1 = 3 and target y=1y = 1, with a batch of one row.

a1=max⁡(0,  2×0.5)=1,o=1×3=3a_1 = \max(0,\; 2 \times 0.5) = 1, \qquad o = 1 \times 3 = 3
L=12(3−1)2=2,δout=3−1=2L = \tfrac{1}{2}(3 - 1)^2 = 2, \qquad \delta_{\text{out}} = 3 - 1 = 2
∂L∂W1=a1 δout=1×2=2\frac{\partial L}{\partial W_1} = a_1 \, \delta_{\text{out}} = 1 \times 2 = 2
δ1=δout W1×1=2×3=6\delta_{1} = \delta_{\text{out}} \, W_1 \times 1 = 2 \times 3 = 6
∂L∂W0=x δ1=2×6=12\frac{\partial L}{\partial W_0} = x \, \delta_{1} = 2 \times 6 = 12

Both gradients are positive, so both weights should shrink to pull the output of 3 down toward the target of 1. The factor 1 in the fourth line is the ReLU slope, since the unit is active.

Visual example

Loading the example.

Try this

  • Try the circles data, which one layer of two units cannot solve.
  • Train longer and watch the loss fall.

Code sample

import numpy as np
from impl import MLP
from config import MLPConfig

X = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]])
y = np.array([0, 1, 1, 0])                        # XOR: no linear model can fit this

model = MLP(MLPConfig(hidden_sizes=[8], activation="tanh", lr=0.05, epochs=300, batch_size=4)).fit(X, y)
print(model.predict(X))                           # [0 1 1 0]
print(model.predict_proba(X).round(2))            # (4, 2), rows sum to 1
print(model.loss_history_[0], model.loss_history_[-1])
Read the implementation (158 lines)
"""Multilayer perceptron with manual backpropagation and Adam, for classification and regression.

NumPy only. Layer i computes a_i = act(a_{i-1} W_i + b_i); the last layer has no activation. Parameters live
in `params` as "W0", "b0", "W1", "b1", ... with W_i of shape (fan_in, fan_out).
"""
from __future__ import annotations

import numpy as np

try:
    from .config import MLPConfig
except ImportError:  # run from the template's own folder
    from config import MLPConfig


class _Adam:
    """Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""

    def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
        self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
        self.m = {k: np.zeros_like(v) for k, v in params.items()}
        self.v = {k: np.zeros_like(v) for k, v in params.items()}
        self.t = 0

    def step(self, grads: dict) -> None:
        """Apply one update. grads: same keys and shapes as the parameters."""
        self.t += 1
        for k, g in grads.items():
            self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
            self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
            m_hat = self.m[k] / (1 - self.beta1**self.t)
            v_hat = self.v[k] / (1 - self.beta2**self.t)
            self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)

def _softmax(z: np.ndarray) -> np.ndarray:
    """Softmax along the last axis, shifted by the row maximum for stability."""
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)


class MLP:
    """Fully connected network. After `fit`: `params`, `loss_history_` (mean loss per epoch), `classes_`."""

    def __init__(self, config: MLPConfig | None = None) -> None:
        self.config = config or MLPConfig()
        self.params: dict[str, np.ndarray] = {}
        self.classes_: np.ndarray | None = None
        self.loss_history_: list[float] = []
        self._n_layers = 0
        self._single_target = False

    def initialize(self, n_in: int, n_out: int) -> None:
        """Create the weights for `n_in` input features and `n_out` outputs (classes or targets).

        ReLU layers use He initialisation, tanh layers use Xavier (Glorot) initialisation; biases start at zero.
        """
        rng = np.random.default_rng(self.config.seed)
        sizes = [n_in, *[int(h) for h in self.config.hidden_sizes], n_out]
        self._n_layers = len(sizes) - 1
        self.params = {}
        for i, (fan_in, fan_out) in enumerate(zip(sizes[:-1], sizes[1:])):
            scale = np.sqrt(2.0 / fan_in) if self.config.activation == "relu" else np.sqrt(1.0 / fan_in)
            self.params[f"W{i}"] = scale * rng.normal(size=(fan_in, fan_out))
            self.params[f"b{i}"] = np.zeros(fan_out)

    def _forward(self, X: np.ndarray) -> list[np.ndarray]:
        """Activations of every layer. X: (n, d). Returns [X, a_1, ..., output] with output of shape (n, n_out)."""
        acts = [X]
        for i in range(self._n_layers):
            z = acts[-1] @ self.params[f"W{i}"] + self.params[f"b{i}"]
            if i < self._n_layers - 1:
                z = np.maximum(z, 0.0) if self.config.activation == "relu" else np.tanh(z)
            acts.append(z)
        return acts

    def loss_and_grads(self, X: np.ndarray, y: np.ndarray) -> tuple[float, dict]:
        """Loss on a batch and its gradient for every parameter.

        X: (n, d). y: class indices in 0..C-1 of shape (n,) for classification, or real targets of shape
        (n, k) for regression. Returns (loss, grads) where grads has the same keys and shapes as `params`.
        """
        n = len(X)
        acts = self._forward(X)
        out = acts[-1]
        if self.config.task == "classification":
            p = _softmax(out)
            loss = -np.mean(np.log(p[np.arange(n), y] + 1e-300))
            delta = p
            delta[np.arange(n), y] -= 1.0
            delta /= n
        else:
            diff = out - y
            loss = 0.5 * np.sum(diff**2) / n
            delta = diff / n
        grads = {}
        for i in reversed(range(self._n_layers)):
            W = self.params[f"W{i}"]
            loss += 0.5 * self.config.l2 * np.sum(W**2)
            grads[f"W{i}"] = acts[i].T @ delta + self.config.l2 * W
            grads[f"b{i}"] = delta.sum(axis=0)
            if i > 0:
                delta = delta @ W.T
                a = acts[i]  # output of hidden layer i - 1
                delta = delta * (a > 0) if self.config.activation == "relu" else delta * (1.0 - a**2)
        return float(loss), grads

    def fit(self, X: np.ndarray, y: np.ndarray) -> "MLP":
        """Train with mini-batch Adam.

        X: features, shape (n, d). y: labels of any hashable type, shape (n,), for classification; real
        targets of shape (n,) or (n, k) for regression.
        """
        cfg = self.config
        X = np.asarray(X, dtype=float)
        y = np.asarray(y)
        if X.ndim != 2 or len(X) != len(y):
            raise ValueError("X must have shape (n, d) and y must have n rows")
        if cfg.task == "classification":
            self.classes_, target = np.unique(y, return_inverse=True)
            n_out = len(self.classes_)
        else:
            self._single_target = y.ndim == 1
            target = y.astype(float).reshape(len(y), -1)
            n_out = target.shape[1]
        self.initialize(X.shape[1], n_out)
        optimizer = _Adam(self.params, cfg.lr)
        rng = np.random.default_rng(cfg.seed + 1)
        self.loss_history_ = []
        n = len(X)
        for _ in range(cfg.epochs):
            order = rng.permutation(n)
            total = 0.0
            for start in range(0, n, cfg.batch_size):
                rows = order[start : start + cfg.batch_size]
                loss, grads = self.loss_and_grads(X[rows], target[rows])
                optimizer.step(grads)
                total += loss * len(rows)
            self.loss_history_.append(total / n)
        return self

    def forward(self, X: np.ndarray) -> np.ndarray:
        """Raw network output (class scores or regression values). X: (n, d). Returns shape (n, n_out)."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before predicting")
        return self._forward(np.asarray(X, dtype=float))[-1]

    def predict_proba(self, X: np.ndarray) -> np.ndarray:
        """Class probabilities (classification only). X: (n, d). Returns (n, C); columns follow `classes_`."""
        if self.config.task != "classification":
            raise RuntimeError("predict_proba is for classification")
        return _softmax(self.forward(X))

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Predicted labels (classification) or values (regression). X: (n, d). Returns (n,) or (n, k)."""
        out = self.forward(X)
        if self.config.task == "classification":
            return self.classes_[out.argmax(axis=1)] if self.classes_ is not None else out.argmax(axis=1)
        return out[:, 0] if self._single_target else out
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Make a two-class data set that a line cannot separate, such as two interleaved half circles. Train MLP with MLPConfig hidden_sizes set to an empty list, then to one layer of 32 units. Compare accuracy from predict and the curves in loss_history_. Then pick one entry of params, nudge it by a small amount, and check that the change in the loss from loss_and_grads matches the gradient it returns.

Check on learning

  1. With hidden_sizes empty the template is a linear model. Why does adding a hidden layer with no activation not make it any more powerful?
    A way to think about it

    Write out xW0W1\mathbf{x} W_0 W_1 and ask whether a single matrix could do the same job. Then ask what the activation breaks in that argument.

  2. The template uses He scaling for relu and Xavier scaling for tanh. What would go wrong in a deep network if all weights started much too large or much too small?
    A way to think about it

    Follow the size of the activations forward and the size of the gradients backward through ten layers when each layer multiplies them by 3, or by 0.3.

  3. Training loss keeps falling while the loss on held-out rows starts to rise. What is the network doing, and which settings in the config would you change first?
    A way to think about it

    Think about what the extra capacity is being spent on. Consider l2, hidden_sizes and epochs, and what each one limits.

  4. Why is the output error for softmax with cross-entropy simply p−ey\mathbf{p} - \mathbf{e}_y, with no extra slope factor?
    A way to think about it

    Differentiate −log⁡py-\log p_y with respect to one score oko_k using the softmax formula. The terms from the softmax slope cancel with the 1/py1/p_y from the log.