Build and Train a Network on Fashion-MNIST
This is the lesson where you train a real neural network. It will look at small pictures of clothes and learn to say what each one is: a T-shirt, a sneaker, a bag. By the end it will get close to 9 out of 10 pictures right, and you will understand every line of code that got it there.
Open a new Google Colab notebook and turn on a GPU (Runtime, then Change runtime type). Paste each code block into its own cell and run them in order.
What You'll Learn
- How to load a real image dataset with torchvision
- What a
DataLoaderand a batch are - How to define a network as an
nn.Moduleclass - Which loss function and optimizer to use for classification
- How to write the training loop that every PyTorch project uses
The Dataset: Fashion-MNIST
Fashion-MNIST has 70,000 grayscale images of clothing, each 28 by 28 pixels. There are 10 classes:
| Label | Class | Label | Class |
|---|---|---|---|
| 0 | T-shirt/top | 5 | Sandal |
| 1 | Trouser | 6 | Shirt |
| 2 | Pullover | 7 | Sneaker |
| 3 | Dress | 8 | Bag |
| 4 | Coat | 9 | Ankle boot |
It is small enough to train in a few minutes, and hard enough that your model has to learn real patterns.
Step 1: Imports and Device
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import v2
device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
print("Using", device)
Step 2: Load the Data
torchvision can download Fashion-MNIST for you. The transform turns each image into a tensor of numbers between 0 and 1, which is what the network expects.
transform = v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])
train_data = datasets.FashionMNIST(root="data", train=True, download=True, transform=transform)
test_data = datasets.FashionMNIST(root="data", train=False, download=True, transform=transform)
print(len(train_data), "training images")
print(len(test_data), "test images")
image, label = train_data[0]
print(image.shape, train_data.classes[label]) # torch.Size([1, 28, 28]) Ankle boot
This uses torchvision.transforms.v2, which the PyTorch docs recommend as of November 2026. Older tutorials use transforms.ToTensor(). It still works but is marked as deprecated.
Look at a few images to see what the network will learn from:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 6, figsize=(12, 2))
for i, ax in enumerate(axes):
img, lbl = train_data[i]
ax.imshow(img.squeeze(), cmap="gray")
ax.set_title(train_data.classes[lbl])
ax.axis("off")
plt.show()
Step 3: Batches with DataLoader
The network does not learn from one image at a time, and it does not look at all 60,000 at once. It learns from small groups called batches. A DataLoader cuts the dataset into batches and shuffles the training data each epoch, so the model does not learn the order of the images.
train_loader = DataLoader(train_data, batch_size=64, shuffle=True)
test_loader = DataLoader(test_data, batch_size=256)
X, y = next(iter(train_loader))
print(X.shape) # torch.Size([64, 1, 28, 28])
print(y.shape) # torch.Size([64])
One batch holds 64 images and 64 labels. One full pass over all the training batches is called an epoch.
Step 4: Define the Network
In PyTorch you define a network as a class that inherits from nn.Module. It has two parts:
__init__creates the layers.forwardsays how data flows through them.
class FashionNet(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.layers = nn.Sequential(
nn.Linear(28 * 28, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 10),
)
def forward(self, x):
x = self.flatten(x) # [64, 1, 28, 28] becomes [64, 784]
return self.layers(x) # [64, 10]: one score per class
model = FashionNet().to(device)
print(model)
Here is what each piece does:
nn.Flatten()turns each 28 by 28 image into one row of 784 numbers.nn.Linear(784, 256)is a fully connected layer. Each of its 256 outputs is a weighted sum of all 784 inputs, plus a bias.nn.ReLU()keeps positive numbers and turns negative numbers into 0. Without a step like this, stacking layers would be no better than one layer.- The last layer has 10 outputs, one per class. These raw scores are called logits. The highest score is the model's guess.
Count the numbers the model will learn:
total = sum(p.numel() for p in model.parameters())
print(f"{total:,} parameters") # 235,146 parameters
Every one of these starts random. Training will adjust all of them.
Step 5: Loss Function and Optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
nn.CrossEntropyLossis the standard loss for picking one class out of several. It takes the raw logits and the true labels. Do not add a softmax layer to your model first, because this loss already does that step inside.- Adam is an optimizer that adjusts the step size for each weight on its own. It is a safe first choice. A learning rate of
1e-3(0.001) is a common starting point.
Step 6: The Training Loop
This is the heart of the course. Every PyTorch training loop has the same five steps for each batch:
def train_one_epoch(model, loader, loss_fn, optimizer):
model.train()
total_loss = 0.0
for X, y in loader:
X, y = X.to(device), y.to(device) # 1. move the batch to the GPU
logits = model(X) # 2. forward pass: make predictions
loss = loss_fn(logits, y) # 3. measure how wrong they are
optimizer.zero_grad() # 4. reset old gradients
loss.backward() # compute new gradients
optimizer.step() # 5. update the weights
total_loss += loss.item() * len(X)
return total_loss / len(loader.dataset)
Steps 4 and 5 are the same three lines you learned in lesson 2: zero_grad(), backward(), step(). The only new part is that the data now comes in batches and the model is a full network.
Step 7: Measure Accuracy
def evaluate(model, loader, loss_fn):
model.eval()
total_loss, correct = 0.0, 0
with torch.no_grad():
for X, y in loader:
X, y = X.to(device), y.to(device)
logits = model(X)
total_loss += loss_fn(logits, y).item() * len(X)
correct += (logits.argmax(dim=1) == y).sum().item()
n = len(loader.dataset)
return total_loss / n, correct / n
logits.argmax(dim=1) picks the class with the highest score for each image. You will learn more about model.eval() and torch.no_grad() in the next lesson.
Step 8: Train
for epoch in range(5):
train_loss = train_one_epoch(model, train_loader, loss_fn, optimizer)
test_loss, test_acc = evaluate(model, test_loader, loss_fn)
print(f"epoch {epoch+1} train loss {train_loss:.3f} test loss {test_loss:.3f} accuracy {test_acc:.1%}")
On a Colab GPU this takes about a minute. You should see something like this (your numbers will differ a little):
epoch 1 train loss 0.518 test loss 0.437 accuracy 84.5%
epoch 2 train loss 0.370 test loss 0.380 accuracy 86.1%
epoch 3 train loss 0.331 test loss 0.362 accuracy 86.8%
epoch 4 train loss 0.307 test loss 0.353 accuracy 87.4%
epoch 5 train loss 0.289 test loss 0.350 accuracy 87.4%
Your network went from random guessing (10% accuracy) to around 87% in five passes over the data.
Step 9: Ask the Model About One Image
model.eval()
image, label = test_data[0]
with torch.no_grad():
logits = model(image.unsqueeze(0).to(device)) # add a batch dimension
probs = logits.softmax(dim=1)
guess = probs.argmax(dim=1).item()
print("Guess:", test_data.classes[guess], f"({probs[0, guess]:.1%} sure)")
print("Truth:", test_data.classes[label])
unsqueeze(0) turns one image of shape [1, 28, 28] into a batch of one, [1, 1, 28, 28]. Models always expect a batch, even for a single image. softmax turns the logits into probabilities that add up to 1.
If Something Goes Wrong
| Error or symptom | Usual cause |
|---|---|
| "Expected all tensors to be on the same device" | You forgot .to(device) on the model or the batch. |
| "mat1 and mat2 shapes cannot be multiplied" | The input size of a Linear layer does not match the data. Print the shapes. |
| Loss does not go down | Check that optimizer.zero_grad() is in the loop and the learning rate is not too high. |
| Training is slow | You are on CPU. Check the runtime type in Colab. |
Key Takeaways
- torchvision downloads common datasets, and transforms turn images into tensors.
- A DataLoader feeds the model shuffled batches. One pass over all of them is an epoch.
- Define a model as an
nn.Modulewith layers in__init__and the data flow inforward. - For classification, use
nn.CrossEntropyLosson raw logits and start with the Adam optimizer. - The training loop is always: move data, forward pass, loss,
zero_grad(),backward(),step().
Quiz
Up next · Lesson 4 of 6
Evaluate Your Model and Spot Overfitting
6 min read
3 of 6 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

