Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Deep Learning & Neural Networks — Alpha School

Lesson 7: Building and Training a Network in PyTorch

So far you have learned how networks work in theory. Now you will build one. PyTorch is a popular Python library for deep learning, and its design mirrors the ideas of this course: you describe the layers, define how data flows forward through them, and let the library handle the backward pass for you. The code below builds a small network for recognising handwritten digits, and every line maps to something you already understand.

A network in PyTorch is a class that inherits from torch.nn.Module. In its constructor you create the layers; in its forward method you say how data flows through them. The example uses two hidden layers of 128 and 64 neurons with ReLU activations, and an output layer of 10 neurons, one per digit. That is the whole architecture — the same layers, weights and activations from Lesson 2, written as code.

The Training Loop

Training is a loop with four steps, repeated for every batch. First, run the batch forward through the network to get predictions. Second, compute the loss by comparing those predictions with the true labels. Third, clear the old gradients and call loss.backward(), which runs backpropagation for you. Fourth, call optimizer.step() to update the weights. Those four steps, repeated over many batches and epochs, are the whole of training — everything else is preparation and measurement.

import torch
import torch.nn as nn

class DigitNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 128)
        self.fc2 = nn.Linear(128, 64)
        self.out = nn.Linear(64, 10)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        return self.out(x)

model = DigitNet()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
loss_fn = nn.CrossEntropyLoss()

for inputs, labels in train_loader:   # one batch at a time
    preds = model(inputs)             # 1. forward pass
    loss = loss_fn(preds, labels)     # 2. measure the loss
    optimizer.zero_grad()             # 3a. clear old gradients
    loss.backward()                   # 3b. backpropagation
    optimizer.step()                  # 4. update the weights

A few details deserve attention. nn.Linear(784, 128) creates a layer with 784 inputs — one per pixel of a 28 by 28 image — and 128 outputs. CrossEntropyLoss is the standard loss for classification: it compares the network's scores for all ten digits with the correct one. And optimizer.zero_grad() is easy to forget and important: without it, gradients from the previous batch would pile up and corrupt the next update.

Running It and Watching It Learn

Before training, split your data into training and validation sets and build a data loader for each — the loader handles batching and shuffling for you. After each epoch, run the model on the validation set without updating anything (use torch.no_grad() for that pass) and record both losses. If the training loss falls and the validation loss falls with it, your network is learning. If they split apart, you have met overfitting, and the previous lesson tells you what to do next. That loop — train, validate, adjust — is the daily work of deep learning.

Setting Up Your Environment

Before the code in this lesson will run, you need Python and PyTorch installed, and the simplest path is a fresh environment with a package manager. Install Python, then install PyTorch following the instructions on the PyTorch website for your computer — the CPU version is enough for everything in this course, and the small networks here train in minutes on an ordinary laptop. Work in a folder for the project, keep your data files beside your code, and run the script from the terminal so you can see the loss printed as training proceeds. If the import of torch fails, the usual cause is installing it into a different Python from the one you are running, so check that first before anything else.

A second practical habit is to print progress as you go. After each epoch, print the training loss and the validation loss on one line, so you can watch the two numbers together. When something goes wrong — and it will — those two lines are the first evidence you have, and they will tell you whether the model is learning, memorising, or stuck. Many beginners train in silence and only discover at the end that nothing learned; a single printed line per epoch costs nothing and saves hours.

Common First Errors

Three errors catch almost every beginner, so learn to recognise them. The first is a shape mismatch: the network expects 784 inputs and receives something else, usually because an image was not flattened from 28 by 28 into a single list. The error message will mention shapes, and the fix is to reshape the input before it enters the network. The second is forgetting to call the model in training mode or evaluation mode where it matters — for the networks in this course the difference is small, but it becomes important once dropout is involved. The third is the missing zero_grad, which makes the loss behave strangely because gradients from earlier batches pile up. If the loss jumps or grows instead of falling, check these three before anything else.

Finally, save your trained model when a run goes well. PyTorch lets you save the weights with a single line, and loading them later lets you test the model, show it to others, or continue training without starting over. A trained network is the product of real time and electricity; treating it as disposable is wasteful, and a saved model is also the evidence that your capstone actually worked.

Key Terms

PyTorch
A popular Python library for building and training neural networks.
torch.nn.Module
The PyTorch base class for a network; you define its layers and its forward method.
nn.Linear
A PyTorch layer that computes a weighted sum plus a bias for every output neuron.
CrossEntropyLoss
The standard loss for classification tasks in PyTorch.
Data loader
A PyTorch helper that serves training examples in shuffled batches.
torch.no_grad()
A setting that turns off gradient tracking, used when evaluating a model without training it.
Training loop
The repeated four-step cycle: forward pass, loss, backward pass, weight update.

Discussion Questions

  1. Why must the gradients be cleared before each backward pass? What would happen if they were not?
  2. The code uses Adam with a learning rate of 0.001. How would you decide whether that value is right for your problem?
  3. Why should validation be run with gradients turned off?

Practice Questions

  1. What does loss.backward() do?
  2. What is the purpose of optimizer.step()?
  3. In the example, why does the first layer take 784 inputs?
  4. Why is optimizer.zero_grad() needed before each backward pass?
  5. What does CrossEntropyLoss compare?
Show answers
  1. It runs backpropagation, computing the gradient of the loss with respect to every weight in the network. The gradients are stored, ready for the optimiser to use.
  2. It updates the weights by one step, using the gradients and the optimiser's rule. Without it, the gradients would be computed but never applied.
  3. Because each handwritten digit image is 28 by 28 pixels, and 28 × 28 = 784 — one input per pixel.
  4. Otherwise gradients from the previous batch would pile up and corrupt the next update. PyTorch accumulates gradients by default, so they must be cleared each step.
  5. The network's scores for all the classes against the correct label. It is the standard loss for classification, where exactly one answer is right.
Keep reading to complete this lesson