Image Classification with MNIST
Tensors · Data Prep · Model Building · Training
The MNIST Dataset
MNIST is 70,000 grayscale images of handwritten digits (0–9), each 28×28 pixels — 60,000 for training, 10,000 for testing. It's the "hello world" of deep learning: small enough to train fast, rich enough to teach every core idea you'll reuse for the rest of this course.
Tensors
A tensor is a multi-dimensional array — PyTorch's version of a NumPy array, but with two superpowers: it can run on a GPU, and it can automatically track gradients for backpropagation (the process, a few sections down, that figures out how much to adjust each weight). A single MNIST image is a 28×28 tensor; a batch of 32 images is a 32×28×28 tensor.
import torch x = torch.rand(28, 28) # one "image" of random pixel values print(x.shape) # torch.Size([28, 28])
Preparing the Data
Raw pixel values (0–255) get converted to tensors and normalized to a small, consistent range so the network trains faster and more stably. A DataLoader wraps the dataset to serve it in shuffled batches:
from torch.utils.data import DataLoader train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
Creating the Model
Flatten() takes the image's grid shape — 28 rows of 28 numbers each — and lays it out as one long row of 784 numbers in a line. A dense layer only knows how to read a flat list of numbers, so this step turns the 2D picture into that 1D list before anything else happens.
Then the model passes that list through hidden layers with a non-linear activation called ReLU. ReLU's actual job is simple: any negative number becomes 0, any positive number is left alone. That one small rule is what makes stacking layers actually useful — without it, stacking layers collapses down to being mathematically no different from a single layer. Finally, the output layer has 10 units, one per digit.
import torch.nn as nn
model = nn.Sequential(
nn.Flatten(),
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 10)
)
Training the Model
Training repeats four steps per batch: forward pass (make a prediction) → compute loss (how wrong was it, via CrossEntropyLoss) → backward pass (compute gradients) → optimizer step (nudge the weights). One full pass through all the training data is called an epoch.
Adam is the specific recipe used for that "nudge" step — it decides how big a step to take for each weight, and it adjusts that step size automatically as training goes, which is why it's a safe default rather than something you need to hand-tune.
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
for images, labels in train_loader:
optimizer.zero_grad()
outputs = model(images)
loss = loss_fn(outputs, labels)
loss.backward()
optimizer.step()
Vocabulary
- Tensor
- A multi-dimensional array — PyTorch's core data structure, with GPU support and gradient tracking built in.
- Batch
- A group of examples processed together in one step, rather than one at a time.
- Epoch
- One full pass through the entire training dataset.
- Flatten
- Reshapes a multi-dimensional tensor into one long row per example.
- ReLU
- An activation function: negative numbers become 0, positive numbers stay unchanged.
- Loss function (Cross-Entropy)
- Measures how wrong a prediction was, as a single number to minimize.
- Optimizer (Adam)
- Decides how much to adjust each weight after a mistake, and by how much.
- Backpropagation / gradient
- The calculation that works out how much each individual weight contributed to the error.