AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
↘Training Results & Evaluation
  1. Reading Loss & Accuracy Curves
  2. Classification Metrics
  3. Regression Metrics & Validation
  4. Experiment Logging & Reproducibility
  5. Hyperparameter Tuning
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Training Results & Evaluation

Reading Loss & Accuracy Curves

Learn to diagnose a training run from its graphs: good fit, overfitting, underfitting, bad learning rates, noisy batches, plateaus, leakage, double descent and LLM loss spikes — and what to do about each.

Beginner~22 min·6 references
Key terms
Loss curveTraining lossValidation lossOverfittingUnderfittingLearning rateSmoothing (EMA)Early stoppingGradient clippingData leakage

A Loss curve is the single most useful window into a model while it trains. Every framework — Keras, PyTorch Lightning, Hugging Face Trainer, TensorBoard, MLflow, W&B — draws the same two lines: [[training-loss]] (how wrong the model is on data it learns from) and [[validation-loss]] (how wrong it is on held-out data it never trains on). Reading these lines correctly tells you whether to wait, stop, change the learning rate, add data, or suspect a bug. This lesson is a field guide: each pattern, what it looks like, why it happens, and what to do.

≈
Practice exams vs the real exam
Training loss is your score on practice questions you have seen many times; validation loss is your score on a fresh mock exam. If practice scores keep improving but mock-exam scores get worse, you are memorizing answers instead of understanding — that is overfitting. If both scores stay bad, you have not studied enough (or the textbook is too hard for you) — that is underfitting.

Anatomy of a training graph

  • x-axis: training progress — epochs (full passes over the data) or steps / iterations (one optimizer update each). LLM runs are almost always plotted in steps or tokens seen.
  • y-axis: the Loss function value (e.g. Cross-entropy (log loss) for classification, MSE for regression). Lower is better. A log scale on y makes late, small improvements visible.
  • Training curve: often logged every step (noisy, because each mini-batch is different) or averaged over the epoch.
  • Validation curve: computed periodically (every epoch or every N steps) on the whole Validation set, so it has fewer, smoother points.
  • Accuracy (or another metric) curves: go *up* when things improve. They are coarser than loss: Accuracy only checks whether the top prediction is right, while loss also measures *how confident* the model is.
✓
Sanity-check the very first point
Before any pattern-reading, check the loss at step 0. With softmax cross-entropy over C balanced classes and a freshly initialized model, the loss should be about ln(C): ≈ 2.30 for 10 classes, ≈ 6.91 for 1000. A much higher starting loss suggests a bad initialization or a bug in the labels/loss. Karpathy also recommends deliberately overfitting one small batch to ~zero loss first: if the model cannot even memorize 2–10 examples, something in the pipeline is broken.[2]
L₀ ≈ −ln(1/C) = ln C (C = 10 → 2.30, C = 1000 → 6.91)
Expected initial cross-entropy loss when the model outputs a uniform distribution.
In words: “a fresh model that knows nothing gives every class the same probability 1/C, so its Cross-entropy (log loss) loss is −ln(1/C), which equals ln C.” It is the loss of a fair guess: your very first logged loss should be close to it. Much higher means the model starts out confidently wrong.
Symbols(hover a symbol in the formula)
L₀
loss at step 0, before any training
≈
approximately (exact only if the outputs are perfectly uniform)
ln
natural logarithm (base e ≈ 2.718); −ln p is large when p is small
1/C
probability that a uniform guess gives to the correct class
C
number of classes
→
“gives”
▸Worked example
C = 10 classes, untrained model outputs 0.1 for every class Cross-entropy = −ln(probability of the true class) = −ln 0.1 ≈ 2.303 C = 2: ln 2 ≈ 0.693 C = 3: ln 3 ≈ 1.099 C = 1000: ln 1000 ≈ 6.908 If a 10-class model starts at loss 5.0, it gives the true class only about e^(−5) ≈ 0.007 — far below 0.1: check the initialization scale or the labels.

The pattern catalogue

PatternWhat you seeWhat to do
Good fitBoth losses fall fast then flatten; val sits slightly above train with a small, stable gap. Val accuracy flattens near train accuracy.Keep the checkpoint with the best val metric. Try a bigger model/more data only if you need more performance.
OverfittingTrain loss keeps falling; val loss reaches a minimum then rises (U-shape). Train accuracy → ~100% while val accuracy stalls or drops. The gap widens.Early stopping at the val minimum; more data or Data augmentation; Regularisation (Dropout, Weight decay); smaller model.
UnderfittingBoth losses stay high and close together; they flatten early. Accuracy is poor on train *and* val.Bigger model, train longer, raise LR, reduce regularization, better features. Check the Baseline — is the task learnable?
LR too highLoss bounces up and down, does not settle, spikes, or shoots to NaN/inf (divergence). Sometimes it drops quickly then stalls at a mediocre level.Lower the Learning rate 3–10×; add Learning rate warmup; add Gradient clipping; check for bad inputs (NaN, huge values).
LR too lowLoss decreases smoothly but painfully slowly, almost a straight line, far from converged when the budget ends.Raise the LR (try ×3, ×10); do a quick LR sweep on a log grid.
Noisy small batchesStep-level train loss is a thick, jagged band; the trend underneath still goes down.Judge the trend with smoothing; if it really hurts, increase Batch size or lower LR. Some noise is normal and even helps generalization.
Plateau, then dropLoss flattens, then suddenly drops in a 'staircase' exactly where a step LR schedule decays the LR (classic ResNet/ImageNet curves).Expected behaviour. If you plateau without a schedule, use ReduceLROnPlateau or a cosine schedule.
Data leakageVal loss is suspiciously low (well below train) or val accuracy is unrealistically high from the start; test results later collapse in production.Check for duplicates between splits, features computed with future information or with the label, preprocessing fit on all data. See the Data leakage section in the validation lesson.
The eight patterns you will see most often. The interactive widget below generates each one.

Overfitting in detail

In an overfitting run the model first learns general patterns (both curves fall), then starts memorizing quirks of the training set (train keeps falling, val turns upward). The epoch where val loss is lowest is the best model — that is exactly what early stopping saves. A subtle but very common case: val loss starts rising while val accuracy is still flat or even improving. That means the model is becoming *over-confident* on the examples it gets wrong (cross-entropy punishes confident mistakes heavily) even though the argmax is still right. It is an early warning sign of overfitting; pick your stopping metric deliberately (the metric you actually care about) rather than by habit.[1]

When validation loss is *below* training loss

This is not automatically leakage. Three innocent reasons: (1) regularization is active only during training — dropout and data augmentation make training harder than evaluation; (2) timing — epoch-level train loss is an average over an epoch during which the model was still improving, while val loss is measured at the end of the epoch (shift the train curve half an epoch left and the gap often vanishes); (3) the val set may simply be easier (small, or a different distribution). Suspect leakage when the gap is large, appears from the very first epoch, and the val score looks too good to be true for the problem.

Learning-rate symptoms

The learning rate is the knob that most often explains an ugly curve. Too high: each update overshoots the valley, so the loss zig-zags, or grows exponentially until it becomes NaN. Too low: every step is tiny, the curve is a slow, nearly straight slope. A quick fix-it routine from the Deep Learning Tuning Playbook and Karpathy's recipe: sweep the LR on a log grid (e.g. 1e-4, 3e-4, 1e-3, 3e-3), train each for a short budget, and pick the largest LR that is still stable. Add Learning rate warmup if the instability happens only in the first few hundred steps.[2][3]

Double descent (good to know)

Classical theory predicts a U-shaped test error: as models grow, error falls, then rises from overfitting. Nakkiran et al. showed that modern deep networks often show double descent: test error falls, rises around the point where the model can *just barely* fit the training set (the interpolation threshold), then falls again as the model grows further. The same shape can appear over epochs (epoch-wise double descent), especially with label noise. Practical lesson: a val-loss bump does not always mean 'stop forever' — with enough capacity or training, it can come back down. Early stopping is still a safe default; just do not over-interpret one bump.[4]

Loss spikes in LLM training

Large language model runs are plotted over hundreds of thousands of steps and occasionally show a sudden spike: the loss jumps up sharply, then either recovers within a few hundred steps or diverges. The PaLM team reported about 20 such spikes in their largest run, even with Gradient clipping enabled; their fix was to restart from a checkpoint about 100 steps before the spike and skip roughly 200–500 data batches around it, which removed the spikes — suggesting they come from an unlucky interaction of particular batches with the current model state, not from 'bad data' alone.[5] Other common mitigations: a lower peak LR or longer warmup, gradient clipping (norm 1.0 is typical), lower Adam β₂ / higher ε, and frequent checkpoints so restarts are cheap.

Smoothing: seeing the trend through the noise

Step-level loss is noisy, so dashboards apply an exponential moving average (EMA). TensorBoard's 'Smoothing' slider is exactly this weight w: each displayed point is a blend of the previous smoothed value and the new raw value. Always keep the faint raw curve visible: heavy smoothing hides spikes and *lags* behind sudden changes, so the smoothed minimum appears later than the real one.[6]

sₜ = w · sₜ₋₁ + (1 − w) · xₜ (w ∈ [0, 1), e.g. 0.6 – 0.99)
EMA smoothing. xₜ = raw value at step t, sₜ = displayed value. TensorBoard also applies a bias correction so the first points are not pulled toward 0.
In words: “the new smoothed value is w parts the previous smoothed value plus (1 − w) parts the new raw value.” Older points fade out geometrically, so the curve averages roughly the last 1/(1 − w) steps: w = 0.9 ≈ the last 10 steps, w = 0.99 ≈ the last 100. Higher w = smoother, but it lags further behind.
Symbols(hover a symbol in the formula)
sₜ₋₁
smoothed value at the previous step
sₜ
smoothed (displayed) value at step t
w
smoothing weight (TensorBoard's slider): how much memory the average has; w = 0 means no smoothing
xₜ
raw logged value at step t (e.g. the batch loss)
∈
“is in / belongs to”
[0, 1)
interval from 0 (included) up to, but not including, 1
·
multiplication
▸Worked example
w = 0.6, raw losses x = 1.0, 0.6, 0.9, 0.5; start with s₁ = x₁ = 1.0 s₂ = 0.6·1.0 + 0.4·0.6 = 0.84 s₃ = 0.6·0.84 + 0.4·0.9 = 0.864 s₄ = 0.6·0.864 + 0.4·0.5 ≈ 0.718 Raw curve: 1.0 → 0.6 → 0.9 → 0.5 (jumpy) Smoothed curve: 1.0 → 0.84 → 0.864 → 0.718 (calmer, but it trails behind the drop to 0.5)
Loading interactive…
Diagnose generated train/val curves, then explore smoothing and log scale.
  1. Play the gallery. For each curve, decide before clicking: is the gap between train and val growing (overfitting), are both high (underfitting), is it bouncing (LR too high) or crawling (LR too low)? Read the feedback for every mistake.
  2. Spot the leakage case: notice validation sitting clearly *below* training from the start. Compare it with the good-fit case where val is slightly above train.
  3. Slide smoothing from 0 to 0.99 on the noisy small-batch curve. At ~0.6–0.9 the trend becomes readable; at 0.99 the smoothed line lags and hides real changes. Watch where the smoothed minimum moves.
  4. Toggle log scale on the plateau-then-drop and LR-too-low curves: late improvements that look flat on a linear axis become visible.

Knobs you control while watching curves

knobSmoothing weight (EMA)
What it is
Display-only weight w of the exponential moving average applied to a logged curve. It never changes training — only how you see it.
↑ If you increase it
Smoother line, easier to see the trend, but more lag: spikes and turning points are hidden or appear late.
↓ If you decrease it
Closer to raw data: every spike is visible, but the trend is buried in batch-to-batch noise.
Typical values
0.6–0.9 for step-level loss; up to 0.95–0.99 for very noisy, very long runs (LLMs). 0 for epoch-level val curves.
knobEvaluation interval
What it is
How often you compute validation loss/metrics (every epoch, or every N steps).
↑ If you increase it
(evaluate less often) Cheaper training, but a coarse val curve: you may miss the true minimum and save a worse checkpoint.
↓ If you decrease it
(evaluate more often) Finer view of overfitting and better checkpoint selection, but evaluation time adds up.
Typical values
Every epoch for small datasets; every 500–5,000 steps for large models, often on a fixed val subset.
knobEarly-stopping patience
What it is
Number of evaluations with no improvement of the monitored metric (beyond a small min_delta) before training stops.
↑ If you increase it
Tolerates noisy val curves and temporary bumps (even double-descent-like ones), but wastes compute after the true optimum.
↓ If you decrease it
Stops quickly and saves compute, but a single noisy evaluation can end training too early.
Typical values
3–10 epochs (or evaluations); always restore the best checkpoint, not the last.
knobGradient clipping max norm
What it is
If the global L2 norm of all gradients exceeds this value, the gradients are rescaled down to it before the optimizer step. Protects against exploding updates and loss spikes.
↑ If you increase it
Clipping rarely triggers: less protection, closer to unclipped training.
↓ If you decrease it
Clipping triggers almost every step: very stable but effectively shrinks the learning rate and can slow learning.
Typical values
1.0 for transformers/LLMs; 0.5–5 for RNNs. Log the pre-clip gradient norm to see how often it fires.

Logging the curves yourself (PyTorch)

python
import torch
from torch.utils.tensorboard import SummaryWriter

writer = SummaryWriter("runs/exp1")
best_val, patience, bad_epochs = float("inf"), 5, 0
step = 0

for epoch in range(100):
    model.train()
    for x, y in train_loader:
        optimizer.zero_grad()
        loss = loss_fn(model(x), y)
        loss.backward()
        grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimizer.step()
        writer.add_scalar("loss/train_step", loss.item(), step)
        writer.add_scalar("grad_norm", grad_norm.item(), step)
        step += 1

    model.eval()
    val_loss, correct, n = 0.0, 0, 0
    with torch.no_grad():
        for x, y in val_loader:
            logits = model(x)
            val_loss += loss_fn(logits, y).item() * len(y)
            correct += (logits.argmax(1) == y).sum().item()
            n += len(y)
    val_loss /= n
    writer.add_scalar("loss/val", val_loss, step)
    writer.add_scalar("acc/val", correct / n, step)

    if val_loss < best_val:                      # early stopping on val loss
        best_val, bad_epochs = val_loss, 0
        torch.save(model.state_dict(), "best.pt")
    else:
        bad_epochs += 1
        if bad_epochs >= patience:
            break
writer.close()
Log train/val loss and accuracy to TensorBoard, clip gradients, and keep the best checkpoint. View with tensorboard --logdir runs.
!
Common misreadings
Most wrong conclusions about training runs come from reading the graph carelessly, not from the model. Watch out for these:
  • Judging a run from the first few hundred steps — many runs look bad early and fine later (and vice versa).
  • Comparing curves with different smoothing, x-axes (epochs vs steps) or batch sizes.
  • Picking the *last* checkpoint instead of the best-val one.
  • Using the test set to choose when to stop — that turns it into a second validation set and your final score becomes optimistic.
  • Trusting a single run: different seeds can move val metrics by a surprising amount; compare 2–3 seeds before concluding.
  • Ignoring the scale: a gap of 0.01 on a log-loss of 0.05 is large; on a loss of 2.3 it is noise.
▸Go deeper: learning curves vs loss curves

A *loss curve* plots error against training time. A Learning curve (in the classical sense used by scikit-learn) plots train and val score against the number of training examples. It answers a different question: 'would more data help?'. If the val score is still climbing as you add data and the train–val gap is large, more data will likely help (high variance). If both curves have converged to a similar, unsatisfying level, more data will not help — you need a more expressive model or better features (high bias). See the Bias-variance trade-off trade-off.

The Tuning Playbook also recommends looking at training curves of the best trials, not just their final numbers: a best trial that is still improving at the end of its budget means the budget, not the hyperparameters, is the bottleneck; a best trial that overfits strongly suggests adding regularization as a tuned hyperparameter.[3]

Quiz

1.
Train loss keeps decreasing for 50 epochs, but validation loss reached its minimum at epoch 12 and has risen since. What is the best interpretation and action?
2.
Your loss jumps around wildly in the first steps and then becomes NaN. Which change is most likely to fix it?
3.
A 10-class classifier with softmax cross-entropy starts training at a loss of 45. What does this suggest?
4.
Validation loss is slightly lower than training loss throughout training, and you use heavy dropout and data augmentation. What is the most reasonable conclusion?
5.
During a long LLM pretraining run the loss suddenly spikes and does not recover. What did the PaLM team do in this situation?
Score: 0/5

References

  1. [1]
    Machine Learning Crash Course — Overfitting: Interpreting loss curves
    CourseGoogledevelopers.google.com
  2. [2]
    A Recipe for Training Neural Networks
    ArticleAndrej Karpathy2019karpathy.github.io
  3. [3]
    Deep Learning Tuning Playbook
    DocsGodbole, Dahl, Gilmer, Shallue, Nado2023github.com
  4. [4]
    Deep Double Descent: Where Bigger Models and More Data Hurt
    PaperNakkiran et al.2019arxiv.org
  5. [5]
    PaLM: Scaling Language Modeling with Pathways
    PaperChowdhery et al.2022arxiv.org
    Section on training instability / loss spikes.
  6. [6]
    TensorBoard: Get started
    DocsTensorFlowtensorflow.org
← Previous
Regularization, Normalization and Initialization
Next →
Classification Metrics