Shortcuts

Learn the Basics || Quickstart || Tensors || Datasets & DataLoaders || Transforms || Build Model || Autograd || Optimization || Save & Load Model

Optimizing Model Parameters

Now that we have a model and data it’s time to train, validate and test our model by optimizing its parameters on our data. Training a model is an iterative process; in each iteration (called an epoch) the model makes a guess about the output, calculates the error in its guess (loss), collects the derivatives of the error with respect to its parameters (as we saw in the previous section), and optimizes these parameters using gradient descent. For a more detailed walkthrough of this process, check out this video on backpropagation from 3Blue1Brown.

Prerequisite Code

We load the code from the previous sections on Datasets & DataLoaders and Build Model.

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda

training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor()
)

test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor()
)

train_dataloader = DataLoader(training_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)

class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

model = NeuralNetwork()

Out:

Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to data/FashionMNIST/raw/train-images-idx3-ubyte.gz
Extracting data/FashionMNIST/raw/train-images-idx3-ubyte.gz to data/FashionMNIST/raw

Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw/train-labels-idx1-ubyte.gz
Extracting data/FashionMNIST/raw/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw

Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz
Extracting data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw

Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz
Extracting data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw

Hyperparameters

Hyperparameters are adjustable parameters that let you control the model optimization process. Different hyperparameter values can impact model training and convergence rates (read more about hyperparameter tuning)

We define the following hyperparameters for training:
  • Number of Epochs - the number times to iterate over the dataset
  • Batch Size - the number of data samples propagated through the network before the parameters are updated
  • Learning Rate - how much to update models parameters at each batch/epoch. Smaller values yield slow learning speed, while large values may result in unpredictable behavior during training.
learning_rate = 1e-3
batch_size = 64
epochs = 5

Optimization Loop

Once we set our hyperparameters, we can then train and optimize our model with an optimization loop. Each iteration of the optimization loop is called an epoch.

Each epoch consists of two main parts:
  • The Train Loop - iterate over the training dataset and try to converge to optimal parameters.
  • The Validation/Test Loop - iterate over the test dataset to check if model performance is improving.

Let’s briefly familiarize ourselves with some of the concepts used in the training loop. Jump ahead to see the Full Implementation of the optimization loop.

Loss Function

When presented with some training data, our untrained network is likely not to give the correct answer. Loss function measures the degree of dissimilarity of obtained result to the target value, and it is the loss function that we want to minimize during training. To calculate the loss we make a prediction using the inputs of our given data sample and compare it against the true data label value.

Common loss functions include nn.MSELoss (Mean Square Error) for regression tasks, and nn.NLLLoss (Negative Log Likelihood) for classification. nn.CrossEntropyLoss combines nn.LogSoftmax and nn.NLLLoss.

We pass our model’s output logits to nn.CrossEntropyLoss, which will normalize the logits and compute the prediction error.

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

Optimizer

Optimization is the process of adjusting model parameters to reduce model error in each training step. Optimization algorithms define how this process is performed (in this example we use Stochastic Gradient Descent). All optimization logic is encapsulated in the optimizer object. Here, we use the SGD optimizer; additionally, there are many different optimizers available in PyTorch such as ADAM and RMSProp, that work better for different kinds of models and data.

We initialize the optimizer by registering the model’s parameters that need to be trained, and passing in the learning rate hyperparameter.

optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
Inside the training loop, optimization happens in three steps:
  • Call optimizer.zero_grad() to reset the gradients of model parameters. Gradients by default add up; to prevent double-counting, we explicitly zero them at each iteration.
  • Backpropagate the prediction loss with a call to loss.backwards(). PyTorch deposits the gradients of the loss w.r.t. each parameter.
  • Once we have our gradients, we call optimizer.step() to adjust the parameters by the gradients collected in the backward pass.

Full Implementation

We define train_loop that loops over our optimization code, and test_loop that evaluates the model’s performance against our test data.

def train_loop(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    for batch, (X, y) in enumerate(dataloader):
        # Compute prediction and loss
        pred = model(X)
        loss = loss_fn(pred, y)

        # Backpropagation
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch % 100 == 0:
            loss, current = loss.item(), batch * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")


def test_loop(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss, correct = 0, 0

    with torch.no_grad():
        for X, y in dataloader:
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()

    test_loss /= num_batches
    correct /= size
    print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")

We initialize the loss function and optimizer, and pass it to train_loop and test_loop. Feel free to increase the number of epochs to track the model’s improving performance.

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

epochs = 10
for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train_loop(train_dataloader, model, loss_fn, optimizer)
    test_loop(test_dataloader, model, loss_fn)
print("Done!")

Out:

Epoch 1
-------------------------------
loss: 2.315242  [    0/60000]
loss: 2.309011  [ 6400/60000]
loss: 2.280897  [12800/60000]
loss: 2.276091  [19200/60000]
loss: 2.257991  [25600/60000]
loss: 2.217116  [32000/60000]
loss: 2.233580  [38400/60000]
loss: 2.189297  [44800/60000]
loss: 2.196243  [51200/60000]
loss: 2.160221  [57600/60000]
Test Error:
 Accuracy: 38.6%, Avg loss: 2.151922

Epoch 2
-------------------------------
loss: 2.166833  [    0/60000]
loss: 2.164620  [ 6400/60000]
loss: 2.092782  [12800/60000]
loss: 2.115065  [19200/60000]
loss: 2.061288  [25600/60000]
loss: 1.989117  [32000/60000]
loss: 2.037191  [38400/60000]
loss: 1.941108  [44800/60000]
loss: 1.960467  [51200/60000]
loss: 1.889662  [57600/60000]
Test Error:
 Accuracy: 51.0%, Avg loss: 1.876334

Epoch 3
-------------------------------
loss: 1.918218  [    0/60000]
loss: 1.894371  [ 6400/60000]
loss: 1.756171  [12800/60000]
loss: 1.805379  [19200/60000]
loss: 1.702752  [25600/60000]
loss: 1.645934  [32000/60000]
loss: 1.692133  [38400/60000]
loss: 1.573300  [44800/60000]
loss: 1.612845  [51200/60000]
loss: 1.516876  [57600/60000]
Test Error:
 Accuracy: 58.8%, Avg loss: 1.516586

Epoch 4
-------------------------------
loss: 1.590301  [    0/60000]
loss: 1.562892  [ 6400/60000]
loss: 1.390789  [12800/60000]
loss: 1.472315  [19200/60000]
loss: 1.361219  [25600/60000]
loss: 1.349418  [32000/60000]
loss: 1.384912  [38400/60000]
loss: 1.290289  [44800/60000]
loss: 1.330013  [51200/60000]
loss: 1.241136  [57600/60000]
Test Error:
 Accuracy: 63.0%, Avg loss: 1.255984

Epoch 5
-------------------------------
loss: 1.332731  [    0/60000]
loss: 1.326511  [ 6400/60000]
loss: 1.140927  [12800/60000]
loss: 1.253949  [19200/60000]
loss: 1.133963  [25600/60000]
loss: 1.153342  [32000/60000]
loss: 1.190248  [38400/60000]
loss: 1.112329  [44800/60000]
loss: 1.151269  [51200/60000]
loss: 1.074143  [57600/60000]
Test Error:
 Accuracy: 64.6%, Avg loss: 1.091156

Epoch 6
-------------------------------
loss: 1.159728  [    0/60000]
loss: 1.173182  [ 6400/60000]
loss: 0.973350  [12800/60000]
loss: 1.114465  [19200/60000]
loss: 0.991516  [25600/60000]
loss: 1.019727  [32000/60000]
loss: 1.067822  [38400/60000]
loss: 0.997596  [44800/60000]
loss: 1.035360  [51200/60000]
loss: 0.967558  [57600/60000]
Test Error:
 Accuracy: 65.8%, Avg loss: 0.983743

Epoch 7
-------------------------------
loss: 1.039492  [    0/60000]
loss: 1.072310  [ 6400/60000]
loss: 0.858043  [12800/60000]
loss: 1.020954  [19200/60000]
loss: 0.901897  [25600/60000]
loss: 0.925223  [32000/60000]
loss: 0.987949  [38400/60000]
loss: 0.922006  [44800/60000]
loss: 0.955378  [51200/60000]
loss: 0.896546  [57600/60000]
Test Error:
 Accuracy: 66.9%, Avg loss: 0.910463

Epoch 8
-------------------------------
loss: 0.951228  [    0/60000]
loss: 1.002077  [ 6400/60000]
loss: 0.775843  [12800/60000]
loss: 0.955142  [19200/60000]
loss: 0.842809  [25600/60000]
loss: 0.856100  [32000/60000]
loss: 0.932417  [38400/60000]
loss: 0.871075  [44800/60000]
loss: 0.897948  [51200/60000]
loss: 0.846308  [57600/60000]
Test Error:
 Accuracy: 68.2%, Avg loss: 0.857796

Epoch 9
-------------------------------
loss: 0.883850  [    0/60000]
loss: 0.949722  [ 6400/60000]
loss: 0.714809  [12800/60000]
loss: 0.906644  [19200/60000]
loss: 0.801228  [25600/60000]
loss: 0.804110  [32000/60000]
loss: 0.890989  [38400/60000]
loss: 0.834966  [44800/60000]
loss: 0.854721  [51200/60000]
loss: 0.808806  [57600/60000]
Test Error:
 Accuracy: 69.5%, Avg loss: 0.818006

Epoch 10
-------------------------------
loss: 0.830228  [    0/60000]
loss: 0.908175  [ 6400/60000]
loss: 0.667652  [12800/60000]
loss: 0.869883  [19200/60000]
loss: 0.769949  [25600/60000]
loss: 0.763918  [32000/60000]
loss: 0.857782  [38400/60000]
loss: 0.807917  [44800/60000]
loss: 0.820977  [51200/60000]
loss: 0.779136  [57600/60000]
Test Error:
 Accuracy: 70.7%, Avg loss: 0.786504

Done!

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources