Sign in

Artificial neural network (ANN)

Artificial Neural Network

A fully connected feed-forward network: layers of weighted sums and simple non-linear functions, trained by backpropagation.

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

  1. Initialise each weight matrix with small random values (He scaling for ReLU, Xavier for tanh) and each bias with zero.
  2. Forward pass: for each hidden layer compute z=Wa+b\mathbf{z} = W\mathbf{a} + \mathbf{b} and apply the activation to get the next a\mathbf{a}.
  3. At the output, apply softmax to get class probabilities, or keep the linear output for regression.
  4. Measure the loss on a mini-batch: cross-entropy for classification, squared error for regression, plus the L2 penalty on the weights.
  5. Backward pass: start from the output error p−t\mathbf{p} - \mathbf{t} and apply the chain rule layer by layer to get the gradient of every weight and bias.
  6. 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 l2 penalty.
  • 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

IfUse instead
The data is a plain table with a few thousand rowsGradient boosted trees such as XGBoost or LightGBM, or a random forest
The inputs are imagesA convolutional network (CNN)
The inputs are sequences such as text or time seriesAn LSTM, a GRU or a Transformer
You must explain each prediction to a regulatorLogistic regression or a decision tree

Math foundations

  1. One layer

    z(l)=W(l)a(l−1)+b(l),a(l)=ϕ(z(l))\mathbf{z}^{(l)} = W^{(l)} \mathbf{a}^{(l-1)} + \mathbf{b}^{(l)}, \qquad \mathbf{a}^{(l)} = \phi\big(\mathbf{z}^{(l)}\big)

    A weighted sum followed by the activation ϕ\phi. The input is a(0)=x\mathbf{a}^{(0)} = \mathbf{x}. Without ϕ\phi the whole stack would collapse into one linear map.

  2. Softmax output

    pk=ezk∑jezjp_k = \frac{e^{z_k}}{\sum_{j} e^{z_j}}

    Turns the last layer's scores into probabilities that are positive and sum to 1.

  3. Cross-entropy loss

    L=−1n∑i=1n∑ktiklog⁡pik\mathcal{L} = -\frac{1}{n} \sum_{i=1}^{n} \sum_{k} t_{ik} \log p_{ik}

    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.

  4. Error at the output

    δ(L)=∂L∂z(L)=p−t\boldsymbol{\delta}^{(L)} = \frac{\partial \mathcal{L}}{\partial \mathbf{z}^{(L)}} = \mathbf{p} - \mathbf{t}

    For softmax with cross-entropy the gradient at the output is simply prediction minus target (for one row, before averaging over the batch).

  5. Backpropagation

    δ(l)=(W(l+1)⊤δ(l+1))⊙ϕ′(z(l)),∂L∂W(l)=δ(l) a(l−1)⊤\boldsymbol{\delta}^{(l)} = \Big( W^{(l+1)\top} \boldsymbol{\delta}^{(l+1)} \Big) \odot \phi'\big(\mathbf{z}^{(l)}\big), \qquad \frac{\partial \mathcal{L}}{\partial W^{(l)}} = \boldsymbol{\delta}^{(l)} \, \mathbf{a}^{(l-1)\top}

    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.

  6. Adam update

    m←β1m+(1−β1)g,v←β2v+(1−β2)g2,θ←θ−η m/(1−β1s)v/(1−β2s)+ϵm \leftarrow \beta_1 m + (1-\beta_1) g, \quad v \leftarrow \beta_2 v + (1-\beta_2) g^2, \quad \theta \leftarrow \theta - \eta \, \frac{m / (1-\beta_1^{s})}{\sqrt{v / (1-\beta_2^{s})} + \epsilon}

    Each parameter keeps a running mean of its gradient and of its squared gradient, and steps by their ratio. The template uses β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 and ϵ=10−8\epsilon = 10^{-8}.

Symbols

a(l)\mathbf{a}^{(l)}
output (activation) of layer l; layer 0 is the input
W(l),b(l)W^{(l)}, \mathbf{b}^{(l)}
weight matrix and bias vector of layer l
ϕ\phi
hidden activation function, ReLU or tanh
pkp_k
predicted probability of class k
tikt_{ik}
1 if row i belongs to class k, otherwise 0
δ(l)\boldsymbol{\delta}^{(l)}
gradient of the loss with respect to the pre-activation of layer l
⊙\odot
element-wise product
gg
gradient of the loss with respect to one parameter
η\eta
learning rate
ss
number of update steps taken so far
nn
number of rows in the batch

Worked by hand

One row x=(1,2)\mathbf{x} = (1, 2) through a network with two ReLU hidden units and two output classes. Hidden weights are (1,−1)(1, -1) and (0.5,0.5)(0.5, 0.5), output weights are (2,1)(2, 1) and (1,0)(1, 0), all biases are 0. The true class is the first.

z(1)=(1⋅1−1⋅2,  0.5⋅1+0.5⋅2)=(−1,  1.5)z^{(1)} = (1 \cdot 1 - 1 \cdot 2,\; 0.5 \cdot 1 + 0.5 \cdot 2) = (-1,\; 1.5)
a(1)=ReLU⁡(z(1))=(0,  1.5)a^{(1)} = \operatorname{ReLU}(z^{(1)}) = (0,\; 1.5)
z(2)=(2⋅0+1⋅1.5,  1⋅0+0⋅1.5)=(1.5,  0)z^{(2)} = (2 \cdot 0 + 1 \cdot 1.5,\; 1 \cdot 0 + 0 \cdot 1.5) = (1.5,\; 0)
p=(e1.5e1.5+1,  1e1.5+1)=(0.8176,  0.1824)p = \left( \frac{e^{1.5}}{e^{1.5} + 1},\; \frac{1}{e^{1.5} + 1} \right) = (0.8176,\; 0.1824)
L=−ln⁡0.8176=0.2014,δ(2)=p−t=(−0.1824,  0.1824)\mathcal{L} = -\ln 0.8176 = 0.2014, \qquad \delta^{(2)} = p - t = (-0.1824,\; 0.1824)

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 1
Read 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

  1. 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.

  2. Why is the output error p−t\mathbf{p} - \mathbf{t} 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.

  3. 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.

  4. 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.