MACHINE LEARNING / FIELD GUIDEweights / gradients / Python
Back to ML guides

FIELD GUIDE 04

Neural Network in Python
from Scratch (NumPy)

Short answer: you can build a neural network in Python from scratch with NumPy and about 60 lines of code. Create weight matrices, run a forward pass, measure the error with a loss function, use backpropagation to get the gradients, and nudge the weights in a training loop. Below is a complete NumPy neural network that learns XOR, the exact output it prints, and an explanation of every part. No neural-network framework is required.

A small Python and NumPy network, explained from inputs to backpropagation.

In one linenumbers → weighted layers → checked predictions
A developer's hands typing on a laptop keyboard at a calm wooden desk, the screen out of focus
No framework, no magic: a neural network from scratch is a few arrays and a loop.
EXPLAIN / PYTHON / 01
INPUT→HIDDEN→OUTPUT
forward pass / loss / backward pass
Updated November 29, 2026Beginner-first / NumPy only / toy data

01 01 / Start here

A neural network is
math with a learning loop.

Each layer combines numbers using weights and biases, then applies an activation. Training nudges those weights so predictions fit examples better.

What this tutorial builds

We will implement a small feed-forward neural network in Python with NumPy. It learns the XOR truth table, a compact example a single perceptron cannot solve with one straight decision boundary.

forward pass

Make a prediction

Inputs move through a hidden layer and then to one output probability.

loss

Measure mismatch

Binary cross-entropy summarizes how far predicted probabilities are from the labels.

backpropagation

Find the direction

The chain rule carries the error signal backward to each weight and bias.

You need basic Python and the idea of a function. Install NumPy with python -m pip install numpy. NumPy’s quickstart explains the arrays and matrix multiplication used below.

If “layer”, “weight” or “activation” are new words, the neural networks lesson shows them visually first, and the feed-forward network lesson walks through one forward pass by hand.

02 02 / The simple model

Perceptron first,
then a hidden layer.

A perceptron calculates a weighted sum and applies a decision rule. It is a useful starting point, but its boundary is linear.

Why a single perceptron misses XOR

For XOR, the output is 1 when exactly one input is 1: (0, 1) and (1, 0). It is 0 for (0, 0) and (1, 1). No single straight line separates those two positive examples from the two negative ones. A perceptron can learn linearly separable patterns such as AND or OR, but it needs hidden units to express XOR.

InputExpected XORMeaning
[0, 0]0same bits
[0, 1]1different bits
[1, 0]1different bits
[1, 1]0same bits

The network below has two input values, one hidden layer and one output. It is still small enough to follow by hand.

03 03 / Run the model

Full code: neural network
from scratch in NumPy.

Every matrix shape follows the layer it represents: two inputs, four hidden units and one output.

One compact NumPy implementation

This is the whole program: a 2-4-1 network (2 inputs, 4 hidden units, 1 output) trained on XOR with plain gradient descent. It uses NumPy only, no neural-network framework, and a fixed random seed so you get the same numbers every time. Save it as nn_from_scratch.py and run python nn_from_scratch.py.

import numpy as np

# 1. Toy dataset: the XOR truth table (4 examples, 2 inputs, 1 label each)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)

# 2. Initialise weights and biases (fixed seed = same numbers every run)
rng = np.random.default_rng(42)
n_input, n_hidden, n_output = 2, 4, 1
W1 = rng.normal(0.0, 1.0, size=(n_input, n_hidden))
b1 = np.zeros((1, n_hidden))
W2 = rng.normal(0.0, 1.0, size=(n_hidden, n_output))
b2 = np.zeros((1, n_output))

def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))

# 3. Forward pass: input -> hidden (tanh) -> output (sigmoid)
def forward(X):
    z1 = X @ W1 + b1
    a1 = np.tanh(z1)
    z2 = a1 @ W2 + b2
    a2 = sigmoid(z2)
    return a1, a2

# 4. Loss: binary cross-entropy, averaged over the examples
def bce_loss(y_true, y_prob):
    eps = 1e-12
    y_prob = np.clip(y_prob, eps, 1 - eps)
    return -np.mean(y_true * np.log(y_prob) + (1 - y_true) * np.log(1 - y_prob))

# 5. Training loop: forward, loss, backprop, gradient-descent update
learning_rate = 0.5
epochs = 5000
n = X.shape[0]

for epoch in range(epochs + 1):
    a1, a2 = forward(X)
    loss = bce_loss(y, a2)

    # Backpropagation (chain rule, from the output back to the input)
    dz2 = (a2 - y) / n                  # sigmoid + BCE simplifies to this
    dW2 = a1.T @ dz2
    db2 = dz2.sum(axis=0, keepdims=True)
    dz1 = (dz2 @ W2.T) * (1 - a1 ** 2)  # tanh'(z) = 1 - tanh(z)^2
    dW1 = X.T @ dz1
    db1 = dz1.sum(axis=0, keepdims=True)

    # Update every parameter a small step against its gradient
    W2 -= learning_rate * dW2
    b2 -= learning_rate * db2
    W1 -= learning_rate * dW1
    b1 -= learning_rate * db1

    if epoch % 1000 == 0:
        print(f"epoch {epoch:5d}  loss {loss:.4f}")

# 6. Check the trained network
_, probs = forward(X)
preds = (probs >= 0.5).astype(int)
for inputs, p, label in zip(X.astype(int), probs.ravel(), preds.ravel()):
    print(f"input {inputs}  probability {p:.3f}  prediction {label}")
print("accuracy:", (preds == y).mean())

Expected output

We ran this exact script with Python 3.13 and NumPy 2.5 on October 30, 2026. It printed:

epoch     0  loss 0.8299
epoch  1000  loss 0.0055
epoch  2000  loss 0.0024
epoch  3000  loss 0.0015
epoch  4000  loss 0.0011
epoch  5000  loss 0.0009
input [0 0]  probability 0.000  prediction 0
input [0 1]  probability 0.999  prediction 1
input [1 0]  probability 0.999  prediction 1
input [1 1]  probability 0.001  prediction 0
accuracy: 1.0

The loss falls from 0.83 to below 0.001, and all four XOR rows are classified correctly. With the same seed you should get the same output. A different NumPy version can change the last digit, and a different seed gives different numbers (and, rarely, a run that gets stuck; see the tips below).

What each part does

  1. Toy dataset. X holds the four XOR inputs as a 4 × 2 matrix, one row per example. y holds the labels as a 4 × 1 column. Keeping the data as matrices lets one line of code process all four examples at once.
  2. Weights and biases. W1 (2 × 4) connects the 2 inputs to 4 hidden units, and W2 (4 × 1) connects those to the output. Weights start as small random numbers from rng.normal, so the hidden units start out different from each other. Biases start at zero. default_rng(42) fixes the random numbers, which makes the run repeatable.
  3. Forward pass. X @ W1 + b1 is a weighted sum for every example and every hidden unit in one matrix multiplication. np.tanh bends it (without a non-linear activation, two layers would collapse into one straight-line model and XOR would stay unsolvable). The output layer repeats the pattern, and sigmoid squeezes the result into a probability between 0 and 1.
  4. Loss. Binary cross-entropy is small when the network gives a high probability to the right label and grows quickly when it is confidently wrong. np.clip keeps log away from exactly 0.
  5. Backpropagation. The chain rule, applied from the end of the network back to the start. For sigmoid with binary cross-entropy, the gradient at the output simplifies to (a2 - y) / n. Multiplying by a1.T gives the gradient for W2. The error is then passed back through W2.T and multiplied by the tanh derivative, 1 - a1², to get the gradients for W1 and b1.
  6. Update and repeat. Each parameter moves a small step against its gradient: W -= learning_rate * dW. That is gradient descent. The loop runs 5,000 times and prints the loss every 1,000 epochs so you can see it fall.
  7. Check. After training, a final forward pass gives the four probabilities, and a 0.5 threshold turns them into 0/1 predictions.

X @ W1 is matrix multiplication: NumPy’s @ operator combines each row of inputs with the first layer’s weights. * multiplies element by element. Mixing the two up is the most common bug in a NumPy neural network. See the official NumPy quickstart for array shapes and matrix products.

04 04 / Train it

How to train it
step by step.

Training a neural network from scratch is the same short cycle repeated thousands of times. Here it is in order, mapped to the script:

  1. 01 / setupInstall NumPy and fix the seed.

    python -m pip install numpy, then np.random.default_rng(42). A fixed seed means a bug is reproducible, which matters more than you’d think when you’re debugging gradients.

  2. 02 / dataShape the data.

    One example per row: X is (examples × features), y is (examples × 1). Write the shapes down before writing any math.

  3. 03 / parametersInitialise the parameters.

    One weight matrix and one bias row per layer: W1 (2 × 4), b1 (1 × 4), W2 (4 × 1), b2 (1 × 1). Random weights, zero biases.

  4. 04 / forwardRun the forward pass.

    Weighted sum, activation, repeat for the next layer, ending in a probability. Keep the intermediate activations (a1, a2), because backpropagation needs them.

  5. 05 / lossCompute the loss.

    One number that says how wrong the network is right now. Print it regularly; it’s your main signal that training works.

  6. 06 / backwardBackpropagate.

    Work out the gradient of the loss for every weight and bias, starting at the output and moving backwards. Compute all gradients before changing any weight.

  7. 07 / updateUpdate the parameters.

    Subtract learning rate × gradient from each parameter.

  8. 08 / repeatRepeat for many epochs.

    One epoch here is one pass over all four examples. Watch the loss: it should trend down. If it doesn’t, stop and check shapes and signs before training longer.

  9. 09 / evaluateEvaluate.

    Run a final forward pass and compare predictions with the labels. On real data, evaluate on examples the network never trained on.

If the loss won’t go down

We tried a few variations of the script above (5,000 epochs each) to see what breaks:

  • Learning rate too small. With learning_rate = 0.01 the loss was still 0.40 after 5,000 epochs and the network got only 2 of 4 rows right. At 0.05 it reached a loss of 0.015 and solved XOR. Raise the rate or train longer.
  • Too few hidden units. With 2 hidden units, only 9 of 20 seeds (0–19) solved XOR. With 4 hidden units, 19 of 20 did. If a run gets stuck, try another seed or a wider hidden layer.
  • Wrong derivative. If you swap tanh for sigmoid in the hidden layer, the derivative must change too, from 1 - a1² to a1 * (1 - a1). With that change the script also solved XOR (loss 0.0028).
  • Shape errors. A ValueError from @ almost always means a missing transpose (.T) or a weight matrix with its dimensions the wrong way round.
Hands holding a pencil over an open notebook with blank pages beside a closed laptop on a desk
Backpropagation is easier to debug on paper first: write down every shape, then code it.

05 05 / Read the update

Backpropagation,
in four moves.

The update is a repeated calculation, not a special neural-network trick.

  1. 01 / forwardCalculate activations.

    The hidden values are np.tanh(X @ W1 + b1); the output is another weighted sum followed by sigmoid.

  2. 02 / compareFind output error.

    With sigmoid plus binary cross-entropy, the derivative at the output simplifies to (prediction - label) / samples, written (a2 - y) / n in the script.

  3. 03 / chainCarry the error back.

    The hidden-layer derivative multiplies by the output weights and by the tanh derivative, 1 - a². (With a sigmoid hidden layer it would be a × (1 - a).)

  4. 04 / updateMove parameters against the gradient.

    Subtract learning rate times each gradient. Repeating the loop should reduce the loss for this small, well-defined example.

W1 has shape 2 × 4, b1 has shape 1 × 4, W2 has shape 4 × 1, and b2 has shape 1 × 1. A shape mismatch usually means an input, layer width or transpose does not match the equation. For the intuition behind “move against the gradient”, see the interactive gradient descent lesson.

06 06 / Compare

Neural network from scratch
vs PyTorch.

Writing a neural network from scratch teaches you what a framework does for you. Here is the same job done both ways:

AspectFrom scratch (NumPy)PyTorch
GradientsYou derive and code every derivative by handAutograd computes them when you call loss.backward()
LayersWeight matrices and bias arrays you createModules such as nn.Linear and nn.Tanh that hold their own parameters
LossYou write binary cross-entropy yourselfBuilt in, e.g. nn.BCELoss or nn.BCEWithLogitsLoss
Weight updateW -= learning_rate * dW for each arrayAn optimizer from torch.optim, such as SGD or Adam
HardwareNumPy runs on the CPUTensors can run on a GPU
InstallNumPy onlyThe torch package, a much larger download
Best forLearning how training works, debugging intuitionReal datasets, bigger models, research and production work

The math is the same in both. PyTorch’s autograd tutorial shows how it records the forward pass and computes the gradients you wrote by hand above. Once this script makes sense, moving to a framework is mostly learning its API.

07 07 / Keep the limits visible

A toy example
is not a deployment plan.

Four rows can explain a mechanism, but they cannot tell you how a model behaves in a real setting.

Common beginner mistakes

  • Confusing element-wise multiplication * with matrix multiplication @.
  • Updating weights before computing all gradients for the current step.
  • Assuming a low training loss proves performance on new examples.
  • Changing the threshold without saying what decision it represents.
  • Applying a tutorial network to people or consequential decisions without suitable data and review.

For a next step, compare this hand-coded model with the neural-network field lesson, see how the same forward pass works inside a transformer in the feed-forward network lesson, then explore gradient descent or choose a carefully scoped idea from beginner machine learning projects. The beginner course explains the difference between training, validation and test data.

FAQ Python / neural networks

Questions,
answered.

Short answers with the model’s limits left visible.

· beginner tutorial

01 / answerCan I build a neural network from scratch with only Python?

Yes. You can write the math with built-in Python lists, but NumPy makes vector and matrix operations easier to express. This guide uses NumPy and no neural-network framework.

02 / answerIs a perceptron the same as a neural network?

A perceptron is a simple one-layer model often used to introduce neural networks. A multilayer network adds hidden transformations and can represent patterns a single linear decision boundary cannot, such as XOR.

03 / answerWhy does XOR need a hidden layer?

The XOR positives cannot be separated from the negatives by one straight line in the two-input plane. A hidden layer creates intermediate nonlinear features that let the output combine them.

04 / answerDoes this tutorial produce a production-ready model?

No. XOR is a four-row teaching example. Real applications need appropriate data, evaluation, privacy and security review, and evidence that errors are acceptable for the intended use.

05 / answerDo I need to know calculus to build a neural network from scratch?

Not much. You need to know that a derivative tells you which way a number should move to reduce the loss, and how the chain rule passes that signal back through layers. The code in this guide uses only two activation derivatives, for sigmoid and tanh, and both are one line.

06 / answerHow many lines of code does a neural network from scratch take?

The complete NumPy script in this guide is 63 lines including comments and blank lines, or 44 lines of actual code. That covers the data, weight setup, forward pass, loss, backpropagation, training loop and a final check.

07 / answerWhy use NumPy for a neural network from scratch?

NumPy lets you write a whole layer as one matrix multiplication, so the code looks like the math and runs much faster than Python loops. It is not a neural-network framework: it has no automatic gradients, so you still write the forward pass and backpropagation yourself.

08 / answerHow do I build a neural network in Python from scratch?

Install NumPy, then write the pieces yourself: weight and bias arrays, a forward pass through a hidden layer, a loss, backpropagation for the gradients, and a training loop that updates the weights. The example below is a 2-4-1 network that learns XOR in about 60 lines, with a fixed random seed so the printed output matches.

↗keep exploring

More explainAI
field guides.