Overview
A single linear model can only draw a straight boundary. An artificial neural network stacks several linear maps and bends the result between them with a simple non-linear function called an activation, such as ReLU or tanh. Each hidden unit learns one small feature of the input, and the next layer combines those features. Training compares the output with the correct answer, then sends the error backwards through the layers to find how much each weight contributed. Every weight is then moved a little in the direction that lowers the error.
A short history
Warren McCulloch and Walter Pitts described a mathematical model of a neuron in 1943, and Frank Rosenblatt built the perceptron, a trainable single layer, in 1958. Networks with hidden layers became practical in 1986, when David Rumelhart, Geoffrey Hinton and Ronald Williams showed that backpropagation could train them. Faster hardware and larger datasets after 2010 turned the same idea into modern deep learning.
How it works
- Initialise each weight matrix with small random values (He scaling for ReLU, Xavier for tanh) and each bias with zero.
- Forward pass: for each hidden layer compute and apply the activation to get the next .
- At the output, apply softmax to get class probabilities, or keep the linear output for regression.
- Measure the loss on a mini-batch: cross-entropy for classification, squared error for regression, plus the L2 penalty on the weights.
- Backward pass: start from the output error and apply the chain rule layer by layer to get the gradient of every weight and bias.
- Update all parameters with Adam, and repeat over shuffled mini-batches for the configured number of epochs.
Watch out for
- Features on very different scales make training slow or unstable, because the same step size is too large for some weights and too small for others. Standardise the inputs first.
- A network with enough hidden units can memorise a small training set, so the training loss keeps falling while accuracy on new data gets worse. Hold out data and use the
l2penalty. - With ReLU, a unit whose input is negative for every row has zero gradient and stops learning. A lower learning rate or tanh avoids this.
- This template is a small NumPy version for reading and small data. It has no GPU support, dropout or batch normalisation.
Use cases
When to use it
Tabular features of fixed length where a linear model underfits and the data has no grid or sequence structure for a CNN or a recurrent network to exploit.
In industry
- Banking and lending
- Credit scoring models that take a fixed set of applicant features and output a probability of default.
- Manufacturing
- Predicting a quality measure or a failure risk from a fixed vector of sensor readings taken on a production line.
- Online advertising
- The dense layers at the end of click prediction models, which combine embedded features into one score.
Choosing it: what must hold
- Inputs that can be written as a fixed-length vector of numbers, with features scaled to similar ranges.
- Enough labelled rows to fit thousands of weights without memorising the training set.
- A relationship that is not linear, so that a linear model leaves clear error on the table.
When to choose something else
| If | Use instead |
|---|---|
| The data is a plain table with a few thousand rows | Gradient boosted trees such as XGBoost or LightGBM, or a random forest |
| The inputs are images | A convolutional network (CNN) |
| The inputs are sequences such as text or time series | An LSTM, a GRU or a Transformer |
| You must explain each prediction to a regulator | Logistic regression or a decision tree |
Math foundations
One layer
A weighted sum followed by the activation . The input is . Without the whole stack would collapse into one linear map.
Softmax output
Turns the last layer's scores into probabilities that are positive and sum to 1.
Cross-entropy loss
The average of minus the log of the probability given to the correct class. It is 0 for a perfect confident answer and grows without bound for a confident wrong one.
Error at the output
For softmax with cross-entropy the gradient at the output is simply prediction minus target (for one row, before averaging over the batch).
Backpropagation
The chain rule, one layer at a time. The error of a layer is the next layer's error sent back through its weights, then scaled by the slope of the activation.
Adam update
Each parameter keeps a running mean of its gradient and of its squared gradient, and steps by their ratio. The template uses , and .
Symbols
- output (activation) of layer l; layer 0 is the input
- weight matrix and bias vector of layer l
- hidden activation function, ReLU or tanh
- predicted probability of class k
- 1 if row i belongs to class k, otherwise 0
- gradient of the loss with respect to the pre-activation of layer l
- element-wise product
- gradient of the loss with respect to one parameter
- learning rate
- number of update steps taken so far
- number of rows in the batch
Worked by hand
One row through a network with two ReLU hidden units and two output classes. Hidden weights are and , output weights are and , all biases are 0. The true class is the first.
The network gives the correct class a probability of 0.82. The output error says: raise the first score and lower the second, each by 0.18 units of gradient. The first hidden unit is switched off, so no gradient flows through it for this row.
Visual example
Loading the example.
Try this
- Two hidden units make two bends. Count the bends as you add units.
- Press Train again after adding points.
Code sample
import numpy as np
from impl import ANN
from config import ANNConfig
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]] * 25, dtype=float)
y = np.array([0, 1, 1, 0] * 25) # XOR
net = ANN(ANNConfig(hidden_sizes=(8,), activation="tanh", epochs=300, learning_rate=0.02)).fit(X, y)
print(net.predict(X[:4])) # [0 1 1 0]
print(net.predict_proba(X[:4]).round(2)) # class probabilities, rows sum to 1Read the implementation (134 lines)
"""ANN: a fully connected feed-forward network (multilayer perceptron) trained by backpropagation.
NumPy only. The forward pass, the backward pass and the Adam update are written out by hand, so the file
doubles as a reference for how a dense network learns.
"""
from __future__ import annotations
import numpy as np
try:
from .config import ANNConfig
except ImportError: # run from the template's own folder
from config import ANNConfig
def _softmax(z: np.ndarray) -> np.ndarray:
"""Row-wise softmax. z: (n, k) -> (n, k)."""
z = z - z.max(axis=1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
class ANN:
"""Dense network: input -> [linear -> activation] * len(hidden_sizes) -> linear -> output.
task "classification": softmax output trained with cross-entropy; `predict` returns class labels.
task "regression": linear output trained with mean squared error; `predict` returns values.
"""
def __init__(self, config: ANNConfig | None = None) -> None:
self.config = config or ANNConfig()
self.weights: list[np.ndarray] = [] # weights[l]: (fan_in, fan_out)
self.biases: list[np.ndarray] = [] # biases[l]: (fan_out,)
self.classes_: np.ndarray | None = None
self.loss_history: list[float] = [] # mean training loss per epoch
# ---- building blocks -------------------------------------------------------------------------------
def _init_params(self, n_in: int, n_out: int) -> None:
rng = np.random.default_rng(self.config.seed)
sizes = [n_in, *self.config.hidden_sizes, n_out]
gain = 2.0 if self.config.activation == "relu" else 1.0 # He for ReLU, Xavier for tanh
self.weights = [rng.normal(0.0, np.sqrt(gain / a), size=(a, b)) for a, b in zip(sizes[:-1], sizes[1:])]
self.biases = [np.zeros(b) for b in sizes[1:]]
def _act(self, z: np.ndarray) -> np.ndarray:
return np.maximum(z, 0.0) if self.config.activation == "relu" else np.tanh(z)
def _act_grad(self, a: np.ndarray) -> np.ndarray:
"""Derivative of the activation, written in terms of its output a."""
return (a > 0).astype(float) if self.config.activation == "relu" else 1.0 - a**2
def forward(self, X: np.ndarray) -> list[np.ndarray]:
"""Run the network. X: (n, d). Returns the activations of every layer, input first, raw output last."""
acts = [np.asarray(X, dtype=float)]
last = len(self.weights) - 1
for l, (W, b) in enumerate(zip(self.weights, self.biases)):
z = acts[-1] @ W + b
acts.append(z if l == last else self._act(z))
return acts
def loss_and_grads(self, X: np.ndarray, T: np.ndarray) -> tuple[float, list[np.ndarray], list[np.ndarray]]:
"""Loss on a batch and its gradients.
X: (n, d) inputs. T: (n, k) targets (one-hot rows for classification, values for regression).
Returns (loss, weight gradients, bias gradients), the gradients in the same order as the parameters.
"""
acts = self.forward(X)
n = len(X)
if self.config.task == "classification":
P = _softmax(acts[-1])
loss = -np.sum(T * np.log(P + 1e-12)) / n
delta = (P - T) / n
else:
diff = acts[-1] - T
loss = np.sum(diff**2) / n
delta = 2.0 * diff / n
loss += 0.5 * self.config.l2 * sum(np.sum(W**2) for W in self.weights)
gW, gb = [None] * len(self.weights), [None] * len(self.weights)
for l in range(len(self.weights) - 1, -1, -1):
gW[l] = acts[l].T @ delta + self.config.l2 * self.weights[l]
gb[l] = delta.sum(axis=0)
if l > 0:
delta = (delta @ self.weights[l].T) * self._act_grad(acts[l])
return float(loss), gW, gb
# ---- public API ------------------------------------------------------------------------------------
def fit(self, X: np.ndarray, y: np.ndarray) -> "ANN":
"""Train with mini-batch Adam.
X: (n, d) features. y: (n,) class labels for classification; (n,) or (n, k) values for regression.
"""
cfg = self.config
X = np.asarray(X, dtype=float)
if cfg.task == "classification":
self.classes_, idx = np.unique(np.asarray(y), return_inverse=True)
T = np.eye(len(self.classes_))[idx]
else:
T = np.asarray(y, dtype=float).reshape(len(X), -1)
self._init_params(X.shape[1], T.shape[1])
rng = np.random.default_rng(cfg.seed + 1)
params = self.weights + self.biases
m = [np.zeros_like(p) for p in params]
v = [np.zeros_like(p) for p in params]
step = 0
self.loss_history = []
for _ in range(cfg.epochs):
order = rng.permutation(len(X))
total = 0.0
for start in range(0, len(X), cfg.batch_size):
rows = order[start:start + cfg.batch_size]
loss, gW, gb = self.loss_and_grads(X[rows], T[rows])
total += loss * len(rows)
step += 1
for p, g, mi, vi in zip(params, gW + gb, m, v):
mi *= 0.9
mi += 0.1 * g
vi *= 0.999
vi += 0.001 * g * g
p -= cfg.learning_rate * (mi / (1 - 0.9**step)) / (np.sqrt(vi / (1 - 0.999**step)) + 1e-8)
self.loss_history.append(total / len(X))
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Class probabilities. X: (n, d) -> (n, n_classes). Classification only."""
if self.config.task != "classification":
raise ValueError("predict_proba is only defined for task='classification'")
return _softmax(self.forward(X)[-1])
def predict(self, X: np.ndarray) -> np.ndarray:
"""Class labels (n,) for classification; values (n,) or (n, k) for regression."""
out = self.forward(X)[-1]
if self.config.task == "classification":
return self.classes_[out.argmax(axis=1)]
return out[:, 0] if out.shape[1] == 1 else out- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
XOR cannot be solved by a straight line. Build the 100-row XOR data from the template's README and fit ANN twice: once with hidden_sizes=() (a linear model) and once with hidden_sizes=(8,) and activation="tanh". Compare loss_history and the output of predict on the four distinct inputs, and explain the difference.
Check on learning
- If you removed the activation function from every hidden layer, what could a ten-layer network represent that a single linear layer could not?
A way to think about it
Write out two layers without an activation and multiply the matrices together. See what kind of function of the input is left.
- Why is the output error so simple, and what would it mean for learning if the model were confidently wrong?
A way to think about it
Look at the size of each component when the correct class gets probability near 0. Compare that with a loss whose gradient shrinks when the output saturates.
- Your training loss goes down smoothly but the validation loss starts rising after epoch 40. What is happening, and which two settings in this template would you change first?
A way to think about it
Think about what the network is fitting after it has captured the real pattern. Consider the number of weights relative to the number of rows, and the penalty on large weights.
- Why does the template initialise weights with random values instead of zeros?
A way to think about it
Follow two hidden units with identical weights through one forward and one backward pass. Ask whether their gradients can ever differ.