Skip to main content

AI and machine learning · Intermediate · 30 min

Write a PyTorch training loop from scratch

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · PyTorch 2.15.0 (CPU) · NumPy 2.5.5

You will train a small PyTorch network on generated customer data with a loop you wrote yourself, complete with a validation pass, a learning-rate scheduler, early stopping, fixed seeds and a checkpoint you can load back.

On this page

Libraries such as PyTorch Lightning and the Hugging Face Trainer hide the training loop behind one fit() call. That works until something goes wrong: the loss will not fall, validation accuracy jumps about, or a run you repeat gives a different answer. At that point you need to know what each line of a loop does, because each of those problems comes from one of them.

In this tutorial you write that loop by hand in plain PyTorch. The task is a small one: a pay-as-you-go solar company wants to know which customers are likely to top up their account within the next seven days, so its field agents can call the ones who probably will not. You generate 6,000 customers with a hidden rule, wrap them in a Dataset and DataLoader, define a network as an nn.Module, and train it. Then you add the parts a real loop needs: a validation pass in eval mode, fixed seeds, a learning-rate scheduler, early stopping, and a checkpoint you can load back and get exactly the same numbers from.

Everything runs on a laptop CPU in well under a minute. No GPU, no downloads after the install. The data is synthetic, so no real customer's details are involved, and the same seeds give the same numbers on the same machine.

Step 1 · Create the project and install PyTorch

Make a throwaway folder and a virtual environment:

Bash
mkdir -p ~/topup-loop-demo
cd ~/topup-loop-demo
python3 -m venv .venv
source .venv/bin/activate

Install PyTorch 2.15.0 from PyTorch's CPU-only package index, then NumPy from PyPI. PyTorch does not need NumPy for this tutorial, but without it every script prints a warning that NumPy failed to initialise.

Bash
pip install --quiet torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu
pip install --quiet numpy==2.5.5

The --index-url matters on Linux. The default torch package on PyPI pulls in the CUDA libraries for NVIDIA GPUs, several gigabytes you do not need on a CPU. The CPU wheel is about 210 MB on Linux and about 140 MB on an Apple silicon Mac. If you pay for data by the gigabyte, the CPU index is the difference between one bundle and several; download once on Wi-Fi and the rest of the tutorial works offline.

Check it worked

Bash
python -c "import torch, numpy; print(torch.__version__, numpy.__version__, torch.cuda.is_available())"

On Linux you see 2.15.0+cpu 2.5.5 False; on a Mac, 2.15.0 2.5.5 False. False is expected: this build has no CUDA support, and nothing below needs it.

Step 2 · Generate customers and wrap them in a Dataset

Each customer has six numbers and one label:

  • days_since_topup: days since their last payment
  • avg_topup: their average top-up, in thousands of the local currency
  • topups_90d: how many times they topped up in the last 90 days
  • household_size: people in the household
  • has_phone_credit: 1 if their phone had airtime at the last check
  • rainy_season: 1 if this is a rainy-season month (less sun, less use)
  • label: 1 if they topped up within seven days, otherwise 0

A Dataset is any object with __len__ (how many rows) and __getitem__ (give me row i). The DataLoader uses those two methods to cut the data into shuffled batches. Here the whole table fits in memory as two tensors; for a CSV or a folder of images you would read the file in __init__ or __getitem__ instead, and the rest of the loop would not change.

Create data.py:

Bash
cat > data.py <<'PY'
import torch
from torch.utils.data import Dataset

FEATURES = [
    "days_since_topup",  # days since the customer last paid
    "avg_topup",         # average top-up, in thousands of the local currency
    "topups_90d",        # number of top-ups in the last 90 days
    "household_size",    # people in the household
    "has_phone_credit",  # 1 if the phone had airtime at the last check
    "rainy_season",      # 1 if the account is in a rainy-season month
]


def make_customers(n=6000, seed=0):
    """Generate n pay-as-you-go customers and whether each topped up within 7 days."""
    g = torch.Generator().manual_seed(seed)
    days = torch.randint(0, 30, (n,), generator=g).float()
    avg = torch.rand(n, generator=g) * 9 + 1
    topups = torch.poisson(torch.full((n,), 6.0), generator=g)
    household = torch.randint(1, 9, (n,), generator=g).float()
    credit = (torch.rand(n, generator=g) < 0.6).float()
    rainy = (torch.rand(n, generator=g) < 0.4).float()

    # The hidden rule: recent, regular payers top up; long gaps and rainy months
    # push the chance down. Days has a bend in it, which a straight line cannot fit well.
    logit = (
        2.0
        - 3.0 * torch.sigmoid((days - 12) / 2)
        + 0.25 * (topups - 6)
        + 0.12 * avg
        - 0.10 * household
        + 0.9 * credit * (1 - rainy)
        - 0.7 * rainy
    )
    y = torch.bernoulli(torch.sigmoid(logit), generator=g)
    X = torch.stack([days, avg, topups, household, credit, rainy], dim=1)
    return X, y


class CustomerDataset(Dataset):
    """Rows of standardised features and a 0/1 label."""

    def __init__(self, X, y, mean, std):
        self.X = (X - mean) / std
        self.y = y

    def __len__(self):
        return len(self.y)

    def __getitem__(self, i):
        return self.X[i], self.y[i]


def load_splits(seed=0):
    """Return train, validation and test datasets plus the scaling numbers."""
    X, y = make_customers(seed=seed)
    order = torch.randperm(len(y), generator=torch.Generator().manual_seed(seed))
    train, val, test = order[:4000], order[4000:5000], order[5000:]
    mean, std = X[train].mean(dim=0), X[train].std(dim=0)
    return (
        CustomerDataset(X[train], y[train], mean, std),
        CustomerDataset(X[val], y[val], mean, std),
        CustomerDataset(X[test], y[test], mean, std),
        mean,
        std,
    )
PY

Three things in there are worth copying into your own projects:

  • The data has its own torch.Generator, so the customers are the same every time, whatever the training code does with random numbers later.
  • The rows are split three ways: 4,000 to train on, 1,000 to make decisions with (validation), and 1,000 kept back for one honest score at the end (test).
  • The mean and standard deviation come from the training rows only and are applied to all three splits. Computing them on all 6,000 rows would leak a little of the validation and test data into training.

Now look at what the DataLoader hands the loop. Create and run peek.py:

Bash
cat > peek.py <<'PY'
from torch.utils.data import DataLoader

from data import load_splits

train_ds, val_ds, test_ds, mean, std = load_splits()
print("rows:", len(train_ds), len(val_ds), len(test_ds))
print("topped up within 7 days:", f"{train_ds.y.mean().item():.1%}")

x0, y0 = train_ds[0]
print("first row:", x0, "label:", y0.item())

loader = DataLoader(train_ds, batch_size=64, shuffle=True)
xb, yb = next(iter(loader))
print("batches per epoch:", len(loader))
print("one batch:", tuple(xb.shape), tuple(yb.shape), xb.dtype)
PY
python peek.py

Check it worked

The output starts rows: 4000 1000 1000 and shows that about 59% of training customers topped up. The first row is six numbers near zero (standardised features), and the label is 1.0 or 0.0. The last two lines read batches per epoch: 63 (4,000 / 64, rounded up: the last batch has 32 rows) and one batch: (64, 6) (64,) torch.float32. Those two shapes are what the model receives and what the loss compares against.

Keep the 59% in mind. A model that always says "will top up" is right 59% of the time, so anything you train has to beat that to be worth having.

Step 3 · Define the model as an nn.Module

An nn.Module holds layers in __init__ and says how data flows through them in forward. Assigning a layer to self registers its weights, which is how model.parameters() later finds every number the optimiser should change.

Create model.py:

Bash
cat > model.py <<'PY'
from torch import nn


class TopUpNet(nn.Module):
    """A small feed-forward network that outputs one logit per customer."""

    def __init__(self, n_features=6, hidden=32, dropout=0.2):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(n_features, hidden),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden, hidden),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden, 1),
        )

    def forward(self, x):
        # (batch, 6) -> (batch, 1) -> (batch,)
        return self.layers(x).squeeze(-1)
PY

The network ends with a plain Linear layer and no sigmoid. Its output is a logit: any real number, where above 0 means "more likely yes". The loss in the next step applies the sigmoid itself, which is more accurate than doing it in the model. When you want a probability for a person to read, call torch.sigmoid on the logit.

Dropout randomly zeroes 20% of the hidden values on each forward pass during training, so the network cannot lean on any single unit. It is also the reason eval mode matters, which you will see in a later step.

Check the model before training it:

Bash
cat > check_model.py <<'PY'
import torch

from model import TopUpNet

model = TopUpNet()
print(model)
n_params = sum(p.numel() for p in model.parameters())
print("parameters:", n_params)

logits = model(torch.zeros(5, 6))
print("output shape:", tuple(logits.shape))
assert n_params == 1313 and logits.shape == (5,)
PY
python check_model.py

Check it worked

The printout lists the seven layers in order, then parameters: 1313 and output shape: (5,). The count is (6 × 32 + 32) + (32 × 32 + 32) + (32 + 1): each Linear layer has a weight per input-output pair plus one bias per output. Five rows in, five logits out, which matches the shape of the labels from the DataLoader.

Step 4 · Write the training loop

One pass of the loop over every training batch is an epoch. Inside it, each batch goes through the same five lines:

Flow diagram of one training step. A batch from the DataLoader goes to 1, zero_grad, which wipes the gradients; 2, model(xb), the forward pass that produces 64 logits; 3, loss_fn, which compares logits with labels and gives one number; 4, loss.backward(), which fills the gradient of all 1,313 weights; and 5, optimiser.step(), which nudges each weight against its gradient. An arrow loops back to the next batch. Notes explain that backward adds to existing gradients, and that validation runs only the forward pass and loss.
One training step, repeated for every batch

Create loop.py with the function that runs one epoch:

Bash
cat > loop.py <<'PY'
def train_one_epoch(model, loader, loss_fn, optimiser):
    """One pass over the training data. Returns the mean training loss."""
    model.train()
    total, count = 0.0, 0
    for xb, yb in loader:
        optimiser.zero_grad()       # 1. clear gradients left from the last batch
        logits = model(xb)          # 2. forward pass
        loss = loss_fn(logits, yb)  # 3. one number: how wrong the batch is
        loss.backward()             # 4. gradients for every parameter
        optimiser.step()            # 5. move the parameters a little
        total += loss.item() * len(xb)
        count += len(xb)
    return total / count
PY

A few details that are easy to get wrong:

  • zero_grad() comes first because backward() adds to each parameter's .grad rather than replacing it. Without it, every step would use the sum of all the gradients so far.
  • loss.item() turns the one-element tensor into a plain Python float. Adding up loss itself would keep every batch's computation graph alive and memory would grow through the epoch.
  • The loss is weighted by len(xb) so the short last batch counts for its 32 rows, not as much as a full one.

Now a script that uses it. BCEWithLogitsLoss is binary cross-entropy for a yes-or-no label, taking logits directly. Adam is a common default optimiser; lr is its learning rate.

Bash
cat > train_v1.py <<'PY'
import torch
from torch import nn
from torch.utils.data import DataLoader

from data import load_splits
from loop import train_one_epoch
from model import TopUpNet

train_ds, val_ds, test_ds, mean, std = load_splits()
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True)

model = TopUpNet()
loss_fn = nn.BCEWithLogitsLoss()
optimiser = torch.optim.Adam(model.parameters(), lr=1e-3)

losses = []
for epoch in range(1, 11):
    loss = train_one_epoch(model, train_loader, loss_fn, optimiser)
    losses.append(loss)
    print(f"epoch {epoch:2d}  train_loss {loss:.4f}")

assert losses[-1] < losses[0]
PY
python train_v1.py

Check it worked

Ten lines print. The first train_loss is something like 0.65 and it falls quickly to about 0.52, then levels off with small ups and downs. Your exact numbers will differ from run to run, because nothing is seeded yet; you fix that two steps from now. If the loss does not move at all, check that optimiser.step() is inside the for loop and that the optimiser was built from model.parameters().

The training loss alone cannot tell you whether the model is learning the rule or memorising these 4,000 customers. For that you need data it never trains on.

Step 5 · Add a validation pass in eval mode

Validation runs the model on the 1,000 held-out customers after each epoch and changes nothing. Two calls make that true:

  • model.eval() switches layers that behave differently in training, here Dropout, into their prediction behaviour. (BatchNorm is the other common one.)
  • torch.no_grad() tells autograd not to record the graph, which saves memory and time, and makes it impossible to call backward() by mistake.

Create evaluate.py:

Bash
cat > evaluate.py <<'PY'
import torch


@torch.no_grad()
def evaluate(model, loader, loss_fn):
    """Mean loss and accuracy on data the model does not learn from."""
    model.eval()
    total, correct, count = 0.0, 0, 0
    for xb, yb in loader:
        logits = model(xb)
        total += loss_fn(logits, yb).item() * len(xb)
        correct += ((logits > 0).float() == yb).sum().item()
        count += len(xb)
    return total / count, correct / count
PY

logits > 0 is the same as a probability above 0.5. train_one_epoch calls model.train() at its start, so switching back after validation is handled.

See for yourself what eval mode changes. This script runs the same customer through an untrained model twice in each mode:

Bash
cat > dropout_check.py <<'PY'
import torch

from model import TopUpNet

model = TopUpNet()
x = torch.randn(1, 6)

model.train()
print("train mode:", model(x).item(), model(x).item())

model.eval()
with torch.no_grad():
    a, b = model(x).item(), model(x).item()
print("eval mode: ", a, b)
assert a == b
PY
python dropout_check.py

In train mode the two numbers differ, because dropout zeroes a different set of units each time. In eval mode they are identical. Forget model.eval() and your validation scores carry that noise.

Now train with a validation pass after each epoch:

Bash
cat > train_v2.py <<'PY'
import torch
from torch import nn
from torch.utils.data import DataLoader

from data import load_splits
from evaluate import evaluate
from loop import train_one_epoch
from model import TopUpNet

train_ds, val_ds, test_ds, mean, std = load_splits()
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True)
val_loader = DataLoader(val_ds, batch_size=256)

model = TopUpNet()
loss_fn = nn.BCEWithLogitsLoss()
optimiser = torch.optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(1, 11):
    train_loss = train_one_epoch(model, train_loader, loss_fn, optimiser)
    val_loss, val_acc = evaluate(model, val_loader, loss_fn)
    print(f"epoch {epoch:2d}  train_loss {train_loss:.4f}  val_loss {val_loss:.4f}  val_acc {val_acc:.3f}")
PY
python train_v2.py

The validation loader does not shuffle: order does not matter when nothing is learned, and a bigger batch makes it faster.

Check it worked

Each line now has three numbers. Validation accuracy climbs from about 0.70 in the first epoch to about 0.75, well above the 59% you get by always saying "will top up". Validation loss settles around 0.51.

You may notice the validation loss is a little lower than the training loss. That is not a bug: the training loss is measured with dropout switched on, which handicaps the model, and it is an average over an epoch in which the model was still improving. The validation loss is measured once, at the end of the epoch, at full strength.

Step 6 · Make runs repeatable with seeds

So far every run starts from different random weights, drops out different units and shuffles in a different order, so the numbers shift each time. That makes it impossible to tell whether a change you made helped or you were lucky. Three random sources need fixing:

  • weight initialisation and dropout, which use PyTorch's global generator (torch.manual_seed)
  • the DataLoader shuffle order, which you give its own generator
  • Python's random module, which this project does not use, but data augmentation code often does

Create seeding.py:

Bash
cat > seeding.py <<'PY'
import random

import torch


def seed_everything(seed):
    """Fix every random number source this project uses. Returns a generator for DataLoader."""
    random.seed(seed)
    torch.manual_seed(seed)  # weight initialisation and dropout
    torch.use_deterministic_algorithms(True)
    return torch.Generator().manual_seed(seed)  # the order DataLoader shuffles in
PY

torch.use_deterministic_algorithms(True) makes PyTorch raise an error if you use an operation that has no repeatable version, rather than giving you slightly different numbers. On CPU it rarely matters; on a GPU it is the setting that catches non-repeatable kernels. If you use NumPy's random functions in your own data code, seed those too.

Test it: train three short runs, two with seed 42 and one with seed 7.

Bash
cat > repeat.py <<'PY'
import torch
from torch import nn
from torch.utils.data import DataLoader

from data import load_splits
from evaluate import evaluate
from loop import train_one_epoch
from model import TopUpNet
from seeding import seed_everything


def short_run(seed):
    g = seed_everything(seed)
    train_ds, val_ds, _, _, _ = load_splits()
    train_loader = DataLoader(train_ds, batch_size=64, shuffle=True, generator=g)
    val_loader = DataLoader(val_ds, batch_size=256)
    model = TopUpNet()
    loss_fn = nn.BCEWithLogitsLoss()
    optimiser = torch.optim.Adam(model.parameters(), lr=1e-3)
    for _ in range(3):
        train_one_epoch(model, train_loader, loss_fn, optimiser)
    return evaluate(model, val_loader, loss_fn)[0]


first, second, other = short_run(42), short_run(42), short_run(7)
print(f"seed 42: {first:.6f}")
print(f"seed 42: {second:.6f}")
print(f"seed 7:  {other:.6f}")
assert first == second and first != other
PY
python repeat.py

The seed is set before the model is built, because building it draws the starting weights.

Check it worked

The two seed 42 lines show the same validation loss to all six decimal places, something like 0.527417, and the seed 7 line shows a different one. Run the script again and you get the same three numbers. On another computer or another PyTorch release the numbers may differ slightly; PyTorch only promises repeatable results on the same platform and version, so record both alongside any result you report.

Step 7 · Add a learning-rate scheduler and early stopping

Two more decisions belong to the validation loss:

  • When to slow down. A high learning rate makes fast progress at first and then bounces around the best weights. ReduceLROnPlateau watches the validation loss and halves the learning rate when it has stopped improving for a few epochs (with patience=3, on the fourth epoch in a row without a new best).
  • When to stop. Training for a fixed number of epochs either stops too soon or carries on while the model starts fitting noise. Early stopping keeps the best epoch so far, saves it, and ends the run when nothing better has turned up for PATIENCE epochs.
Flow diagram of one epoch in train.py. train_one_epoch runs in train mode on 4,000 rows, then evaluate runs in eval mode on 1,000 rows, then scheduler.step(val_loss) halves the learning rate on the 4th epoch in a row without improvement. If this is the best validation loss so far, the script saves checkpoints/best.pt and resets the bad-epoch count, then starts the next epoch. If not, it adds 1 to the count; below 8 it starts the next epoch, at 8 it stops with best.pt holding the best epoch. The test set is not used.
Validation loss steers the learning rate, the checkpoint and the stop

The checkpoint is a dictionary of state_dicts, not the model object. A state_dict maps each parameter's name to its tensor; it does not depend on your class still being importable from the same place, so it survives refactors. The scaling numbers go in too, because without them the saved model cannot read new data.

Create train.py:

Bash
cat > train.py <<'PY'
from pathlib import Path

import torch
from torch import nn
from torch.utils.data import DataLoader

from data import load_splits
from evaluate import evaluate
from loop import train_one_epoch
from model import TopUpNet
from seeding import seed_everything

SEED = 42
MAX_EPOCHS = 200
PATIENCE = 8  # epochs without a better validation loss before stopping
CHECKPOINT = Path("checkpoints/best.pt")

g = seed_everything(SEED)
train_ds, val_ds, test_ds, mean, std = load_splits()
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True, generator=g)
val_loader = DataLoader(val_ds, batch_size=256)

model = TopUpNet()
loss_fn = nn.BCEWithLogitsLoss()
optimiser = torch.optim.Adam(model.parameters(), lr=1e-2)
# Halve the learning rate on the 4th epoch in a row without a better validation loss.
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimiser, mode="min", factor=0.5, patience=3)

CHECKPOINT.parent.mkdir(exist_ok=True)
best_loss, best_epoch, bad_epochs = float("inf"), 0, 0

for epoch in range(1, MAX_EPOCHS + 1):
    train_loss = train_one_epoch(model, train_loader, loss_fn, optimiser)
    val_loss, val_acc = evaluate(model, val_loader, loss_fn)
    lr = optimiser.param_groups[0]["lr"]
    print(f"epoch {epoch:3d}  train {train_loss:.4f}  val {val_loss:.4f}  acc {val_acc:.3f}  lr {lr:.5f}")
    scheduler.step(val_loss)

    if val_loss < best_loss - 1e-4:
        best_loss, best_epoch, bad_epochs = val_loss, epoch, 0
        torch.save(
            {
                "epoch": epoch,
                "model": model.state_dict(),
                "optimiser": optimiser.state_dict(),
                "scheduler": scheduler.state_dict(),
                "val_loss": val_loss,
                "mean": mean,
                "std": std,
                "seed": SEED,
            },
            CHECKPOINT,
        )
    else:
        bad_epochs += 1
        if bad_epochs >= PATIENCE:
            print(f"stopping: no improvement for {PATIENCE} epochs")
            break

print(f"best epoch {best_epoch}, val_loss {best_loss:.4f}, saved to {CHECKPOINT}")
PY
python train.py

The starting learning rate is ten times higher than before, 1e-2, because the scheduler will bring it down. MAX_EPOCHS is only a safety limit; early stopping ends the run long before it. The 1e-4 margin stops a tiny, meaningless improvement from resetting the count.

Check it worked

The run prints one line per epoch and stops on its own after something like 30 epochs with stopping: no improvement for 8 epochs, then a line such as best epoch 20, val_loss 0.5061, saved to checkpoints/best.pt. Read the lr column: it starts at 0.01000 and halves to 0.00500, 0.00250 and so on, each time a few epochs pass without a new best. The validation loss usually improves just after each drop.

The file is there and small:

Bash
ls -l checkpoints/best.pt

It is around 25 KB: 1,313 weights, Adam's two running averages per weight, and a few small entries.

Step 8 · Load the checkpoint and score the test set

Loading is the reverse: build a fresh model from the class, then pour the saved weights in with load_state_dict. torch.load defaults to weights_only=True in current PyTorch, which only unpickles tensors and plain Python types. That is what you want: a checkpoint is a file, and loading a full pickle from someone else can run arbitrary code. Passing it explicitly makes the intent clear.

Create predict.py. It checks the loaded model reproduces the saved validation loss, scores the test set for the first and only time, and predicts for two new customers:

Bash
cat > predict.py <<'PY'
import torch
from torch import nn
from torch.utils.data import DataLoader

from data import load_splits
from evaluate import evaluate
from model import TopUpNet

checkpoint = torch.load("checkpoints/best.pt", weights_only=True)
print("checkpoint from epoch", checkpoint["epoch"], "keys:", sorted(checkpoint))

model = TopUpNet()
model.load_state_dict(checkpoint["model"])
model.eval()

_, val_ds, test_ds, _, _ = load_splits()
loss_fn = nn.BCEWithLogitsLoss()
val_loss, _ = evaluate(model, DataLoader(val_ds, batch_size=256), loss_fn)
test_loss, test_acc = evaluate(model, DataLoader(test_ds, batch_size=256), loss_fn)
print(f"val_loss {val_loss:.4f} (saved {checkpoint['val_loss']:.4f})")
print(f"test_loss {test_loss:.4f}  test_acc {test_acc:.3f}")
assert abs(val_loss - checkpoint["val_loss"]) < 1e-6

# Two new customers: 3 days and 25 days since their last top-up, otherwise alike.
new = torch.tensor([[3, 4.0, 6, 4, 1, 0], [25, 4.0, 6, 4, 1, 0]], dtype=torch.float32)
with torch.no_grad():
    p = torch.sigmoid(model((new - checkpoint["mean"]) / checkpoint["std"]))
print("chance of a top-up within 7 days:", [round(v, 2) for v in p.tolist()])
assert p[0] > p[1]
PY
python predict.py

To carry on training from a checkpoint, for example after a laptop sleeps or a cloud machine is reclaimed, restore the optimiser and scheduler as well as the model. Adam keeps running averages per weight; starting it fresh changes how the next steps behave.

Bash
cat > resume.py <<'PY'
import torch

from model import TopUpNet

checkpoint = torch.load("checkpoints/best.pt", weights_only=True)
model = TopUpNet()
model.load_state_dict(checkpoint["model"])
optimiser = torch.optim.Adam(model.parameters(), lr=1e-2)
optimiser.load_state_dict(checkpoint["optimiser"])
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimiser, mode="min", factor=0.5, patience=3)
scheduler.load_state_dict(checkpoint["scheduler"])
start_epoch = checkpoint["epoch"] + 1
print("resume at epoch", start_epoch, "with lr", optimiser.param_groups[0]["lr"])
PY
python resume.py

From there the loop is the same as in train.py, starting at start_epoch.

Check it worked

predict.py lists the eight keys in the checkpoint, then prints the same validation loss as the training run, matching the saved value to four decimals; the script asserts they agree to within 0.000001. Test accuracy is close to the validation accuracy, something like test_acc 0.749. A test score far below validation would mean your choices had been tuned to the validation set by chance.

The last line gives the customer who paid 3 days ago a much higher chance than the one who paid 25 days ago, something like [0.94, 0.49]. resume.py prints the epoch after the best one and the learning rate in force at that point, which is lower than the starting 0.01, so the restored optimiser carries on where it left off.

A score like this decides who gets a call, not who keeps their service. Before using one on real customers, have a person check a sample of high and low scores against what actually happened, month by month, and check that accuracy holds for each region and language group you serve.

Step 9 · Clean up

Leave the virtual environment and remove the project folder, which includes the PyTorch install:

Bash
deactivate
cd ~
rm -rf ~/topup-loop-demo
ls ~/topup-loop-demo 2>/dev/null || echo "removed"

Check it worked

The last command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.