Learn the Basics || Quickstart || Tensors || Datasets & DataLoaders || Transforms || Build Model || Autograd || Optimization || Save & Load Model
Optimizing Model Parameters#Created On: Feb 09, 2021 | Last Updated: Apr 28, 2025 | Last Verified: Nov 05, 2024
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().__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()
0%| | 0.00/26.4M [00:00<?, ?B/s] 0%| | 65.5k/26.4M [00:00<01:12, 362kB/s] 1%| | 229k/26.4M [00:00<00:37, 689kB/s] 3%|▎ | 754k/26.4M [00:00<00:12, 2.13MB/s] 7%|▋ | 1.93M/26.4M [00:00<00:05, 4.18MB/s] 24%|██▍ | 6.29M/26.4M [00:00<00:01, 14.7MB/s] 38%|███▊ | 10.1M/26.4M [00:00<00:00, 17.7MB/s] 54%|█████▎ | 14.2M/26.4M [00:01<00:00, 23.4MB/s] 72%|███████▏ | 19.1M/26.4M [00:01<00:00, 28.0MB/s] 85%|████████▍ | 22.4M/26.4M [00:01<00:00, 26.7MB/s] 100%|██████████| 26.4M/26.4M [00:01<00:00, 19.3MB/s] 0%| | 0.00/29.5k [00:00<?, ?B/s] 100%|██████████| 29.5k/29.5k [00:00<00:00, 328kB/s] 0%| | 0.00/4.42M [00:00<?, ?B/s] 1%|▏ | 65.5k/4.42M [00:00<00:12, 359kB/s] 5%|▌ | 229k/4.42M [00:00<00:06, 677kB/s] 20%|██ | 885k/4.42M [00:00<00:01, 2.01MB/s] 81%|████████ | 3.57M/4.42M [00:00<00:00, 7.03MB/s] 100%|██████████| 4.42M/4.42M [00:00<00:00, 6.04MB/s] 0%| | 0.00/5.15k [00:00<?, ?B/s] 100%|██████████| 5.15k/5.15k [00:00<00:00, 53.2MB/s]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)
Number of Epochs - the number of 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 = 5Optimization 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.
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.
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.
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.
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) # Set the model to training mode - important for batch normalization and dropout layers # Unnecessary in this situation but added for best practices model.train() for batch, (X, y) in enumerate(dataloader): # Compute prediction and loss pred = model(X) loss = loss_fn(pred, y) # Backpropagation loss.backward() optimizer.step() optimizer.zero_grad() if batch % 100 == 0: loss, current = loss.item(), batch * batch_size + len(X) print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]") def test_loop(dataloader, model, loss_fn): # Set the model to evaluation mode - important for batch normalization and dropout layers # Unnecessary in this situation but added for best practices model.eval() size = len(dataloader.dataset) num_batches = len(dataloader) test_loss, correct = 0, 0 # Evaluating the model with torch.no_grad() ensures that no gradients are computed during test mode # also serves to reduce unnecessary gradient computations and memory usage for tensors with requires_grad=True 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.
Epoch 1 ------------------------------- loss: 2.301304 [ 64/60000] loss: 2.290432 [ 6464/60000] loss: 2.271465 [12864/60000] loss: 2.263968 [19264/60000] loss: 2.244781 [25664/60000] loss: 2.219276 [32064/60000] loss: 2.232433 [38464/60000] loss: 2.192297 [44864/60000] loss: 2.193498 [51264/60000] loss: 2.165598 [57664/60000] Test Error: Accuracy: 43.6%, Avg loss: 2.153058 Epoch 2 ------------------------------- loss: 2.162442 [ 64/60000] loss: 2.155694 [ 6464/60000] loss: 2.097841 [12864/60000] loss: 2.112610 [19264/60000] loss: 2.059788 [25664/60000] loss: 2.005090 [32064/60000] loss: 2.037802 [38464/60000] loss: 1.952445 [44864/60000] loss: 1.960213 [51264/60000] loss: 1.893358 [57664/60000] Test Error: Accuracy: 61.2%, Avg loss: 1.883813 Epoch 3 ------------------------------- loss: 1.918046 [ 64/60000] loss: 1.884855 [ 6464/60000] loss: 1.768483 [12864/60000] loss: 1.804412 [19264/60000] loss: 1.690272 [25664/60000] loss: 1.651173 [32064/60000] loss: 1.671892 [38464/60000] loss: 1.568318 [44864/60000] loss: 1.592192 [51264/60000] loss: 1.489873 [57664/60000] Test Error: Accuracy: 63.3%, Avg loss: 1.503957 Epoch 4 ------------------------------- loss: 1.576854 [ 64/60000] loss: 1.532818 [ 6464/60000] loss: 1.385761 [12864/60000] loss: 1.448331 [19264/60000] loss: 1.329727 [25664/60000] loss: 1.333927 [32064/60000] loss: 1.348226 [38464/60000] loss: 1.271179 [44864/60000] loss: 1.308115 [51264/60000] loss: 1.212155 [57664/60000] Test Error: Accuracy: 64.2%, Avg loss: 1.235920 Epoch 5 ------------------------------- loss: 1.320537 [ 64/60000] loss: 1.293182 [ 6464/60000] loss: 1.130487 [12864/60000] loss: 1.227129 [19264/60000] loss: 1.103541 [25664/60000] loss: 1.134883 [32064/60000] loss: 1.159852 [38464/60000] loss: 1.095598 [44864/60000] loss: 1.134599 [51264/60000] loss: 1.059472 [57664/60000] Test Error: Accuracy: 65.1%, Avg loss: 1.075878 Epoch 6 ------------------------------- loss: 1.152150 [ 64/60000] loss: 1.148260 [ 6464/60000] loss: 0.968152 [12864/60000] loss: 1.094830 [19264/60000] loss: 0.970273 [25664/60000] loss: 1.005118 [32064/60000] loss: 1.047229 [38464/60000] loss: 0.986924 [44864/60000] loss: 1.021950 [51264/60000] loss: 0.966211 [57664/60000] Test Error: Accuracy: 66.4%, Avg loss: 0.974223 Epoch 7 ------------------------------- loss: 1.035344 [ 64/60000] loss: 1.055975 [ 6464/60000] loss: 0.857661 [12864/60000] loss: 1.008065 [19264/60000] loss: 0.888320 [25664/60000] loss: 0.914003 [32064/60000] loss: 0.974111 [38464/60000] loss: 0.916054 [44864/60000] loss: 0.942857 [51264/60000] loss: 0.902876 [57664/60000] Test Error: Accuracy: 67.5%, Avg loss: 0.904448 Epoch 8 ------------------------------- loss: 0.948809 [ 64/60000] loss: 0.991737 [ 6464/60000] loss: 0.778084 [12864/60000] loss: 0.946198 [19264/60000] loss: 0.833845 [25664/60000] loss: 0.846769 [32064/60000] loss: 0.922538 [38464/60000] loss: 0.867979 [44864/60000] loss: 0.885049 [51264/60000] loss: 0.856243 [57664/60000] Test Error: Accuracy: 68.8%, Avg loss: 0.853540 Epoch 9 ------------------------------- loss: 0.881676 [ 64/60000] loss: 0.943043 [ 6464/60000] loss: 0.718092 [12864/60000] loss: 0.899703 [19264/60000] loss: 0.794802 [25664/60000] loss: 0.795869 [32064/60000] loss: 0.883208 [38464/60000] loss: 0.834239 [44864/60000] loss: 0.841301 [51264/60000] loss: 0.819950 [57664/60000] Test Error: Accuracy: 70.3%, Avg loss: 0.814597 Epoch 10 ------------------------------- loss: 0.828120 [ 64/60000] loss: 0.903371 [ 6464/60000] loss: 0.671301 [12864/60000] loss: 0.863500 [19264/60000] loss: 0.765080 [25664/60000] loss: 0.756682 [32064/60000] loss: 0.851471 [38464/60000] loss: 0.809364 [44864/60000] loss: 0.807112 [51264/60000] loss: 0.790412 [57664/60000] Test Error: Accuracy: 71.5%, Avg loss: 0.783472 Done!Further Reading#
Total running time of the script: (1 minutes 14.386 seconds)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4