Note

Click here to download the full example code

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),
nn.ReLU()
)
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
Processing...
Done!
```

## 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.

- Call

## 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)
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 /= size
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.307221 [ 0/60000]
loss: 2.301727 [ 6400/60000]
loss: 2.293826 [12800/60000]
loss: 2.281427 [19200/60000]
loss: 2.280947 [25600/60000]
loss: 2.282351 [32000/60000]
loss: 2.265730 [38400/60000]
loss: 2.277632 [44800/60000]
loss: 2.260041 [51200/60000]
loss: 2.213695 [57600/60000]
Test Error:
Accuracy: 37.0%, Avg loss: 0.035116
Epoch 2
-------------------------------
loss: 2.265179 [ 0/60000]
loss: 2.257184 [ 6400/60000]
loss: 2.236612 [12800/60000]
loss: 2.194381 [19200/60000]
loss: 2.216037 [25600/60000]
loss: 2.230935 [32000/60000]
loss: 2.192703 [38400/60000]
loss: 2.228704 [44800/60000]
loss: 2.191200 [51200/60000]
loss: 2.091365 [57600/60000]
Test Error:
Accuracy: 37.9%, Avg loss: 0.033755
Epoch 3
-------------------------------
loss: 2.220718 [ 0/60000]
loss: 2.198574 [ 6400/60000]
loss: 2.166590 [12800/60000]
loss: 2.072836 [19200/60000]
loss: 2.124839 [25600/60000]
loss: 2.173127 [32000/60000]
loss: 2.086044 [38400/60000]
loss: 2.166099 [44800/60000]
loss: 2.101436 [51200/60000]
loss: 1.932705 [57600/60000]
Test Error:
Accuracy: 38.2%, Avg loss: 0.031995
Epoch 4
-------------------------------
loss: 2.165899 [ 0/60000]
loss: 2.122554 [ 6400/60000]
loss: 2.080557 [12800/60000]
loss: 1.923087 [19200/60000]
loss: 2.013725 [25600/60000]
loss: 2.112495 [32000/60000]
loss: 1.962515 [38400/60000]
loss: 2.097708 [44800/60000]
loss: 2.007544 [51200/60000]
loss: 1.777454 [57600/60000]
Test Error:
Accuracy: 39.6%, Avg loss: 0.030214
Epoch 5
-------------------------------
loss: 2.106806 [ 0/60000]
loss: 2.043889 [ 6400/60000]
loss: 1.992362 [12800/60000]
loss: 1.787888 [19200/60000]
loss: 1.905058 [25600/60000]
loss: 2.050201 [32000/60000]
loss: 1.856685 [38400/60000]
loss: 2.031842 [44800/60000]
loss: 1.926060 [51200/60000]
loss: 1.661872 [57600/60000]
Test Error:
Accuracy: 42.0%, Avg loss: 0.028735
Epoch 6
-------------------------------
loss: 2.043752 [ 0/60000]
loss: 1.970670 [ 6400/60000]
loss: 1.907490 [12800/60000]
loss: 1.684472 [19200/60000]
loss: 1.807296 [25600/60000]
loss: 1.988052 [32000/60000]
loss: 1.773258 [38400/60000]
loss: 1.971488 [44800/60000]
loss: 1.857386 [51200/60000]
loss: 1.580941 [57600/60000]
Test Error:
Accuracy: 43.9%, Avg loss: 0.027557
Epoch 7
-------------------------------
loss: 1.982543 [ 0/60000]
loss: 1.909383 [ 6400/60000]
loss: 1.829998 [12800/60000]
loss: 1.604615 [19200/60000]
loss: 1.725794 [25600/60000]
loss: 1.929796 [32000/60000]
loss: 1.707731 [38400/60000]
loss: 1.921700 [44800/60000]
loss: 1.801901 [51200/60000]
loss: 1.520397 [57600/60000]
Test Error:
Accuracy: 45.0%, Avg loss: 0.026625
Epoch 8
-------------------------------
loss: 1.927654 [ 0/60000]
loss: 1.859316 [ 6400/60000]
loss: 1.763596 [12800/60000]
loss: 1.544053 [19200/60000]
loss: 1.661659 [25600/60000]
loss: 1.879479 [32000/60000]
loss: 1.655556 [38400/60000]
loss: 1.883750 [44800/60000]
loss: 1.755927 [51200/60000]
loss: 1.474720 [57600/60000]
Test Error:
Accuracy: 45.7%, Avg loss: 0.025886
Epoch 9
-------------------------------
loss: 1.879600 [ 0/60000]
loss: 1.818393 [ 6400/60000]
loss: 1.707610 [12800/60000]
loss: 1.496390 [19200/60000]
loss: 1.610458 [25600/60000]
loss: 1.838111 [32000/60000]
loss: 1.614197 [38400/60000]
loss: 1.854321 [44800/60000]
loss: 1.718269 [51200/60000]
loss: 1.437551 [57600/60000]
Test Error:
Accuracy: 46.2%, Avg loss: 0.025300
Epoch 10
-------------------------------
loss: 1.837761 [ 0/60000]
loss: 1.785227 [ 6400/60000]
loss: 1.661100 [12800/60000]
loss: 1.458276 [19200/60000]
loss: 1.570582 [25600/60000]
loss: 1.804275 [32000/60000]
loss: 1.581069 [38400/60000]
loss: 1.831521 [44800/60000]
loss: 1.686258 [51200/60000]
loss: 1.407434 [57600/60000]
Test Error:
Accuracy: 46.7%, Avg loss: 0.024828
Done!
```

## Further Reading¶

**Total running time of the script:** ( 1 minutes 38.727 seconds)