Level 3 In-Depth AI · Deep Learning
Training Neural Networks in Practice
A practical recipe for getting a neural network to train. Look at the data, check that the loss starts where it should, overfit one batch, read the loss curves, then regularise and tune.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, a weekend to practise
- Builds on
- 25 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 25 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- NumPy and Array Thinking
- Supervised Learning
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Regularization: L1 and L2
- Neural Networks
- Backpropagation
- Dropout and Regularizing Neural Networks
- PyTorch
- Optimizers: SGD, Momentum and Adam
- Training Neural Networks in Practice
Read them roughly in this order. See it on the concept map →
Why it matters
The earlier chapters explain the parts: layers, Backpropagation, Optimizers: SGD, Momentum and Adam, learning-rate schedules, regularisation. Knowing the parts is not the same as getting a network to learn. A first attempt usually fails, and it fails quietly. Nothing crashes. The code runs, the loss goes down a bit, and the model is simply worse than it should be. Maybe the labels were shuffled separately from the images, maybe the learning rate is ten times too high, or maybe the validation set leaked into training. A neural network will still train with all of these bugs, so the only defence is a careful process.
This chapter is that process. It is the same whether you train a ten-line classifier on your laptop or a large The Transformer on a cluster: build up from something small that you know works, check every assumption with a number, and read the loss curves like a doctor reads a chart. Andrej Karpathy summed it up in his widely read 2019 blog post: neural network training is a "leaky abstraction" and it "fails silently". Most of what follows comes from that tradition of hard-won practice.
The intuition
Think of a pilot before take-off. The plane is complicated, so the pilot does not just push the throttle and hope. They run through a checklist: fuel, flaps, instruments, each confirmed with a reading. Only then do they take off, and they keep watching the instruments during the flight.
Training a network works the same way:
- Before take-off: look at the data with your own eyes, and set up the simplest possible model to compare against.
- Pre-flight checks: confirm that the loss starts at the value theory predicts, and that the model can memorise a handful of examples perfectly.
- In flight: watch two instruments, the training loss and the validation loss, and know what their shapes mean.
- Adjusting course: only once the model can fit the data do you add regularisation and tune settings, one change at a time.
Key idea Change one thing at a time, and check each change with a number. A network that "sort of trains" can hide a dozen bugs. A sequence of small, verified steps cannot.
How it works
Step 1: become one with the data
Before writing any model code, look at a hundred or so raw examples. Print them, plot them, listen to them. You are looking for duplicates, corrupted files, wrong labels, inconsistent units, and how the classes are balanced. If 95% of your emails are "not spam", a model that always says "not spam" scores 95% accuracy and has learned nothing. You need to know that number before you can judge any result.
Also check how you split the data. The validation set is data held back from training that you use to make decisions. The test set is touched only once, at the end (Training, Validation and Test Sets). The splits must not share near-duplicates, such as the same patient, the same photo cropped twice, or the same day of a time series. Otherwise validation scores look great and the real world doesn't.
Step 2: a dumb baseline
A baseline is the simplest model that could possibly work. That might be "always predict the most common class", a logistic regression, or a tiny network with default settings. It gives you a number to beat and a pipeline that runs end to end: data loading, training, evaluation, saving. Fix the random seed so runs are repeatable while you debug.
Step 3: sanity checks
A sanity check is a quick test whose correct answer you know in advance. Two are worth doing every time.
Check the initial loss. A freshly initialised classifier knows nothing, so it should give roughly equal probability to each of the classes. The cross-entropy loss for an example is , where is the probability the model gave to the correct class. With :
Here is the natural logarithm. For 2 classes that is . For 10 classes (digits) it is . For 1,000 classes (ImageNet) it is about 6.9. If your 10-class model starts at 15, something is off: the outputs are huge because of a bad initialisation, the labels are wrong, or you applied softmax twice.
Overfit a single batch. Take one small batch, say 16 examples, and train on only that batch, again and again. A network with thousands of parameters can memorise 16 examples, so the loss must go to almost zero. This is called overfitting a single batch. If it can't, the bug is in your code, not your data or your hyperparameters. Typical culprits are a missing optimizer.zero_grad(), labels that don't match their inputs, a frozen layer, or a loss applied to the wrong tensor. This one check catches more bugs than any other.
Step 4: fit, and read the loss curves
Now train on the full training set in mini-batches. The training loop is the code that does this. For each batch it runs the forward pass, computes the loss, clears the old gradients, runs backpropagation and takes an optimizer step, then repeats (Gradient Descent showed the four core lines). After each epoch, compute the loss on the validation set with gradients switched off.
Plot both numbers against time. These plots are loss curves, also called learning curves. They are the main instrument panel of deep learning, and their shapes tell you what is going on.
| What you see | What it probably means | What to try |
|---|---|---|
| Both losses fall and flatten close together | Healthy | Train longer or use a bigger model if you need more |
| Training loss falls, validation loss rises | [[overfitting\vert Overfitting]] | More data, augmentation, dropout, weight decay, stop earlier |
| Both losses stay high | Underfitting: model too small or training too short | Bigger model, train longer, higher learning rate |
Loss jumps wildly, then shoots up or becomes NaN |
Learning rate too high, or exploding gradients | Lower learning rate by 3–10×, add warmup, clip gradients |
| Loss stuck exactly flat from step 0 | Nothing is learning: bug, dead ReLUs, zero learning rate | Go back to "overfit one batch" |
| Validation loss lower than training loss | Often dropout or augmentation (active only in training) | Usually fine. Check for leakage if the gap is big |
Two more numbers are worth logging. The gradient norm, the overall size of the gradient vector, warns of explosions before the loss does. The current learning rate confirms that your schedule does what you think it does.
Step 5: regularise
Only once the model can fit the training data do you fight overfitting. The tools come from Dropout and Regularizing Neural Networks and Regularization: L1 and L2, roughly in order of how much they help. More real data comes first. Then Data Augmentation, which means flipping, cropping or otherwise varying the inputs. Then weight decay, then dropout. Finally, early stopping: keep a checkpoint, a saved copy of the weights, from the epoch with the best validation loss, rather than the last one.
Step 6: tune
Hyperparameters do not matter equally. The learning rate matters most. Sweep it on a log scale (for example 3e-4, 1e-3, 3e-3) before touching anything else. Next come the schedule, weight decay, batch size and model size. Hyperparameter Tuning covers search strategies. Google's Deep Learning Tuning Playbook is a good, detailed practical guide.
Batch size
The batch size is the number of examples per gradient step. Larger batches give a less noisy gradient estimate and use the GPU more efficiently, up to the memory limit. But each epoch then has fewer steps. A rule of thumb that often holds is the linear scaling rule: if you multiply the batch size by , multiply the learning rate by too, with a short warmup. Goyal and colleagues at Facebook used it in 2017 to train a ResNet-50 on ImageNet with batches of 8,192 images in one hour, matching the accuracy of small-batch training. The rule breaks down at very large batches, and with Adam the scaling is usually gentler. In practice: pick the largest batch that fits in memory, keep the default otherwise, and re-tune the learning rate whenever you change it. If a batch you want doesn't fit, gradient accumulation sums the gradients of several small batches before taking one optimizer step.
Worked example: reading the numbers
Here is a real run, the PyTorch code in the next section, on a two-class toy dataset:
| Check | Expected | Got | Verdict |
|---|---|---|---|
| Initial loss | 0.743 | Close: initialisation is fine | |
| Loss on one batch of 16 after 200 steps | near 0 | 0.0001 | The code can learn |
| Epoch 10: train / val loss | val ≈ train | 0.123 / 0.095 | Healthy, no overfitting yet |
| Epoch 30: validation accuracy | better than the baseline of 50% | 97.0% | Good |
Each line rules out a whole family of bugs. Only after all four are green is it worth spending time on tuning.
In code
A complete, runnable version of steps 3 and 4 in PyTorch, on scikit-learn's "two moons" toy data:
import math
import torch
import torch.nn as nn
from sklearn.datasets import make_moons
torch.manual_seed(0)
X, y = make_moons(n_samples=1200, noise=0.25, random_state=0)
X, y = torch.tensor(X, dtype=torch.float32), torch.tensor(y)
X_train, y_train, X_val, y_val = X[:1000], y[:1000], X[1000:], y[1000:]
def make_model():
return nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 2))
loss_fn = nn.CrossEntropyLoss() # expects raw scores (logits), not softmax
model = make_model() # Check 1: initial loss ~ ln(2)
with torch.no_grad():
print(f"initial loss {loss_fn(model(X_train), y_train):.3f}, expected ~{math.log(2):.3f}")
opt = torch.optim.Adam(model.parameters(), lr=1e-2) # Check 2: memorise one batch
xb, yb = X_train[:16], y_train[:16]
for step in range(200):
loss = loss_fn(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
print(f"one-batch loss after 200 steps {loss.item():.4f}")
model = make_model() # The real run, on a fresh model
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-2)
for epoch in range(1, 31):
model.train() # dropout/batchnorm in training mode
perm = torch.randperm(len(X_train)) # reshuffle every epoch
for i in range(0, len(X_train), 64):
idx = perm[i:i + 64]
loss = loss_fn(model(X_train[idx]), y_train[idx])
opt.zero_grad(); loss.backward(); opt.step()
model.eval() # evaluation mode
with torch.no_grad(): # no gradients needed
tr = loss_fn(model(X_train), y_train).item()
logits = model(X_val)
va = loss_fn(logits, y_val).item()
acc = (logits.argmax(1) == y_val).float().mean().item()
if epoch in (1, 10, 20, 30):
print(f"epoch {epoch:2d} train {tr:.3f} val {va:.3f} val acc {acc:.3f}")
# initial loss 0.743, expected ~0.693
# one-batch loss after 200 steps 0.0001
# epoch 1 train 0.332 val 0.324 val acc 0.830
# epoch 10 train 0.123 val 0.095 val acc 0.955
# epoch 20 train 0.124 val 0.098 val acc 0.955
# epoch 30 train 0.121 val 0.097 val acc 0.970
In real projects you would also save a checkpoint whenever validation loss improves (torch.save(model.state_dict(), "best.pt")) and send the numbers to a logger such as TensorBoard or Weights & Biases rather than printing them (Experiment Tracking and Reproducibility).
Common pitfalls
- Softmax before
CrossEntropyLoss. PyTorch's cross-entropy applies log-softmax itself. Applying softmax first still trains, but badly. The initial-loss check often catches this. - Forgetting
model.eval()/model.train(). Dropout and batch normalisation behave differently in the two modes. Evaluating in training mode gives noisy, pessimistic validation numbers. Forgetting to switch back silently turns dropout off for the rest of training. - Shape broadcasting. A prediction of shape
(64, 1)minus a target of shape(64,)becomes a(64, 64)matrix without any error, and the loss is nonsense. Print shapes the first time through. - Data and labels out of sync. Shuffling the inputs and the labels separately is the classic version. Overfitting one batch won't catch it, because random labels can be memorised too. Looking at a few (input, label) pairs straight from your data loader does.
- Not shuffling the training data. If the data are sorted by class, each batch contains one class and the model swings back and forth.
- Tuning on the test set. Every decision you make by looking at a score is a little bit of training. Make decisions on validation data and touch the test set once.
- Changing several things at once. When the result improves or breaks, you won't know why.
Watch out
NaNloss is a symptom, not a bug in itself. The usual causes, in order: learning rate too high, alog(0)or division by zero in a hand-written loss, bad input values (checktorch.isnan(x).any()on the data), and exploding gradients in deep or recurrent networks. Lower the learning rate first, then clip gradients withtorch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)beforeopt.step().
Where it leads
- Residual Connections and normalisation layers make very deep networks much easier to train in the first place.
- Transfer Learning: rather than training from scratch, start from a network someone else trained on a large dataset. For most practical problems this is step 2 of the recipe.
- Mixed Precision Training and Distributed Training make the same recipe run faster on bigger hardware.
- Experiment Tracking and Reproducibility and Hyperparameter Tuning turn steps 4–6 into a systematic process.
- GPUs and Why AI Needs Them explains what actually limits your batch size.
A bit of history
For most of the 1990s and 2000s, training deep networks had a reputation as a black art, full of tricks passed on in labs rather than written down. Yann LeCun, Léon Bottou, Genevieve Orr and Klaus-Robert Müller's 1998 chapter Efficient BackProp was one of the first attempts to collect them: shuffle the data, normalise the inputs, pick initial weights carefully. After 2012, when deep networks began to win competitions, the knowledge spread through courses (CS231n, fast.ai) and blog posts, most famously Karpathy's A Recipe for Training Neural Networks (2019). In 2023 a group at Google Research published the Deep Learning Tuning Playbook, a long, openly shared document about tuning in practice. The tools have changed, but the core advice — start small, verify everything, change one thing at a time — has not.
Try it
- In the code, add
torch.softmax(..., dim=1)around the model output before the loss. What happens to the initial loss and the final accuracy?- Set the learning rate of the real run to
1.0. Describe the loss curve. Then add gradient clipping. Does it help?- Shuffle
y_trainrandomly (y_train = y_train[torch.randperm(1000)]) and train again. Does the one-batch check still pass? What do the training and validation losses do now?Hint for 3: a big enough network can memorise random labels, so training loss can still fall while validation accuracy stays near 50%. This is why you look at the data and run the checks.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
A Recipe for Training Neural Networks
Hard-won, practical advice on training neural nets without fooling yourself.
Deep Learning Tuning Playbook
A long, practical guide to choosing and tuning optimizers, batch sizes, learning rates and schedules, written from experience training many models.
Practical Deep Learning for Coders
Top-down and code-first: you train state-of-the-art models in lesson one, then learn how they work. It suits programmers.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Full Stack Deep Learning
Lectures on taking deep learning and LLM projects from idea to production.
Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour
Introduced the linear learning-rate scaling rule with warmup for large batch sizes.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/training-neural-networks.md