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 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
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()
```

```
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
0%| | 0/26421880 [00:00<?, ?it/s]
0%| | 32768/26421880 [00:00<01:26, 305373.07it/s]
0%| | 65536/26421880 [00:00<01:27, 299668.11it/s]
0%| | 131072/26421880 [00:00<01:00, 434171.77it/s]
1%| | 229376/26421880 [00:00<00:42, 614436.99it/s]
2%|1 | 491520/26421880 [00:00<00:20, 1248562.07it/s]
4%|3 | 950272/26421880 [00:00<00:11, 2232273.58it/s]
7%|7 | 1933312/26421880 [00:00<00:05, 4406424.97it/s]
15%|#4 | 3833856/26421880 [00:00<00:02, 8475324.49it/s]
26%|##6 | 6946816/26421880 [00:00<00:01, 14605705.32it/s]
37%|###6 | 9764864/26421880 [00:01<00:00, 17908628.21it/s]
49%|####8 | 12877824/26421880 [00:01<00:00, 20989210.61it/s]
61%|###### | 16023552/26421880 [00:01<00:00, 23213961.55it/s]
72%|#######2 | 19136512/26421880 [00:01<00:00, 24783594.57it/s]
84%|########4 | 22249472/26421880 [00:01<00:00, 25803438.12it/s]
96%|#########5| 25362432/26421880 [00:01<00:00, 26511364.76it/s]
100%|##########| 26421880/26421880 [00:01<00:00, 15868945.10it/s]
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
0%| | 0/29515 [00:00<?, ?it/s]
100%|##########| 29515/29515 [00:00<00:00, 267469.14it/s]
100%|##########| 29515/29515 [00:00<00:00, 265938.45it/s]
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
0%| | 0/4422102 [00:00<?, ?it/s]
1%| | 32768/4422102 [00:00<00:14, 298442.96it/s]
1%|1 | 65536/4422102 [00:00<00:14, 297025.91it/s]
3%|2 | 131072/4422102 [00:00<00:09, 432074.74it/s]
5%|5 | 229376/4422102 [00:00<00:06, 612642.45it/s]
11%|#1 | 491520/4422102 [00:00<00:03, 1246000.79it/s]
21%|##1 | 950272/4422102 [00:00<00:01, 2231914.81it/s]
44%|####3 | 1933312/4422102 [00:00<00:00, 4405814.97it/s]
85%|########5 | 3768320/4422102 [00:00<00:00, 8283061.60it/s]
100%|##########| 4422102/4422102 [00:00<00:00, 4982637.83it/s]
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
0%| | 0/5148 [00:00<?, ?it/s]
100%|##########| 5148/5148 [00:00<00:00, 24991061.33it/s]
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.backward()`

. 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!")
```

```
Epoch 1
-------------------------------
loss: 2.302558 [ 0/60000]
loss: 2.290977 [ 6400/60000]
loss: 2.264834 [12800/60000]
loss: 2.264973 [19200/60000]
loss: 2.259708 [25600/60000]
loss: 2.212368 [32000/60000]
loss: 2.230089 [38400/60000]
loss: 2.182537 [44800/60000]
loss: 2.190904 [51200/60000]
loss: 2.156970 [57600/60000]
Test Error:
Accuracy: 41.5%, Avg loss: 2.149055
Epoch 2
-------------------------------
loss: 2.162335 [ 0/60000]
loss: 2.152007 [ 6400/60000]
loss: 2.086072 [12800/60000]
loss: 2.109022 [19200/60000]
loss: 2.077324 [25600/60000]
loss: 1.994249 [32000/60000]
loss: 2.037649 [38400/60000]
loss: 1.942874 [44800/60000]
loss: 1.961001 [51200/60000]
loss: 1.886463 [57600/60000]
Test Error:
Accuracy: 58.8%, Avg loss: 1.883057
Epoch 3
-------------------------------
loss: 1.920987 [ 0/60000]
loss: 1.887682 [ 6400/60000]
loss: 1.762417 [12800/60000]
loss: 1.812568 [19200/60000]
loss: 1.727483 [25600/60000]
loss: 1.653746 [32000/60000]
loss: 1.692851 [38400/60000]
loss: 1.575782 [44800/60000]
loss: 1.612807 [51200/60000]
loss: 1.507453 [57600/60000]
Test Error:
Accuracy: 61.7%, Avg loss: 1.523113
Epoch 4
-------------------------------
loss: 1.591845 [ 0/60000]
loss: 1.556843 [ 6400/60000]
loss: 1.399432 [12800/60000]
loss: 1.481499 [19200/60000]
loss: 1.377016 [25600/60000]
loss: 1.352708 [32000/60000]
loss: 1.379682 [38400/60000]
loss: 1.287053 [44800/60000]
loss: 1.328695 [51200/60000]
loss: 1.230411 [57600/60000]
Test Error:
Accuracy: 63.0%, Avg loss: 1.256233
Epoch 5
-------------------------------
loss: 1.331043 [ 0/60000]
loss: 1.316590 [ 6400/60000]
loss: 1.145932 [12800/60000]
loss: 1.260213 [19200/60000]
loss: 1.139981 [25600/60000]
loss: 1.155192 [32000/60000]
loss: 1.183158 [38400/60000]
loss: 1.107134 [44800/60000]
loss: 1.150611 [51200/60000]
loss: 1.065710 [57600/60000]
Test Error:
Accuracy: 64.1%, Avg loss: 1.088427
Epoch 6
-------------------------------
loss: 1.155968 [ 0/60000]
loss: 1.162620 [ 6400/60000]
loss: 0.977938 [12800/60000]
loss: 1.119096 [19200/60000]
loss: 0.995007 [25600/60000]
loss: 1.023149 [32000/60000]
loss: 1.061538 [38400/60000]
loss: 0.992993 [44800/60000]
loss: 1.035918 [51200/60000]
loss: 0.962663 [57600/60000]
Test Error:
Accuracy: 65.2%, Avg loss: 0.980338
Epoch 7
-------------------------------
loss: 1.034984 [ 0/60000]
loss: 1.063037 [ 6400/60000]
loss: 0.863486 [12800/60000]
loss: 1.024950 [19200/60000]
loss: 0.905495 [25600/60000]
loss: 0.931241 [32000/60000]
loss: 0.982671 [38400/60000]
loss: 0.919573 [44800/60000]
loss: 0.957403 [51200/60000]
loss: 0.894356 [57600/60000]
Test Error:
Accuracy: 66.6%, Avg loss: 0.907435
Epoch 8
-------------------------------
loss: 0.947136 [ 0/60000]
loss: 0.994560 [ 6400/60000]
loss: 0.782589 [12800/60000]
loss: 0.958973 [19200/60000]
loss: 0.847170 [25600/60000]
loss: 0.865170 [32000/60000]
loss: 0.928014 [38400/60000]
loss: 0.871206 [44800/60000]
loss: 0.901558 [51200/60000]
loss: 0.846088 [57600/60000]
Test Error:
Accuracy: 67.7%, Avg loss: 0.855562
Epoch 9
-------------------------------
loss: 0.880251 [ 0/60000]
loss: 0.943971 [ 6400/60000]
loss: 0.722824 [12800/60000]
loss: 0.910332 [19200/60000]
loss: 0.806514 [25600/60000]
loss: 0.815856 [32000/60000]
loss: 0.886954 [38400/60000]
loss: 0.837633 [44800/60000]
loss: 0.860024 [51200/60000]
loss: 0.809682 [57600/60000]
Test Error:
Accuracy: 69.0%, Avg loss: 0.816550
Epoch 10
-------------------------------
loss: 0.827405 [ 0/60000]
loss: 0.903809 [ 6400/60000]
loss: 0.676605 [12800/60000]
loss: 0.872933 [19200/60000]
loss: 0.776132 [25600/60000]
loss: 0.777970 [32000/60000]
loss: 0.853874 [38400/60000]
loss: 0.812989 [44800/60000]
loss: 0.827992 [51200/60000]
loss: 0.780654 [57600/60000]
Test Error:
Accuracy: 70.2%, Avg loss: 0.785589
Done!
```

## Further Reading¶

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