
Writing a neural network from scratch, with nothing but Python and NumPy, is the fastest way to understand what deep learning frameworks do for you. There is no magic inside: a network is a few matrix multiplications, a nonlinearity, a loss function and the chain rule that tells every weight which way to move. Once you have written those 80 lines yourself, PyTorch stops being a black box.
This guide builds a neural network from scratch in three steps. First, a single neuron in 9 lines of Python. Then a network with a hidden layer that learns XOR, which a single neuron cannot, with backpropagation written by hand. Finally, a real multilayer network with ReLU, softmax and cross-entropy that classifies handwritten digits from the MNIST data set with 97.8% accuracy in about 15 seconds on a laptop CPU. We check our gradients numerically, compare the result with the same network in PyTorch, and measure which design choices actually matter.
Key takeaways:
- A neural network is matrix multiplications, activations, a loss and the chain rule; about 80 lines of NumPy are enough for a working multilayer network.
- A single neuron learns linearly separable rules; a hidden layer lets the network solve XOR and real tasks.
- Our NumPy network reaches 97.8% test accuracy on MNIST in 10 epochs, about 15 seconds on a CPU, the same as the identical network in PyTorch (97.9%).
- Always check backpropagation with a numerical gradient check: our largest relative error was 3 × 10−7.
What a neural network computes
A neural network is a function with many adjustable numbers, the weights. Each layer takes a vector of inputs, multiplies it by a weight matrix, adds a bias vector and applies a simple nonlinear function, the activation. Stacking layers lets the network represent complicated functions, such as the mapping from the pixels of an image to the digit it shows. Our guide to how neural networks work explains the ideas in more depth; here we focus on the code.
Training repeats four steps:
- Forward pass: compute the network’s output for a batch of examples.
- Loss: measure how wrong the output is, for example with mean squared error or cross-entropy.
- Backward pass: compute the gradient of the loss with respect to every weight using the chain rule, which is what backpropagation means.
- Update: move every weight a small step against its gradient, as in gradient descent.
All the code below needs only Python 3 and NumPy; PyTorch is used once, to check our results. We ran it with NumPy 2.5 and PyTorch 2.14.
Step 1: a single neuron in 9 lines
The smallest possible neural network is one neuron, the perceptron with a smooth sigmoid activation. A well-known example by Milo Spencer-Harper teaches a neuron a simple rule from four examples: the output equals the first of three inputs. Here is a modern NumPy version:
import numpy as np
X = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
y = np.array([[0, 1, 1, 0]]).T
w = 2 * np.random.default_rng(1).random((3, 1)) - 1
for _ in range(10000):
out = 1 / (1 + np.exp(-(X @ w)))
w += X.T @ ((y - out) * out * (1 - out))
print("new example [1, 0, 0] ->", 1 / (1 + np.exp(-(np.array([1, 0, 0]) @ w))))
print("weights:", w.ravel().round(2))
new example [1, 0, 0] -> [0.99993705]
weights: [ 9.67 -0.21 -4.63]
The neuron has never seen the input [1, 0, 0], yet it answers 0.9999, almost exactly 1. Each line does one thing:
Xholds four training examples with three inputs each, andythe correct answers.wstarts as three random weights between −1 and 1.- In each of 10,000 iterations, the neuron computes its output with the sigmoid function 1 / (1 + e−x), which squashes any number into the range 0 to 1.
- The update multiplies the error
y − outby the slope of the sigmoid,out · (1 − out), and by the inputs. Confident outputs, where the slope is small, change little; inputs that are 0 do not change their weight at all.
The learned weights tell the story: a large positive weight (9.67) for the first input, almost zero for the second, and a negative weight for the third input, which is always 1 and acts as a bias.
Step 2: a hidden layer and backpropagation (XOR)
A single neuron draws one straight line (or plane) through its input space, so it can only learn problems that a line can separate. The classic counterexample is XOR: the output is 1 when exactly one of two inputs is 1. No single line separates (0, 1) and (1, 0) from (0, 0) and (1, 1). Minsky and Papert used this limitation in 1969 to argue against perceptrons; the answer, popularized by Rumelhart, Hinton and Williams in 1986, was a hidden layer trained with backpropagation.

The code below first tries a single neuron, then a network with one hidden layer of four neurons. The backward pass applies the chain rule layer by layer: the error signal of the output layer, d_out, is sent back through the output weights and multiplied by the derivative of the hidden layer’s sigmoid to give d_h.
import numpy as np
sigmoid = lambda z: 1 / (1 + np.exp(-z))
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]]) # XOR: 1 when the inputs differ
rng = np.random.default_rng(0)
# 1. A single neuron (no hidden layer) cannot learn XOR
w, b = rng.normal(size=(2, 1)), 0.0
for _ in range(10000):
out = sigmoid(X @ w + b)
delta = (out - y) * out * (1 - out) # derivative of squared error through the sigmoid
w -= 1.0 * X.T @ delta
b -= 1.0 * delta.sum()
print("single neuron:", sigmoid(X @ w + b).ravel().round(3))
# 2. One hidden layer of 4 neurons learns it
W1, b1 = rng.normal(size=(2, 4)), np.zeros(4)
W2, b2 = rng.normal(size=(4, 1)), np.zeros(1)
for step in range(10000):
h = sigmoid(X @ W1 + b1) # forward pass
out = sigmoid(h @ W2 + b2)
d_out = (out - y) * out * (1 - out) # backward pass: chain rule, layer by layer
d_h = (d_out @ W2.T) * h * (1 - h)
W2 -= 1.0 * h.T @ d_out; b2 -= 1.0 * d_out.sum(0)
W1 -= 1.0 * X.T @ d_h; b1 -= 1.0 * d_h.sum(0)
if step in (0, 1000, 9999):
print(f"step {step:5d} loss {((out - y) ** 2).mean():.4f}")
print("two-layer network:", out.ravel().round(3))
np.savez("xor_weights.npz", W1=W1, b1=b1, W2=W2, b2=b2)
single neuron: [0.5 0.5 0.5 0.5]
step 0 loss 0.3352
step 1000 loss 0.0023
step 9999 loss 0.0001
two-layer network: [0.01 0.986 0.991 0.012]
The single neuron gives up and outputs 0.5 for every input: the best a straight line can do. The two-layer network outputs 0.01, 0.986, 0.991 and 0.012, the correct XOR answers. The loss is the mean squared error, and its gradient for the output weights follows directly from the chain rule:

Plotting the trained network’s output for every point of the plane shows what the hidden layer did: its four neurons each draw a line, and the output neuron combines them into a diagonal band that puts the two “1” examples on one side and the two “0” examples on the other.

Step 3: a real network for MNIST
XOR has four examples. A useful network has to learn from tens of thousands. MNIST is the standard first data set: 70,000 grayscale images of handwritten digits, 28 × 28 pixels each, split into 60,000 for training and 10,000 for testing, published by Yann LeCun, Corinna Cortes and Christopher Burges. The original site is often unavailable, but copies of the four files are on GitHub, for example in the fgnt/mnist repository; put them in a data folder.
For a real task, we change four things compared with the XOR network. Each is a standard modern choice:
- ReLU in hidden layers. max(0, z) is cheap and its gradient does not shrink to almost zero for large inputs, as the sigmoid’s does. Our guide to activation functions compares the options.
- Softmax output with cross-entropy loss. The last layer outputs ten numbers, one per digit; softmax turns them into probabilities, and cross-entropy is the negative log-probability of the correct digit. Combined, their gradient is remarkably simple: the predicted probabilities minus the one-hot vector of the correct class.
- He initialization. Weights start as random numbers with variance 2 / (number of inputs), which keeps the scale of signals roughly constant from layer to layer with ReLU.
- Mini-batch SGD with momentum. Instead of the whole data set, each update uses a batch of 64 images; momentum accumulates past gradients to smooth the path. One pass over all 60,000 images is an epoch.
import gzip
import time
import numpy as np
def load_mnist(path="data"):
"""Read the four MNIST files (IDX format) into NumPy arrays."""
def images(f):
with gzip.open(f"{path}/{f}") as fh:
return np.frombuffer(fh.read(), np.uint8, offset=16).reshape(-1, 784).astype(np.float32) / 255
def labels(f):
with gzip.open(f"{path}/{f}") as fh:
return np.frombuffer(fh.read(), np.uint8, offset=8).astype(np.int64)
return (images("train-images-idx3-ubyte.gz"), labels("train-labels-idx1-ubyte.gz"),
images("t10k-images-idx3-ubyte.gz"), labels("t10k-labels-idx1-ubyte.gz"))
def softmax(z):
z = z - z.max(axis=1, keepdims=True) # subtract the max for numerical stability
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
class MLP:
"""A fully connected network: ReLU hidden layers, softmax output, cross-entropy loss."""
def __init__(self, sizes, seed=0):
rng = np.random.default_rng(seed)
# He initialization: weights ~ N(0, 2 / fan_in), the standard choice for ReLU
self.W = [rng.normal(0, np.sqrt(2 / m), (m, n)).astype(np.float32) for m, n in zip(sizes[:-1], sizes[1:])]
self.b = [np.zeros(n, np.float32) for n in sizes[1:]]
def forward(self, X):
self.a = [X] # keep every layer's output for the backward pass
for i, (W, b) in enumerate(zip(self.W, self.b)):
z = self.a[-1] @ W + b
self.a.append(np.maximum(z, 0) if i < len(self.W) - 1 else z)
return self.a[-1] # logits of the last layer
def backward(self, logits, y):
n = len(y)
p = softmax(logits)
loss = -np.log(p[np.arange(n), y] + 1e-12).mean()
d = p.copy()
d[np.arange(n), y] -= 1 # gradient of softmax + cross-entropy: p - one_hot(y)
d /= n
grads = []
for i in reversed(range(len(self.W))):
grads.append((self.a[i].T @ d, d.sum(axis=0)))
if i > 0:
d = (d @ self.W[i].T) * (self.a[i] > 0) # chain rule through the ReLU
return loss, grads[::-1]
def predict(self, X):
return self.forward(X).argmax(axis=1)
def train(model, X, y, X_test, y_test, epochs=10, batch=64, lr=0.05, momentum=0.9, seed=0):
rng = np.random.default_rng(seed)
velocity = [[np.zeros_like(W), np.zeros_like(b)] for W, b in zip(model.W, model.b)]
history = []
for epoch in range(1, epochs + 1):
start, losses = time.time(), []
for idx in np.array_split(rng.permutation(len(X)), len(X) // batch):
loss, grads = model.backward(model.forward(X[idx]), y[idx])
losses.append(loss)
for i, (gW, gb) in enumerate(grads): # SGD with momentum
velocity[i][0] = momentum * velocity[i][0] + gW
velocity[i][1] = momentum * velocity[i][1] + gb
model.W[i] -= lr * velocity[i][0]
model.b[i] -= lr * velocity[i][1]
acc = (model.predict(X_test) == y_test).mean()
history.append((epoch, float(np.mean(losses)), float(acc), time.time() - start))
print(f"epoch {epoch:2d} train loss {np.mean(losses):.4f} test accuracy {acc:.2%} {time.time() - start:.1f} s")
return history
if __name__ == "__main__":
X_train, y_train, X_test, y_test = load_mnist()
print(X_train.shape, X_test.shape)
model = MLP([784, 256, 128, 10])
train(model, X_train, y_train, X_test, y_test)
Running it prints:
(60000, 784) (10000, 784)
epoch 1 train loss 0.2252 test accuracy 96.51% 1.2 s
epoch 2 train loss 0.0933 test accuracy 97.27% 1.7 s
epoch 3 train loss 0.0625 test accuracy 97.66% 1.4 s
epoch 4 train loss 0.0478 test accuracy 97.70% 1.4 s
epoch 5 train loss 0.0363 test accuracy 97.76% 1.8 s
epoch 6 train loss 0.0301 test accuracy 97.90% 1.6 s
epoch 7 train loss 0.0242 test accuracy 97.69% 1.6 s
epoch 8 train loss 0.0148 test accuracy 97.99% 1.7 s
epoch 9 train loss 0.0161 test accuracy 97.85% 1.7 s
epoch 10 train loss 0.0128 test accuracy 97.80% 1.4 s
After one epoch, about 1.5 seconds on two CPU cores, the network already recognizes 96.5% of test digits; after ten epochs it reaches 97.8%, with a best of 98.0% at epoch 8. For simplicity, the script reports test accuracy after every epoch; in a real project, you would hold out part of the training set for validation and look at the test set only once, at the end.
A few details in the code matter more than they seem:
- Numerical stability.
softmaxsubtracts the largest value before exponentiating; without it,np.expoverflows for large logits. The small constant in the log avoids log(0). - Caching activations.
forwardkeeps every layer’s output inself.a, because the backward pass needs them to compute weight gradients. This is exactly what frameworks store in memory during training, and why training needs more memory than inference. - Vectorization. Every operation works on a whole batch at once with matrix multiplications; a Python loop over examples would be hundreds of times slower.
- float32. Single precision halves the memory and speeds up matrix multiplication, with no loss of accuracy for this task.
Step 4: check the gradients and compare with PyTorch
A bug in backpropagation rarely crashes: the network just learns badly, and it is hard to tell why. Two checks catch almost every error. The first is gradient checking: change one weight by a tiny ε in both directions, measure the change in loss and compare (L(w + ε) − L(w − ε)) / 2ε with the gradient from backprop. The second is to build the same network in a framework, start it from the same weights and compare gradients and training.
import time
import numpy as np
import torch
from mnist_numpy import MLP, load_mnist, train
X_train, y_train, X_test, y_test = load_mnist()
# 1. Gradient check: compare backprop with numerical derivatives on a small network
rng = np.random.default_rng(0)
small = MLP([784, 32, 10], seed=1)
small.W = [W.astype(np.float64) for W in small.W]
small.b = [b.astype(np.float64) for b in small.b]
Xs, ys = X_train[:20].astype(np.float64), y_train[:20]
_, grads = small.backward(small.forward(Xs), ys)
worst = 0
for layer in range(2):
for _ in range(10):
i, j = rng.integers(small.W[layer].shape[0]), rng.integers(small.W[layer].shape[1])
old, eps = small.W[layer][i, j], 1e-5
small.W[layer][i, j] = old + eps
plus, _ = small.backward(small.forward(Xs), ys)
small.W[layer][i, j] = old - eps
minus, _ = small.backward(small.forward(Xs), ys)
small.W[layer][i, j] = old
numeric, analytic = (plus - minus) / (2 * eps), grads[layer][0][i, j]
worst = max(worst, abs(numeric - analytic) / max(1e-8, abs(numeric) + abs(analytic)))
print(f"gradient check: largest relative error {worst:.1e}")
# 2. The same network in PyTorch, starting from the same weights
numpy_net = MLP([784, 256, 128, 10])
torch_net = torch.nn.Sequential(torch.nn.Linear(784, 256), torch.nn.ReLU(), torch.nn.Linear(256, 128), torch.nn.ReLU(),
torch.nn.Linear(128, 10))
with torch.no_grad():
for layer, W, b in zip(torch_net[::2], numpy_net.W, numpy_net.b):
layer.weight.copy_(torch.from_numpy(W.T))
layer.bias.copy_(torch.from_numpy(b))
idx = np.arange(64)
_, grads = numpy_net.backward(numpy_net.forward(X_train[idx]), y_train[idx])
loss = torch.nn.functional.cross_entropy(torch_net(torch.from_numpy(X_train[idx])), torch.from_numpy(y_train[idx]))
loss.backward()
diff = max(np.abs(layer.weight.grad.numpy().T - g[0]).max() for layer, g in zip(torch_net[::2], grads))
print(f"largest difference between NumPy and PyTorch gradients: {diff:.1e}")
torch_net.zero_grad()
print("NumPy:")
hist_numpy = train(numpy_net, X_train, y_train, X_test, y_test)
print("PyTorch:")
opt = torch.optim.SGD(torch_net.parameters(), lr=0.05, momentum=0.9)
Xt, yt, Xv = torch.from_numpy(X_train), torch.from_numpy(y_train), torch.from_numpy(X_test)
rng = np.random.default_rng(0) # same shuffling as the NumPy run
hist_torch = []
for epoch in range(1, 11):
start, losses = time.time(), []
for idx in np.array_split(rng.permutation(len(Xt)), len(Xt) // 64):
idx = torch.from_numpy(idx)
loss = torch.nn.functional.cross_entropy(torch_net(Xt[idx]), yt[idx])
opt.zero_grad()
loss.backward()
opt.step()
losses.append(loss.item())
with torch.no_grad():
acc = (torch_net(Xv).argmax(1).numpy() == y_test).mean()
hist_torch.append((epoch, float(np.mean(losses)), float(acc), time.time() - start))
print(f"epoch {epoch:2d} train loss {np.mean(losses):.4f} test accuracy {acc:.2%} {time.time() - start:.1f} s")
np.save("history.npy", np.array([hist_numpy, hist_torch]))
gradient check: largest relative error 3.1e-07
largest difference between NumPy and PyTorch gradients: 1.9e-08
NumPy:
epoch 1 train loss 0.2252 test accuracy 96.51% 1.6 s
epoch 2 train loss 0.0933 test accuracy 97.27% 1.9 s
epoch 3 train loss 0.0625 test accuracy 97.66% 1.8 s
epoch 4 train loss 0.0478 test accuracy 97.70% 1.8 s
epoch 5 train loss 0.0363 test accuracy 97.76% 1.7 s
epoch 6 train loss 0.0301 test accuracy 97.90% 1.6 s
epoch 7 train loss 0.0242 test accuracy 97.69% 1.5 s
epoch 8 train loss 0.0148 test accuracy 97.99% 1.7 s
epoch 9 train loss 0.0161 test accuracy 97.85% 1.6 s
epoch 10 train loss 0.0128 test accuracy 97.80% 1.5 s
PyTorch:
epoch 1 train loss 0.2257 test accuracy 96.31% 1.7 s
epoch 2 train loss 0.0932 test accuracy 97.15% 1.5 s
epoch 3 train loss 0.0657 test accuracy 97.39% 1.4 s
epoch 4 train loss 0.0465 test accuracy 97.84% 1.6 s
epoch 5 train loss 0.0371 test accuracy 97.74% 1.7 s
epoch 6 train loss 0.0295 test accuracy 97.87% 1.5 s
epoch 7 train loss 0.0226 test accuracy 97.71% 1.5 s
epoch 8 train loss 0.0189 test accuracy 98.17% 1.5 s
epoch 9 train loss 0.0175 test accuracy 97.88% 1.4 s
epoch 10 train loss 0.0137 test accuracy 97.92% 1.5 s
The largest relative error of the gradient check is 3 × 10−7; values below about 10−5 mean the backward pass is correct, while a bug typically gives errors near 1. The gradients of our NumPy network and PyTorch’s automatic differentiation agree to 2 × 10−8, the precision of float32 arithmetic. Trained from the same starting point on the same batches, the two networks follow almost the same curves: 97.80% for NumPy and 97.92% for PyTorch after ten epochs, with the same speed of about 1.5 seconds per epoch on the CPU. The small differences come from the different order of floating-point operations, which accumulates over 9,370 updates.

Experiments: what matters in a small network
With a working network, it is easy to test which ingredients matter. We changed one thing at a time and trained each variant for ten epochs with the same settings:
| Variant | Layer sizes | Test accuracy after 10 epochs |
|---|---|---|
| No hidden layer (softmax regression) | 784-10 | 92.25% |
| One hidden layer of 32 | 784-32-10 | 96.77% |
| One hidden layer of 256 | 784-256-10 | 98.11% |
| Two hidden layers (baseline) | 784-256-128-10 | 97.80% (best 97.99%) |
| Baseline without momentum | 784-256-128-10 | 97.71% |
| Baseline, tiny initial weights N(0, 0.01) | 784-256-128-10 | 97.94% |
| Sigmoid instead of ReLU | 784-256-128-10 | 97.37% |
| Sigmoid, no momentum | 784-256-128-10 | 92.56% |

What the experiments show:
- A hidden layer is what makes it a neural network. Without one, the model is softmax regression, a linear classifier, and stops at 92.3%. A hidden layer of just 32 neurons adds 4.5 points.
- Width helped more than depth here. One hidden layer of 256 neurons reached 98.1%, slightly better than our two-layer network. We repeated both with three more random seeds: the one-layer network scored 98.1–98.2% every time, the two-layer one 97.4–97.9%. With these hyperparameters and ten epochs, the extra layer did not pay off; deeper networks pay off on harder tasks or with architectures built for images, such as convolutional networks, which exceed 99% on MNIST.
- Old-style choices hurt together, not separately. Replacing ReLU with sigmoid cost 0.4 points, removing momentum cost 0.1 points, and tiny initial weights changed nothing in a network this shallow. But sigmoid without momentum, the typical setup of older tutorials, reached only 92.6% in ten epochs: sigmoid gradients are small, and without momentum the network learns slowly.
From scratch to frameworks
Our NumPy network matches PyTorch in accuracy and, on a CPU, in speed. What frameworks add is everything around the core:
- Automatic differentiation. We wrote
backwardby hand for one architecture. PyTorch records the operations of any forward pass and computes gradients automatically, so you can change the model without rewriting calculus. - GPUs. The same code runs on a graphics card, which matters as soon as networks and data sets grow.
- Building blocks. Convolutions, attention, normalization layers, dropout, optimizers such as Adam, mixed precision and distributed training are ready to use and tested.
The from-scratch version is still worth writing once. It makes shapes, gradients and numerical tricks concrete, and when a model in a framework does not train, you know where to look. To continue, rebuild this network in our PyTorch tutorial, read PyTorch vs TensorFlow to choose a framework, or move on to deep learning architectures. If you have not trained a model on tabular data yet, our Kaggle Titanic tutorial covers the classic machine learning workflow.
FAQ
Can you build a neural network without any libraries?
Yes. Everything in this guide can be written in pure Python with lists and loops; NumPy only makes the matrix operations short and fast. A pure Python version of the MNIST network would work but take hours instead of seconds.
How many lines of code does a neural network need?
A single trainable neuron fits in 9 lines, as in step 1. A complete multilayer network with ReLU, softmax, cross-entropy, mini-batches and momentum, including data loading, takes about 80 lines of NumPy.
Why use softmax and cross-entropy instead of mean squared error?
For classification, cross-entropy punishes confident wrong answers strongly and gives large gradients when the model is wrong, so learning is faster. Combined with softmax, its gradient is simply the predicted probabilities minus the correct one-hot vector.
How many hidden layers do I need?
For simple tabular or vector data, one or two hidden layers are usually enough, and width often matters more than depth, as our experiment showed. Images, sound and text benefit from deep architectures designed for them, such as convolutional networks and transformers.
What accuracy should a from-scratch network reach on MNIST?
A simple fully connected network reaches about 97–98% in a few epochs; with more epochs, learning rate schedules and regularization, around 98.5%. Convolutional networks exceed 99%.
Is there a good book on neural networks from scratch?
“Neural Networks from Scratch in Python” by Harrison Kinsley and Daniel Kukieła builds a full framework in NumPy step by step, and Andrej Karpathy’s free “Neural Networks: Zero to Hero” video series starts with micrograd, a tiny automatic differentiation engine written from scratch.
