◆ AI All-in-One

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
↗ Plan a path here

Read first

Optimizers: SGD, Momentum and AdamDropout and Regularizing Neural NetworksPyTorch

This leads to

Transfer LearningDistributed TrainingMixed Precision Training
The full path from zero — 25 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Tensors and Shapes
  13. NumPy and Array Thinking
  14. Supervised Learning
  15. Linear Regression
  16. Training, Validation and Test Sets
  17. The Perceptron
  18. Logistic Regression
  19. Overfitting and the Bias–Variance Tradeoff
  20. Regularization: L1 and L2
  21. Neural Networks
  22. Backpropagation
  23. Dropout and Regularizing Neural Networks
  24. PyTorch
  25. Optimizers: SGD, Momentum and Adam
  26. 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.
1 · Look at the dataread 100 examplescheck labels, balance 2 · Simple baselinetiny model, defaultsnote its score 3 · Sanity checksinitial loss ≈ ln(C)overfit one batch 4 · Fitbig enough modeltrain loss goes low 5 · Regularisemore data, augment,dropout, weight decay 6 · Tunelearning rate first,then the rest something breaks? go back to the last setup that worked
Fig. 1 The training recipe. Each step only starts once the previous one works. When something breaks, go back to the last setup that worked and change one thing.

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 CC classes. The cross-entropy loss for an example is −ln⁡p-\ln p, where pp is the probability the model gave to the correct class. With p=1/Cp = 1/C:

Linitial≈−ln⁡1C=ln⁡CL_{\text{initial}} \approx -\ln\frac{1}{C} = \ln C

Here ln⁡\ln is the natural logarithm. For 2 classes that is ln⁡2≈0.693\ln 2 \approx 0.693. For 10 classes (digits) it is ln⁡10≈2.303\ln 10 \approx 2.303. 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.

Healthyboth fall, small gapepochs →loss Overfittingval turns up while train keeps fallingepochs →loss best checkpoint Learning rate too hightraining loss: jumpy, then blows upepochs →loss → NaN Underfittingboth stay high and flatepochs →loss training lossvalidation loss
Fig. 2 Four loss-curve shapes and what they mean. Healthy: both fall and level off close together. Overfitting: validation loss turns back up while training loss keeps falling, so keep the checkpoint from the minimum. Learning rate too high: jumpy, then the loss explodes. Underfitting: both curves stay high.
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 kk, multiply the learning rate by kk 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 ln⁡2=0.693\ln 2 = 0.693 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 NaN loss is a symptom, not a bug in itself. The usual causes, in order: learning rate too high, a log(0) or division by zero in a hand-written loss, bad input values (check torch.isnan(x).any() on the data), and exploding gradients in deep or recurrent networks. Lower the learning rate first, then clip gradients with torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) before opt.step().

Where it leads

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

  1. 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?
  2. Set the learning rate of the real run to 1.0. Describe the loss curve. Then add gradient clipping. Does it help?
  3. Shuffle y_train randomly (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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You build a 10-class image classifier. Before any training, the loss on the first batch is 15. What does this tell you?

  2. You train on a single batch of 16 examples for 200 steps and the loss stays around 1.5. Where is the problem most likely to be?

  3. Training loss keeps falling, but validation loss reached its lowest point at epoch 12 and has risen since. What should you do?

  4. Your validation loss is slightly lower than your training loss throughout training. What is the most likely reason?

  5. You raise your batch size from 256 to 1,024 with SGD. According to the linear scaling rule, what should you do to the learning rate?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Deep Learning Tuning Playbook

Godbole, Dahl, Gilmer, Shallue & Nado (Google Research) · 2023 · Intermediate · Free

A long, practical guide to choosing and tuning optimizers, batch sizes, learning rates and schedules, written from experience training many models.

Course

Practical Deep Learning for Coders

Jeremy Howard (fast.ai) · Beginner · Free

Top-down and code-first: you train state-of-the-art models in lesson one, then learn how they work. It suits programmers.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Course

Full Stack Deep Learning

FSDL · Intermediate · Free

Lectures on taking deep learning and LLM projects from idea to production.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/training-neural-networks.md