On this page
Neural networks power everything from photo apps to chatbots, and most of us use them through libraries that hide the maths behind a single line of code. For this project, from the 42 curriculum, the rule was simple: no machine-learning library. Only NumPy for arrays. Every neuron, every derivative and every update rule had to be written by hand.
This article walks through how a multilayer perceptron works, one idea at a time, using the real code from my repository. Two parts are interactive: a single neuron you can tune with sliders, and the full network, ported to TypeScript, which you can train on the real data without leaving this page.
The problem
The dataset is the Wisconsin Diagnostic Breast Cancer dataset: 569 patients, each described by 30 measurements computed from a microscope image of cells taken from a breast mass. For ten properties of the cell nuclei (radius, texture, perimeter, area, smoothness, compactness, concavity, concave points, symmetry and fractal dimension) the file gives the mean, the standard error and the worst value.
Each patient is labelled benign (357) or malignant (212). The task: given the 30 numbers, predict the label.
- patients
- 569
- measurements each
- 30
- used for training
- 455
- kept aside to test
- 114
Before any learning, split.py shuffles the rows with a fixed seed and keeps 20% aside. The network never sees those 114 patients while it trains, so they tell us honestly how it does on new cases. Then every feature is standardised: we subtract the mean and divide by the standard deviation, so an area in the thousands and a smoothness around 0.1 end up on the same scale. Those statistics come from the training set only, and are saved with the model so that new data is scaled exactly the same way.
One neuron
The building block is loosely inspired by biology. A real neuron receives signals through its dendrites, combines them in the cell body, and fires along its axon if the total is strong enough. An artificial neuron does the same thing with arithmetic.
It multiplies each input by a weight, adds everything up together with a bias, then passes the total through an activation function. In this project the hidden neurons use the sigmoid, which squashes any number into the range 0 to 1:
A large positive weight means “this input pushes me to fire”, a negative one means “this input holds me back”, and the bias sets how easily the neuron fires at all. Try it:
Drag the sliders. Teal lines are positive weights, orange ones negative; thicker means stronger.
Learning, in the end, just means finding good values for the weights and biases. One neuron can only draw a straight boundary between two classes. To capture more complex patterns we need many of them.
def sigmoid(z):
# Sigmoid activation function: f(z) = 1 / (1 + exp(-z))
return 1.0 / (1.0 + np.exp(-z))
def sigmoid_derivative(a):
# Derivative of the sigmoid function: f'(z) = f(z) * (1 - f(z))
return a * (1.0 - a)
def softmax(z):
# Softmax activation function: f(z)_i = exp(z_i) / sum(exp(z_j)) for all j
z_shifted = z - np.max(z, axis=1, keepdims=True)
exp_z = np.exp(z_shifted)
return exp_z / np.sum(exp_z, axis=1, keepdims=True)
A network of neurons
A multilayer perceptron stacks neurons in layers. Every neuron of a layer is connected to every neuron of the next one, which is why these are called dense or fully connected layers. My network has the 30 inputs, two hidden layers of 24 neurons, and 2 outputs: one for benign, one for malignant.
Computing a whole layer for a batch of patients is one matrix multiplication. If X holds a batch (one row per patient) and W the weights (one column per neuron), then:
That is exactly what DenseLayer.forward does. It also remembers its input and output, because the backward pass will need them later:
def forward(self, input_batch):
self.input_batch = input_batch
weighted_sum = input_batch @ self.weights + self.bias
if self.activation_name == "sigmoid":
self.output_batch = sigmoid(weighted_sum)
elif self.activation_name == "softmax":
self.output_batch = softmax(weighted_sum)
else:
raise ValueError(f"unknown activation '{self.activation_name}'")
return self.output_batch
The network's own forward pass just feeds each layer's output into the next one:
def forward(self, input_batch):
output_batch = input_batch
for layer in self.layers:
output_batch = layer.forward(output_batch)
return output_batch
One detail matters before training even starts: the initial weights. If they were all zero, every neuron in a layer would compute the same thing and receive the same update, forever. So they start random, drawn uniformly in a range that shrinks as the number of inputs grows (He-uniform initialisation), which keeps the signals from exploding or vanishing as they cross the layers.
def he_uniform(n_inputs, n_outputs, rng):
limit = np.sqrt(6.0 / n_inputs)
return rng.uniform(-limit, limit, size=(n_inputs, n_outputs))
Scores to probabilities
The last layer produces two raw scores. To read them as probabilities, the output layer uses softmax: exponentiate each score, then divide by the total, so the outputs are positive and add up to 1.
Scores of 2.0 and −1.0, for example, become 95% benign and 5% malignant. In the code above, notice the line z - np.max(z, axis=1, keepdims=True). Mathematically it changes nothing, since softmax gives the same result if you subtract the same number from every score. But np.exp(1000) overflows to infinity, while np.exp(0) is a comfortable 1. It is a one-line fix for a bug that would only show up once the weights grow large.
Measuring mistakes
To improve, the network needs a single number that says how wrong it is: the loss. For classification the standard choice is categorical cross-entropy: take the probability the network gave to the correct answer, and compute its negative logarithm.
If a tumour is malignant and the network says 90% malignant, the loss is −ln(0.9) ≈ 0.105. If it says 10%, the loss is −ln(0.1) ≈ 2.303, more than twenty times worse. Confident mistakes are punished hard, which is exactly what we want.
def categorical_crossentropy(true_labels, predicted_probs):
"""
E = -mean( sum_over_classes( true * log(predicted) ) )
"""
epsilon = 1e-12
predicted_probs = np.clip(predicted_probs, epsilon, 1 - epsilon)
per_example_loss = -np.sum(true_labels * np.log(predicted_probs), axis=1)
return np.mean(per_example_loss)
The np.clip keeps probabilities away from exactly 0, because log(0) is minus infinity and a single one would turn the whole loss into nan.
Backpropagation
Now the heart of it. For each of the 1,394 parameters we want to know: if I nudge this weight up a little, does the loss go up or down, and by how much? That quantity is the gradient. Computing it for every weight, efficiently, is what backpropagation does: it starts from the loss and walks backwards through the layers, applying the chain rule from calculus at each step.
It starts with a lovely simplification. When softmax and cross-entropy are combined, the gradient of the loss with respect to the output layer's raw scores is simply:
prediction minus truth: if the network said 0.8 where the answer was 1, the error signal is −0.2
def backward(self, true_labels, predicted_probs):
grad = predicted_probs - true_labels
for layer in reversed(self.layers):
grad = layer.backward(grad)
Each layer then turns the gradient it receives into three things: the gradient of its weights, the gradient of its biases, and the gradient to hand to the layer before it. For a sigmoid layer, the gradient first goes through the sigmoid's derivative, a(1 − a), which conveniently only needs the layer's own output:
def backward(self, grad_output):
batch_size = self.input_batch.shape[0]
if self.activation_name == "softmax":
grad_weighted_sum = grad_output
elif self.activation_name == "sigmoid":
grad_weighted_sum = grad_output * sigmoid_derivative(self.output_batch)
else:
raise ValueError(f"unknown activation '{self.activation_name}'")
self.grad_weights = self.input_batch.T @ grad_weighted_sum / batch_size
self.grad_bias = np.sum(grad_weighted_sum, axis=0, keepdims=True) / batch_size
grad_input = grad_weighted_sum @ self.weights.T
return grad_input
Gradient descent & Adam
Once we have the gradients, learning is a matter of walking downhill. Gradient descent moves every weight a small step against its gradient. The size of that step is the learning rate (0.0314 by default in my train.py).
def update(self, learning_rate):
self.weights -= learning_rate * self.grad_weights
self.bias -= learning_rate * self.grad_bias
The network does this after every mini-batch of 8 patients rather than after the whole dataset, so it makes 57 small updates per pass over the training data (one epoch). The noise from small batches even helps it avoid getting stuck.
I also implemented Adam, the optimiser most deep-learning projects use by default. Adam keeps, for every single weight, a running average of its gradient (m, a kind of momentum) and of its squared gradient (v). Dividing one by the square root of the other gives each weight its own step size: weights with consistent, small gradients move faster, and noisy ones are calmed down.
def update_adam(self, learning_rate, step, beta1=0.9, beta2=0.999, epsilon=1e-8):
# weights
self.m_weights = beta1 * self.m_weights + (1 - beta1) * self.grad_weights
self.v_weights = beta2 * self.v_weights + (1 - beta2) * self.grad_weights ** 2
m_hat = self.m_weights / (1 - beta1 ** step)
v_hat = self.v_weights / (1 - beta2 ** step)
self.weights -= learning_rate * m_hat / (np.sqrt(v_hat) + epsilon)
The “hat” versions correct a bias: m and v start at zero, so for the first steps their averages are too small. Dividing by 1 − βstep fixes that, and the correction fades as training goes on.
Train it yourself
Enough equations. Below is my network, ported line by line from Python to TypeScript, training on the same 455 patients and tested on the same 114. Every epoch it measures the loss on both sets. Press play, then try Adam, then turn on early stopping.
Real data, real backpropagation, running in your browser. Each run starts from new random weights, so no two runs are exactly alike.
- Epoch
- 0/100
- Test accuracy
- –
- Mistakes
- –
Here “test” means the 114 patients held out by split.py (the validation set). Both curves fall quickly at first. With gradient descent the test loss then flattens and drifts up only gently. With Adam it bottoms out within about 20 epochs and climbs clearly afterwards, while the training loss keeps falling. That upturn is the subject of the next section.
Knowing when to stop
The training loss measures how well the network fits patients it has already seen. The test loss measures how well it does on patients it has never seen. While both go down, the network is learning general patterns. When the test loss starts rising while the training loss keeps falling, it is starting to memorise the training set, quirks and noise included. That is overfitting.
Early stopping is the simple cure. After each epoch, if the validation loss is the best so far, save a copy of the weights. If it has not improved for patience epochs in a row, stop and put the best weights back.
if patience is not None:
if val_loss < best_val_loss:
best_val_loss = val_loss
best_weights = [(layer.weights.copy(), layer.bias.copy())
for layer in self.layers]
epochs_without_improvement = 0
else:
epochs_without_improvement += 1
if epochs_without_improvement >= patience:
if verbose:
print(f"Early stopping at epoch {epoch} due to no improvement in validation loss for {patience} epochs.")
break
Results
On the 114 patients it never trained on, the model saved by that run makes 2 mistakes.predict.py reloads the weights and the scaler from disk and reports:
- accuracy on unseen patients
- 98.2%
- F1 score (malignant)
- 0.976
- mistakes
- 2 / 114
- parameters learned
- 1,394
Accuracy alone can flatter a model when one class is rarer, so the project also tracks precision, recall and F1 every epoch, with malignant as the positive class. Precision answers “when it says malignant, how often is it right?”, and recall answers “of the malignant tumours, how many did it catch?”. In a medical setting, a missed malignant tumour costs far more than a false alarm, which is why recall matters so much.
What I learned
- The maths is less scary in code. Backpropagation looks intimidating on paper. Written out, the backward pass of a layer is three lines of matrix products.
- Shapes are the best debugger. In matrix code, most bugs show up as a matrix with the wrong shape, so checking the expected shape of each line is the fastest way to find them.
- Numerical stability is not optional. Shifting softmax by its maximum and clipping before the logarithm look like details, but without them a single extreme value turns the whole loss into
nan. - Validation data keeps you honest. Without a held-out set, the network would have looked better and better while getting worse on new patients.
- There is always more to try. He initialisation was designed for ReLU layers. With sigmoid, Xavier/Glorot initialisation is the textbook choice; it works well here, but it is the first experiment I would run next, along with ReLU hidden layers.
The full code, with the training and comparison scripts, is on GitHub.
About the project: multilayer-perceptron
A multilayer perceptron written from scratch in Python with NumPy, with no ML framework, that classifies breast tumours as benign or malignant using the Wisconsin Diagnostic Breast Cancer dataset.
- 30 → 24 → 24 → 2
- 569 patients
- Adam + early stopping
Built with
- Python
- NumPy
- pandas
- Matplotlib
