Plot Training and Validation Loss Curves in Python (PyTorch and Keras)

Record and plot training and validation loss in PyTorch and Keras, mark the best epoch, smooth noisy curves, and recognize overfitting and a bad learning rate.

To plot training loss curves, record the training and validation loss after every epoch and draw both lists with ax.plot(). In Keras, model.fit() returns them in history.history["loss"] and history.history["val_loss"]. In PyTorch, you append the numbers to your own lists inside the training loop. The code below was run with PyTorch 2.15 and Keras 3.15.

Quick Example

This trains a small PyTorch network on 300 noisy points from scikit-learn's make_moons, with another 300 held out for validation.

import matplotlib.pyplot as plt
import torch
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from torch import nn

X, y = make_moons(n_samples=600, noise=0.35, random_state=4)
X_train, X_val, y_train, y_val = train_test_split(
    X, y, test_size=0.5, stratify=y, random_state=4)
X_train, X_val = (torch.tensor(a, dtype=torch.float32) for a in (X_train, X_val))
y_train, y_val = (torch.tensor(a, dtype=torch.float32).unsqueeze(1)
                  for a in (y_train, y_val))


def train(lr=0.01, epochs=200, dropout=0.0, seed=4):
    """Train a small network and return the loss after every epoch."""
    torch.manual_seed(seed)
    model = nn.Sequential(
        nn.Linear(2, 64), nn.ReLU(), nn.Dropout(dropout),
        nn.Linear(64, 64), nn.ReLU(), nn.Dropout(dropout),
        nn.Linear(64, 1),
    )
    loss_fn = nn.BCEWithLogitsLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    history = {"loss": [], "val_loss": []}

    for epoch in range(epochs):
        model.train()
        total = 0.0
        for batch in torch.randperm(len(X_train)).split(32):
            optimizer.zero_grad()
            loss = loss_fn(model(X_train[batch]), y_train[batch])
            loss.backward()
            optimizer.step()
            total += loss.item() * len(batch)  # a float, not a tensor
        history["loss"].append(total / len(X_train))

        model.eval()
        with torch.no_grad():
            history["val_loss"].append(loss_fn(model(X_val), y_val).item())
    return history


def plot_loss(history, ax, title):
    epochs = range(1, len(history["loss"]) + 1)
    ax.plot(epochs, history["loss"], color="#1d4ed8", lw=2, label="Training")
    ax.plot(epochs, history["val_loss"], color="#ea580c", lw=2, label="Validation")
    ax.set(title=title, xlabel="Epoch", ylabel="Loss")


history = train()
best = min(range(len(history["val_loss"])), key=history["val_loss"].__getitem__)

fig, ax = plt.subplots(figsize=(7, 4.5), layout="constrained")
plot_loss(history, ax, "Training and validation loss")
ax.axvline(best + 1, color="#475569", ls="--", lw=1,
           label=f"Best epoch ({best + 1})")
ax.legend()
print("best epoch", best + 1, "val loss", round(history["val_loss"][best], 3))
print("last epoch loss", round(history["loss"][-1], 3),
      "val loss", round(history["val_loss"][-1], 3))
plt.show()

PyTorch loss curves where training loss keeps falling to 0.16 while validation loss bottoms out at epoch 18 and then rises to 0.43

Training loss keeps falling, from about 0.48 to 0.16. Validation loss is lowest at epoch 18 (0.285) and climbs to 0.425 by epoch 200. That widening gap is overfitting: the network is learning noise in the training points.

Three details in the loop affect what you plot:

  • loss.item() stores a plain number. Plotting the loss tensors themselves fails with Can't call numpy() on Tensor that requires grad, and keeping them also holds on to memory. Tensors on a GPU need to be moved to the CPU first, which .item() does too.
  • The training loss is weighted by batch size, so a short last batch doesn't count as much as a full one.
  • model.eval() and torch.no_grad() apply to validation. The first turns dropout off, and the second skips gradient tracking.

How to Plot Loss from a Keras History Object

model.fit() returns a History object. Its history attribute is a dictionary with one list per metric, and passing validation_data (or validation_split) adds the val_ entries. This reuses the data and plot_loss() from above, running Keras 3 on the PyTorch backend. Keras defaults to TensorFlow, so set KERAS_BACKEND before the first import keras. Skip that line if you use TensorFlow.

import os

os.environ["KERAS_BACKEND"] = "torch"  # set before importing keras

import keras
from keras import layers

keras.utils.set_random_seed(4)


def build_model():
    model = keras.Sequential([
        keras.Input(shape=(2,)),
        layers.Dense(64, activation="relu"),
        layers.Dense(64, activation="relu"),
        layers.Dense(1, activation="sigmoid"),
    ])
    model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.01),
                  loss="binary_crossentropy", metrics=["accuracy"])
    return model


model = build_model()
fit = model.fit(X_train.numpy(), y_train.numpy(),
                validation_data=(X_val.numpy(), y_val.numpy()),
                epochs=200, batch_size=32, verbose=0)
print(list(fit.history))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
plot_loss(fit.history, ax1, "Loss")
epochs = range(1, len(fit.epoch) + 1)
ax2.plot(epochs, fit.history["accuracy"], color="#1d4ed8", label="Training")
ax2.plot(epochs, fit.history["val_accuracy"], color="#ea580c", label="Validation")
ax2.set(title="Accuracy", xlabel="Epoch", ylabel="Accuracy")
ax1.legend()
ax2.legend(loc="lower right")
plt.show()

Keras loss and accuracy curves side by side, with validation loss rising while validation accuracy stays roughly flat near 0.87

Validation loss climbs while validation accuracy stays roughly flat around 0.87. Loss penalizes confident wrong answers, so it can get worse even when the number of correct predictions barely changes. If you only plot accuracy, you can miss this.

Stop at the Best Epoch with EarlyStopping

EarlyStopping ends training once the monitored value stops improving for patience epochs. With restore_best_weights=True, the model goes back to the weights from its best epoch.

keras.utils.set_random_seed(4)
model = build_model()
stop = keras.callbacks.EarlyStopping(
    monitor="val_loss", patience=20, restore_best_weights=True)
fit = model.fit(X_train.numpy(), y_train.numpy(),
                validation_data=(X_val.numpy(), y_val.numpy()),
                epochs=200, batch_size=32, callbacks=[stop], verbose=0)

val = fit.history["val_loss"]
print("stopped after", len(val), "epochs; best epoch", stop.best_epoch + 1)
print("restored val loss", model.evaluate(X_val.numpy(), y_val.numpy(), verbose=0)[0],
      "best", min(val))

fig, ax = plt.subplots(figsize=(7, 4.5), layout="constrained")
plot_loss(fit.history, ax, "Early stopping with patience=20")
ax.axvline(stop.best_epoch + 1, color="#475569", ls="--", lw=1,
           label=f"Weights restored (epoch {stop.best_epoch + 1})")
ax.legend()
plt.show()

Loss curves ending after 61 epochs with a dashed line at epoch 41, where validation loss was lowest

Training stopped after 61 epochs and restored epoch 41, where validation loss was 0.278. A larger patience tolerates noisier curves at the cost of more epochs. Because the stopping point was picked using the validation set, report final performance on a separate test set.

In PyTorch, keep copy.deepcopy(model.state_dict()) each time validation loss improves, then pass it to model.load_state_dict() after the loop. The deep copy matters because state_dict() returns references to the live weights.

What Do Overfitting and a Bad Learning Rate Look Like?

The train() function from the Quick Example takes the learning rate and dropout as arguments, so four runs show four common shapes. Shared axes keep the panels comparable.

runs = {
    "Learning rate too low (0.00001)": train(lr=0.00001),
    "Reasonable fit (dropout 0.3)": train(lr=0.003, dropout=0.3),
    "Overfitting (no dropout, lr 0.03)": train(lr=0.03),
    "Learning rate too high (1.0)": train(lr=1.0),
}

fig, axes = plt.subplots(2, 2, figsize=(10, 7), layout="constrained",
                         sharex=True, sharey=True)
for ax, (title, run) in zip(axes.flat, runs.items()):
    plot_loss(run, ax, title)
    ax.label_outer()
    print(title, {k: (round(min(v), 3), round(v[-1], 3)) for k, v in run.items()})
axes[0, 0].legend()
axes[0, 0].set_ylim(0, 1.2)
plt.show()

Four loss curve panels: a learning rate that is too low still sitting high after 200 epochs, a reasonable fit with two flat curves, overfitting with validation loss rising, and a learning rate that is too high jumping erratically

What you see Likely cause What to try
Both curves still high at the last epoch Learning rate too low, or too few epochs Raise the learning rate or train longer
Both curves flatten with a small, steady gap A reasonable fit Stop here, or compare on a test set
Training loss falls while validation loss rises Overfitting Early stopping, dropout, weight decay, more data
Large spikes or jumps to a worse level Learning rate too high Lower it, often by 10 times
Both curves flatten early at a high value Underfitting A larger model or better features

In the too-low run, training loss is still 0.52 after 200 epochs, while the other runs reach about 0.25 or lower at their best. In the too-high run, the first losses are off the top of the chart, and late in training both curves settle around 0.6, worse than where they had been.

To find out whether more data would help, plot error against training set size with a learning curve. It answers a different question from the epoch-by-epoch curves here.

Smooth a Noisy Loss Curve and Use a Log Scale

An exponentially weighted mean from pandas makes the trend easier to see. Keep the raw values faintly behind it so the smoothing doesn't hide spikes. This uses the PyTorch history from the Quick Example.

import pandas as pd

df = pd.DataFrame(history, index=range(1, len(history["loss"]) + 1))
smooth = df.ewm(span=15).mean()

fig, ax = plt.subplots(figsize=(7, 4.5), layout="constrained")
for column, color, label in [("loss", "#1d4ed8", "Training"),
                             ("val_loss", "#ea580c", "Validation")]:
    ax.plot(df.index, df[column], color=color, alpha=0.25, lw=1)
    ax.plot(smooth.index, smooth[column], color=color, lw=2, label=label)
ax.set(title="Smoothed loss on a log scale", xlabel="Epoch", ylabel="Loss",
       yscale="log")
ax.yaxis.set_major_formatter("{x:g}")
ax.yaxis.set_minor_formatter("{x:g}")
ax.legend()
plt.show()

Smoothed training and validation loss on a log scale, with faint raw values behind the smooth lines

yscale="log" gives equal space to equal ratios, which helps when loss drops by a large factor early and then improves slowly. A larger span gives a smoother line that lags further behind the raw values. Choose the best epoch from the raw or saved values, and say so if a chart is smoothed.

Why Is My Validation Loss Lower Than My Training Loss?

This is often normal:

  • Dropout is on while the training loss is measured and off during validation.
  • Timing: the training loss is averaged over batches while the weights are still improving, but validation runs after the epoch ends. It matters most in the first few epochs.
  • The split: a small or easier validation set can score better by chance.

If the gap is large and stays for the whole run, check for duplicated rows between the two sets.

Practical Tips

  • Plot both curves on one y-axis. Separate axes can make a large gap look small.
  • Start the x-axis at epoch 1. fit.epoch counts from 0, as does EarlyStopping.best_epoch.
  • A single lowest point on a noisy curve is partly luck. Compare a few seeds before reading much into small differences.
  • Save the history so you can redraw charts without retraining: pd.DataFrame(history).to_csv("history.csv", index_label="epoch").

Similar Topics