Deep Learning Frameworks
Deep learning means neural networks with many layers, trained on large data sets — usually on GPUs. It is the technology behind image classifiers, speech recognition and large language models. The two dominant frameworks are PyTorch and TensorFlow/Keras. They aren't available in this in-browser playground (they're far too large), so in this lesson you'll first build the core mechanism — a network trained by backpropagation — in plain NumPy, and then see how the same model looks in the real frameworks.
A network from scratch
Below is a complete two-layer network that learns XOR. It has the three ingredients every framework automates:
- a forward pass (inputs → hidden layer → output),
- a loss (how wrong the predictions are),
- a backward pass (gradients via the chain rule) followed by a gradient-descent update.
import numpy as np
rng = np.random.default_rng(1)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
W1 = rng.normal(0, 1, (2, 4)); b1 = np.zeros(4) # input -> 4 hidden neurons
W2 = rng.normal(0, 1, (4, 1)); b2 = np.zeros(1) # hidden -> 1 output
sigmoid = lambda z: 1 / (1 + np.exp(-z))
lr = 1.0
for epoch in range(3001):
# forward pass
h = np.tanh(X @ W1 + b1)
out = sigmoid(h @ W2 + b2)
loss = -np.mean(y * np.log(out) + (1 - y) * np.log(1 - out)) # binary cross-entropy
# backward pass (chain rule)
d_out = (out - y) / len(X) # gradient of loss w.r.t. the output's pre-activation
dW2 = h.T @ d_out; db2 = d_out.sum(axis=0)
d_h = (d_out @ W2.T) * (1 - h ** 2) # tanh'(z) = 1 - tanh(z)^2
dW1 = X.T @ d_h; db1 = d_h.sum(axis=0)
# gradient-descent update
W1 -= lr * dW1; b1 -= lr * db1
W2 -= lr * dW2; b2 -= lr * db2
if epoch in (0, 100, 500, 3000):
print(f"epoch {epoch:4}: loss={loss:.4f} outputs={out.ravel().round(3)}")epoch 0: loss=0.6712 outputs=[0.5 0.659 0.464 0.554]
epoch 100: loss=0.0379 outputs=[0.011 0.962 0.958 0.057]
epoch 500: loss=0.0051 outputs=[0.001 0.994 0.994 0.008]
epoch 3000: loss=0.0008 outputs=[0. 0.999 0.999 0.001]
The loss drops steadily and the outputs approach the targets 0 1 1 0. (Try default_rng(0): with that starting point the network gets stuck with two outputs near 0.5 — a local minimum. Random initialisation matters, which is why frameworks use careful initialisation schemes.) That's all deep learning is at its core — just with millions of weights, many more layer types, and automatic gradient computation.
Mini-batches and epochs
Real data sets don't fit in one matrix multiplication. Training loops over mini-batches (for example 32 rows at a time); one pass over all batches is an epoch. Each batch gives a noisy but cheap gradient estimate — stochastic gradient descent:
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(200, 3))
true_w = np.array([2.0, -1.0, 0.5])
y = X @ true_w + rng.normal(0, 0.1, 200)
w = np.zeros(3)
batch_size, lr = 32, 0.1
for epoch in range(1, 6):
order = rng.permutation(len(X)) # shuffle every epoch
for start in range(0, len(X), batch_size):
idx = order[start:start + batch_size]
grad = 2 * X[idx].T @ (X[idx] @ w - y[idx]) / len(idx) # gradient of MSE
w -= lr * grad
mse = np.mean((X @ w - y) ** 2)
print(f"epoch {epoch}: w={w.round(3)} mse={mse:.4f}")epoch 1: w=[ 1.556 -0.753 0.242] mse=0.2918
epoch 2: w=[ 1.878 -0.941 0.43 ] mse=0.0318
epoch 3: w=[ 1.963 -0.989 0.473] mse=0.0136
epoch 4: w=[ 1.992 -1. 0.491] mse=0.0119
epoch 5: w=[ 2.006 -1.001 0.487] mse=0.0119
The same idea in PyTorch
PyTorch is the most popular framework in research and increasingly in industry. You define the model as layers, and loss.backward() computes every gradient automatically (autograd). This code is for reading — it needs a local Python installation with pip install torch:
import torch
from torch import nn
X = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
y = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)
model = nn.Sequential(
nn.Linear(2, 4),
nn.Tanh(),
nn.Linear(4, 1),
)
loss_fn = nn.BCEWithLogitsLoss() # sigmoid + cross-entropy in one
optimizer = torch.optim.SGD(model.parameters(), lr=1.0)
for epoch in range(3000):
optimizer.zero_grad() # reset gradients
loss = loss_fn(model(X), y) # forward pass + loss
loss.backward() # backward pass (autograd)
optimizer.step() # gradient-descent update
print(torch.sigmoid(model(X)).detach().round())Compare it with the NumPy version: nn.Linear replaces X @ W + b, loss.backward() replaces the four hand-written gradient lines, and optimizer.step() replaces the manual updates.
The same idea in Keras
Keras (part of TensorFlow, and since Keras 3 also able to run on PyTorch or JAX) hides the training loop behind compile and fit, much like scikit-learn:
import numpy as np
import keras
from keras import layers
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype="float32")
y = np.array([0, 1, 1, 0], dtype="float32")
model = keras.Sequential([
keras.Input(shape=(2,)),
layers.Dense(4, activation="tanh"),
layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer=keras.optimizers.SGD(learning_rate=1.0),
loss="binary_crossentropy", metrics=["accuracy"])
model.fit(X, y, epochs=3000, verbose=0)
print(model.predict(X).round())Layer types beyond dense layers
| Layer | Good for | Idea |
|---|---|---|
| Dense / Linear | tabular data, final layers | every input connected to every neuron |
Convolution (Conv2d) |
images | small filters slide over the image, sharing weights |
Recurrent (LSTM, GRU) |
sequences | a hidden state carried from step to step |
| Attention / Transformer | text, and now almost everything | each position looks at every other position |
| Dropout | regularization | randomly switch off neurons during training |
| Batch / layer normalisation | stable training | rescale activations inside the network |
When to use deep learning
- Yes: images, audio, video, free text, very large data sets, or when you can fine-tune a pretrained model (transfer learning) — often the fastest route to excellent results.
- Often no: small or medium tabular data. Gradient-boosted trees usually win there, train in seconds and need far less tuning.
Go further: Building Models with nn.Module starts the PyTorch part of the Deep Learning course: modules, containers and composing models.
Test yourself
What does loss.backward() do in PyTorch?
- Undoes the last training step
- Computes the gradient of the loss with respect to every parameter
- Prints the loss
- Reverses the data order
What is an epoch?
- One mini-batch
- One full pass over the training data
- One layer of the network
- One weight update
Which layer type is designed for images?
- Dense
- Convolution
- Dropout
- Embedding