A complete training loop for a multilayer network

MediumDeep learning and building neural networksClassification

Goal: Writing the training and evaluation loop by hand on synthetic data.

Python — example.py
import torch
from torch import nn

torch.manual_seed(0)
X = torch.rand(1200, 2) * 2 - 1
y = ((X ** 2).sum(1) < 0.5).long()
X_tr, y_tr, X_te, y_te = X[:1000], y[:1000], X[1000:], y[1000:]

model = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 2))
opt = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()

for epoch in range(1, 201):
    model.train()
    loss = loss_fn(model(X_tr), y_tr)
    opt.zero_grad(); loss.backward(); opt.step()
    if epoch % 50 == 0:
        model.eval()
        with torch.no_grad():
            acc = (model(X_te).argmax(1) == y_te).float().mean().item()
        print(f"epoch {epoch:3d}  loss={loss.item():.4f}  test_acc={acc:.3f}")

Code explanation

We generate data with a non-linear rule (points inside a circle), build a network with two hidden layers, then repeat: forward pass, loss computation, zeroing gradients, backward, optimizer step. torch.no_grad() during evaluation saves memory.

Requirements

Shell
pip install torch

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

epoch  50  loss=0.1008  test_acc=1.000
epoch 100  loss=0.0197  test_acc=0.995
epoch 150  loss=0.0111  test_acc=0.995
epoch 200  loss=0.0077  test_acc=0.995

This example was actually run and tested on 21 November 2026 on a CPU — torch 2.15.0, python 3.13.18

Libraries used

Related examples

ResearchPyTorchRun and tested

A capsule layer with dynamic routing

Implementing the squash function and the routing-by-agreement algorithm between capsules as in the paper by Sabour et al. (2017).

Convolutional networks · Scientific research