Learn PyTorch · 5/12

Training a Model: The Optimization Loop

10 min read

Welcome back! So, you've built a neural network model. Fantastic! Right now, though, your model is like a newborn baby—it doesn't know anything. If you ask it to predict something, its guess will be completely random and utterly useless.

The problem is clear: our model is "untrained." We need a systematic way to teach it how to make accurate predictions.

This guide will walk you through the very heart of deep learning: the training process. This process is an elegant loop where the model makes a guess, gets scored on how wrong it is, and then gets adjusted just a little bit to be better on the next try. We repeat this thousands of times, and voilà, the model learns!

Let's imagine we're teaching a brand new, high-tech robot 🤖 how to shoot a basketball 🏀. The robot is our model, and its internal settings (angles, power) are the parameters we need to tune. This entire process is our Optimization Loop.


1. Choosing a Loss Function: The Brutally Honest Scoreboard 📝

The Problem: The robot takes its first shot. It misses. How do we tell it how badly it missed? Simply saying "you missed" isn't enough. Did it miss by a millimeter or a meter? We need a precise, mathematical way to measure the error.

The Solution: A Loss Function (also called a "Criterion") is our tool for this. It takes the model's prediction (where the ball went) and the actual target (the center of the hoop) and calculates a single number—the "loss" or "error"—that represents how bad the prediction was. A higher number means a worse miss.

Our goal throughout training is to get this loss number as close to zero as possible.

In the industry, you'll see two types of loss functions used 99% of the time, depending on your task.

For Regression (Predicting a Number): MSELoss

If you're predicting a continuous value, like the price of a house or... the exact distance a basketball shot was from the hoop, you'll want Mean Squared Error loss.

  • What it does: It calculates the difference between the prediction and the target, squares it, and then averages these squared differences across all the data points.
  • Why square it? Squaring does two cool things:
    1. It makes the error positive, so missing high isn't cancelled out by missing low.
    2. It punishes larger errors way more than smaller ones. Missing by 10 units gives a squared error of 100, while missing by 2 gives an error of only 4. This tells the model to really fix its big mistakes.

Here’s how you'd set it up in PyTorch:

python
import torch
import torch.nn as nn

# Let's pretend our robot shot the ball to position 2.5
# But the hoop was at position 5.0
prediction = torch.tensor([2.5])
target = torch.tensor([5.0])

# Initialize the loss function
loss_fn = nn.MSELoss()

# Calculate the loss
loss = loss_fn(prediction, target)

print(loss) # Output will be tensor(6.25), because (5.0 - 2.5)^2 = 6.25

For Classification (Predicting a Category): CrossEntropyLoss

If you're predicting which category something belongs to—like "cat," "dog," or "bird," or which of three possible hoops (A, B, C) our robot should aim for—this is your champion.

  • What it does: CrossEntropyLoss is brilliant for classification. It does two things in one package:
    1. It applies a function (SoftMax) to your model's raw output scores (logits) to turn them into probabilities (e.g., "75% chance it's hoop A, 15% hoop B, 10% hoop C").
    2. It then measures how bad those probabilities are, heavily penalizing the model if it was very confident about the wrong answer.

Here’s a PyTorch example:

python
import torch
import torch.nn as nn

# Model's raw output for 3 classes (e.g., hoop A, B, C)
# It thinks it's most likely class 0 (hoop A).
predictions = torch.tensor([[2.0, -1.0, 0.5]]) # Raw scores (logits)

# The correct answer was class 2 (hoop C).
# Note: The target is just the index of the correct class.
target = torch.tensor([2])

# Initialize the loss function
loss_fn = nn.CrossEntropyLoss()

# Calculate the loss
loss = loss_fn(predictions, target)

print(loss) # Output will be a tensor with the calculated loss value

🧠 Fun Fact: Cross-Entropy is a concept borrowed from information theory. It's a way of measuring the "surprise" of seeing the true outcome given your predicted probabilities. If you predict a 1% chance of rain and it pours, you are very "surprised," and the loss is high!


2. Setting up an Optimizer: The Smart Coach 👨‍🏫

The Problem: Okay, our loss function just screamed at the robot: "YOUR LOSS IS 6.25!". The robot knows it messed up. But what should it do? Which of its 1,000 internal settings (parameters) should it change, and by how much?

The Solution: An Optimizer is the algorithm that acts like a coach. It takes the loss value and uses it to figure out how to update every single one of the model's parameters to make the loss smaller next time.

  • Under the Hood (The 10-Second Version): The optimizer uses a process called backpropagation (powered by calculus's chain rule) to calculate the "gradient" for each parameter. Think of the gradient as a little arrow pointing in the direction of the steepest increase in loss. The optimizer then takes a small step in the exact opposite direction of that arrow, thereby decreasing the loss. The size of that step is called the learning rate.

You'll mostly encounter two main optimizers.

The Classic: SGD (Stochastic Gradient Descent)

SGD is the old, reliable workhorse. It's simple and effective. It calculates the gradient and takes a step. That's it.

  • Analogy: Our robot coach (SGD) tells the robot, "Your aim was off. Adjust your arm 0.1 degrees to the right." It's a consistent, steady, but sometimes slow and wobbly path to improvement.
python
import torch.optim as optim

# Assume `model` is your defined neural network
# The `model.parameters()` call gives the optimizer a list of all
# the things it needs to be able to tune.
# `lr` is the learning rate - maybe the most important hyperparameter!
optimizer = optim.SGD(model.parameters(), lr=0.01)

The Default Choice: Adam (Adaptive Moment Estimation)

Adam is the optimizer that, in many cases, "just works." It's an extension of SGD that is often much faster and more reliable.

  • What makes it special? It adapts the learning rate for each parameter individually. It maintains a "momentum" (a running average of past gradients), which helps it move more confidently in the right direction.
  • Analogy: Adam is a smarter coach. It says, "Okay, for the past 10 shots, you've consistently missed to the left. Let's make a bigger adjustment to the right this time. But your power looks pretty good, so let's make only a tiny adjustment there."
python
import torch.optim as optim

# Same setup, just a different class! Adam is often a great starting point.
optimizer = optim.Adam(model.parameters(), lr=0.001)

Industry Standard: When in doubt, start with Adam. It's robust and performs well on a wide variety of problems.


3. The Standard PyTorch Training Loop: The Practice Session 🔄

The Problem: We have our Scoreboard (Loss Function) and our Coach (Optimizer). Now we need to structure the actual practice session. How do we combine these pieces to make the robot take a shot, get feedback, and adjust, over and over again?

The Solution: This is the famous PyTorch Training Loop. It's a simple for loop that iterates through our training data. Inside this loop, a sacred 5-step ritual is performed for each batch of data.

Here is the holy grail, the five steps you will write thousands of times in your career:

  1. Forward Pass: Get a prediction from the model.
    predictions = model(inputs)
  2. Calculate Loss: Use the loss function to see how wrong the prediction was.
    loss = loss_fn(predictions, labels)
  3. Zero Gradients: Crucially, reset the optimizer's memory of past errors.
    optimizer.zero_grad()

    Why? PyTorch accumulates gradients by default. If you don't zero them out, the gradient from the current batch will be added to the gradients from all previous batches, which would be like the coach trying to correct the current shot based on an average of every mistake the robot has ever made. It would be total chaos!

  4. Backward Pass (Backpropagation): Calculate the gradients for every parameter.
    loss.backward()
  5. Update Weights: Tell the optimizer to adjust the parameters based on the gradients it just calculated.
    optimizer.step()

Here is what it looks like in code, assuming you have a dataloader feeding you batches of inputs and labels:

python
# A single "epoch" is one full pass through the entire training dataset.
# We usually train for multiple epochs.

NUM_EPOCHS = 10

for epoch in range(NUM_EPOCHS):
    # Loop over the data loader for training
    for batch in train_dataloader:
        inputs, labels = batch

        # 1. Forward pass
        outputs = model(inputs)

        # 2. Calculate loss
        loss = loss_fn(outputs, labels)

        # 3. Zero the gradients
        optimizer.zero_grad()

        # 4. Backward pass
        loss.backward()

        # 5. Update the weights
        optimizer.step()

    print(f"Epoch {epoch+1}, Loss: {loss.item()}")

That's it! That's the core of training in PyTorch.


4. Model Evaluation: The Championship Game 🏆

The Problem: Our robot has been practicing for hours from the free-throw line. Its loss is super low, and it almost never misses... from that one spot. But what happens if we ask it to shoot from the three-point line, a spot it has never seen before? Will it still perform well? Just because it's good at the training data doesn't mean it's actually a good basketball player. This is the problem of overfitting.

The Solution: We need to evaluate our model on data it has never seen. We typically split our dataset into a training set and a validation set (or test set). The Validation Loop is how we check our model's performance on this unseen data.

The validation loop is similar to the training loop, but with two key differences:

  1. We turn off gradient calculations with torch.no_grad(). We're just evaluating, not learning, so there's no need to calculate gradients. This makes the process faster and uses less memory.
  2. We put the model in evaluation mode with model.eval(). This tells layers like Dropout and BatchNorm (which behave differently during training and testing) to switch to their inference-time behavior.
python
# Set the model to evaluation mode
model.eval()

num_correct = 0
num_samples = 0

# Wrap the loop in the no_grad context manager
with torch.no_grad():
    for batch in validation_dataloader:
        inputs, labels = batch

        # 1. Forward pass (still need predictions)
        outputs = model(inputs)

        # We don't need loss for evaluation, but we can compute it if we want to track it.
        # loss = loss_fn(outputs, labels)

        # Let's calculate a more human-friendly metric: Accuracy
        # Get the class with the highest score
        _, predictions = torch.max(outputs, 1)
        num_samples += labels.size(0)
        num_correct += (predictions == labels).sum().item()

# Switch back to training mode for the next epoch
model.train()

accuracy = 100 * num_correct / num_samples
print(f"Validation Accuracy: {accuracy:.2f}%")

By monitoring your validation accuracy (or another metric), you get a true sense of how well your model is generalizing to new situations. This is the number that truly matters!

Extra Reading & References 📚

Challenge

Challenge: Implement the PyTorch Training Loop

You are tasked with completing a PyTorch training script. A neural network, a dataloader, a loss function, and an optimizer have already been initialized for you.

Your goal is to implement the core logic inside the training loop. For each batch of data provided by the train_dataloader, you must perform the five essential steps of a single training iteration in the correct sequence.

Expected result

Your solution should be a Python script where the comments inside the for loop are replaced with the correct PyTorch code. The five steps must be implemented using the appropriate methods in the correct order.

The core of your solution inside the loop should be equivalent to this:

python
# 1. Forward Pass
pred = model(X)

# 2. Calculate Loss
loss = loss_fn(pred, y)

# 3. Zero Gradients
optimizer.zero_grad()

# 4. Backward Pass
loss.backward()

# 5. Update Weights
optimizer.step()
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.