Learning path: Neural Networks from Scratch to Embeddings · Step 6 of 9
The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
Rebuild the Keras digit network in PyTorch and write the training loop yourself: DataLoader batches, an nn.Module class, five lines per batch, eval with no_grad, and 0.9756 test accuracy.
What you will learn
- Batch data with TensorDataset and DataLoader
- Write a model as an nn.Module class with a forward method
- Train with the five-line loop: forward, loss, zero_grad, backward, step
- Check a model with model.eval() and torch.no_grad(), and test once at the end
Before you start
- Your First Neural Network with Keras
- Loss and Backpropagation
An automatic car changes gear for you. That's Keras: one call to fit and the gears change by themselves, under the hood. A manual gearbox is a little more work. That's PyTorch: the gears are forward, loss, zero_grad, backward and step, and you change every one yourself.
Same road, same speed. The difference is control. In this article we rebuild the digit network from Your First Neural Network with Keras and write the training loop out in full.
Step 1: batches from a DataLoader
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
torch.manual_seed(42)
d = np.load("mnist.npz")
X = torch.tensor(d["x_train"] / 255.0,
dtype=torch.float32)
y = torch.tensor(d["y_train"], dtype=torch.long)
X_tr, y_tr = X[:48000], y[:48000]
X_va, y_va = X[48000:], y[48000:]
Pixels divided by 255 become float tensors. The first 48,000 images train and the last 12,000 validate, the same split Keras used.
train_ds = TensorDataset(X_tr, y_tr)
train_loader = DataLoader(
train_ds, batch_size=32, shuffle=True)
xb, yb = next(iter(train_loader))
print(X_tr.shape, X_va.shape)
print("batches per epoch:", len(train_loader))
print("one batch:", xb.shape, yb.shape)
torch.Size([48000, 28, 28]) torch.Size([12000, 28, 28])
batches per epoch: 1500
one batch: torch.Size([32, 28, 28]) torch.Size([32])
A TensorDataset pairs every picture with its label. The DataLoader hands them out in shuffled batches of 32: 1,500 batches per epoch, each one 32 pictures and 32 labels.
Step 2: the model is a class
class DigitNet(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.hidden = nn.Linear(784, 128)
self.out = nn.Linear(128, 10)
def forward(self, x):
x = self.flatten(x)
x = torch.relu(self.hidden(x))
return self.out(x)
A PyTorch model extends nn.Module. In __init__ you list the layers. In forward you say how the data flows through them: that's the forward pass, written by you. There's no softmax at the end, because nn.CrossEntropyLoss takes the raw scores.
device = "cuda" if torch.cuda.is_available() else "cpu"
model = DigitNet().to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
print("params:", sum(p.numel() for p in model.parameters()))
print("device:", device)
params: 101770
device: cpu
The same 101,770 knobs as in Keras. The loss is cross-entropy and the optimiser is Adam. On a GPU, device simply becomes cuda.
Step 3: the five-line training loop
def train_one_epoch():
model.train()
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
pred = model(xb)
loss = loss_fn(pred, yb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
fit.- Forward:
pred = model(xb), the batch goes through the network. - Loss:
loss_fn(pred, yb), how wrong was the guess? - Zero grad:
optimizer.zero_grad()wipes the gradients from the last batch. PyTorch adds gradients up otherwise, like dirty dishes piling up in the sink. - Backward:
loss.backward()passes the blame back to every weight. That's backpropagation. - Step:
optimizer.step()nudges every weight.
Then the next batch, and the same five lines again. That's really all training is.
Step 4: checking with eval() and no_grad()
def evaluate(X, y):
model.eval()
with torch.no_grad():
pred = model(X.to(device))
y = y.to(device)
loss = loss_fn(pred, y).item()
acc = (pred.argmax(1) == y).float().mean()
return loss, acc.item()
model.eval() switches the model to checking mode. Inside torch.no_grad() no blame is tracked, so it's faster and it never changes a weight. train() is for learning, eval() is for checking.
Ten epochs, our way
for epoch in range(1, 11):
train_one_epoch()
tr_loss, _ = evaluate(X_tr, y_tr)
va_loss, va_acc = evaluate(X_va, y_va)
print(f"epoch {epoch:2d}",
f"train_loss {tr_loss:.3f}",
f"val_loss {va_loss:.3f}",
f"val_acc {va_acc:.3f}")
epoch 1 train_loss 0.166 val_loss 0.174 val_acc 0.951
epoch 2 train_loss 0.102 val_loss 0.126 val_acc 0.965
epoch 3 train_loss 0.067 val_loss 0.100 val_acc 0.970
epoch 4 train_loss 0.049 val_loss 0.090 val_acc 0.974
epoch 5 train_loss 0.037 val_loss 0.083 val_acc 0.975
epoch 6 train_loss 0.029 val_loss 0.084 val_acc 0.975
epoch 7 train_loss 0.024 val_loss 0.088 val_acc 0.975
epoch 8 train_loss 0.018 val_loss 0.090 val_acc 0.975
epoch 9 train_loss 0.018 val_loss 0.095 val_acc 0.976
epoch 10 train_loss 0.018 val_loss 0.099 val_acc 0.973
Validation accuracy goes from 0.951 after epoch 1 to 0.973 after epoch 10. The validation loss is lowest at epoch 5 (0.083) and then creeps up again: the same overfitting signal we saw in Keras and in The Training Loop.
Step 5: only now, the test set
X_te = torch.tensor(d["x_test"] / 255.0,
dtype=torch.float32)
y_te = torch.tensor(d["y_test"], dtype=torch.long)
test_loss, test_acc = evaluate(X_te, y_te)
print("test accuracy:", round(test_acc, 4))
with torch.no_grad():
scores = model(X_te[:1].to(device))
print("true:", y_te[0].item())
print("predicted:", scores.argmax().item())
test accuracy: 0.9756
true: 7
predicted: 7
0.9756 on the test digits. Keras gave 0.9772, so it's the same network within a few tenths of a percent. The first test image is a 7, and the network says 7.
Common mistakes
- Leaving out
optimizer.zero_grad(). Gradients from earlier batches pile up and the steps go wrong. - Adding softmax before
nn.CrossEntropyLoss. The loss expects raw scores and applies it for you. - Evaluating without
model.eval()andtorch.no_grad(). You waste memory tracking gradients you'll never use. - Model and data on different devices. Move both with
.to(device).
Quick recap
| Piece | PyTorch | Keras equivalent |
|---|---|---|
| Batches | DataLoader(batch_size=32, shuffle=True) | fit(batch_size=32) |
| Model | class DigitNet(nn.Module) with forward | Sequential([...]) |
| Training | forward, loss, zero_grad, backward, step | fit |
| Checking | model.eval() + torch.no_grad() | evaluate |
| Test accuracy | 0.9756 | 0.9772 |
Try it yourself
Change batch_size from 32 to 128. How many batches per epoch do you get now, and what happens to the validation accuracy?
The notebook and mnist.npz are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Your First Neural Network with Keras: MNIST Digits at 97.7%
Next →Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.