CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
pytorch

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: pytorch/tutorials
Path: blob/main/beginner_source/basics/optimization_tutorial.py
Views: 713
1
"""
2
`Learn the Basics <intro.html>`_ ||
3
`Quickstart <quickstart_tutorial.html>`_ ||
4
`Tensors <tensorqs_tutorial.html>`_ ||
5
`Datasets & DataLoaders <data_tutorial.html>`_ ||
6
`Transforms <transforms_tutorial.html>`_ ||
7
`Build Model <buildmodel_tutorial.html>`_ ||
8
`Autograd <autogradqs_tutorial.html>`_ ||
9
**Optimization** ||
10
`Save & Load Model <saveloadrun_tutorial.html>`_
11
12
Optimizing Model Parameters
13
===========================
14
15
Now that we have a model and data it's time to train, validate and test our model by optimizing its parameters on
16
our data. Training a model is an iterative process; in each iteration the model makes a guess about the output, calculates
17
the error in its guess (*loss*), collects the derivatives of the error with respect to its parameters (as we saw in
18
the `previous section <autograd_tutorial.html>`_), and **optimizes** these parameters using gradient descent. For a more
19
detailed walkthrough of this process, check out this video on `backpropagation from 3Blue1Brown <https://www.youtube.com/watch?v=tIeHLnjs5U8>`__.
20
21
Prerequisite Code
22
-----------------
23
We load the code from the previous sections on `Datasets & DataLoaders <data_tutorial.html>`_
24
and `Build Model <buildmodel_tutorial.html>`_.
25
"""
26
27
import torch
28
from torch import nn
29
from torch.utils.data import DataLoader
30
from torchvision import datasets
31
from torchvision.transforms import ToTensor
32
33
training_data = datasets.FashionMNIST(
34
root="data",
35
train=True,
36
download=True,
37
transform=ToTensor()
38
)
39
40
test_data = datasets.FashionMNIST(
41
root="data",
42
train=False,
43
download=True,
44
transform=ToTensor()
45
)
46
47
train_dataloader = DataLoader(training_data, batch_size=64)
48
test_dataloader = DataLoader(test_data, batch_size=64)
49
50
class NeuralNetwork(nn.Module):
51
def __init__(self):
52
super().__init__()
53
self.flatten = nn.Flatten()
54
self.linear_relu_stack = nn.Sequential(
55
nn.Linear(28*28, 512),
56
nn.ReLU(),
57
nn.Linear(512, 512),
58
nn.ReLU(),
59
nn.Linear(512, 10),
60
)
61
62
def forward(self, x):
63
x = self.flatten(x)
64
logits = self.linear_relu_stack(x)
65
return logits
66
67
model = NeuralNetwork()
68
69
70
##############################################
71
# Hyperparameters
72
# -----------------
73
#
74
# Hyperparameters are adjustable parameters that let you control the model optimization process.
75
# Different hyperparameter values can impact model training and convergence rates
76
# (`read more <https://pytorch.org/tutorials/beginner/hyperparameter_tuning_tutorial.html>`__ about hyperparameter tuning)
77
#
78
# We define the following hyperparameters for training:
79
# - **Number of Epochs** - the number times to iterate over the dataset
80
# - **Batch Size** - the number of data samples propagated through the network before the parameters are updated
81
# - **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.
82
#
83
84
learning_rate = 1e-3
85
batch_size = 64
86
epochs = 5
87
88
89
90
#####################################
91
# Optimization Loop
92
# -----------------
93
#
94
# Once we set our hyperparameters, we can then train and optimize our model with an optimization loop. Each
95
# iteration of the optimization loop is called an **epoch**.
96
#
97
# Each epoch consists of two main parts:
98
# - **The Train Loop** - iterate over the training dataset and try to converge to optimal parameters.
99
# - **The Validation/Test Loop** - iterate over the test dataset to check if model performance is improving.
100
#
101
# Let's briefly familiarize ourselves with some of the concepts used in the training loop. Jump ahead to
102
# see the :ref:`full-impl-label` of the optimization loop.
103
#
104
# Loss Function
105
# ~~~~~~~~~~~~~~~~~
106
#
107
# When presented with some training data, our untrained network is likely not to give the correct
108
# answer. **Loss function** measures the degree of dissimilarity of obtained result to the target value,
109
# and it is the loss function that we want to minimize during training. To calculate the loss we make a
110
# prediction using the inputs of our given data sample and compare it against the true data label value.
111
#
112
# Common loss functions include `nn.MSELoss <https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html#torch.nn.MSELoss>`_ (Mean Square Error) for regression tasks, and
113
# `nn.NLLLoss <https://pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html#torch.nn.NLLLoss>`_ (Negative Log Likelihood) for classification.
114
# `nn.CrossEntropyLoss <https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html#torch.nn.CrossEntropyLoss>`_ combines ``nn.LogSoftmax`` and ``nn.NLLLoss``.
115
#
116
# We pass our model's output logits to ``nn.CrossEntropyLoss``, which will normalize the logits and compute the prediction error.
117
118
# Initialize the loss function
119
loss_fn = nn.CrossEntropyLoss()
120
121
122
123
#####################################
124
# Optimizer
125
# ~~~~~~~~~~~~~~~~~
126
#
127
# 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).
128
# All optimization logic is encapsulated in the ``optimizer`` object. Here, we use the SGD optimizer; additionally, there are many `different optimizers <https://pytorch.org/docs/stable/optim.html>`_
129
# available in PyTorch such as ADAM and RMSProp, that work better for different kinds of models and data.
130
#
131
# We initialize the optimizer by registering the model's parameters that need to be trained, and passing in the learning rate hyperparameter.
132
133
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
134
135
#####################################
136
# Inside the training loop, optimization happens in three steps:
137
# * 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.
138
# * Backpropagate the prediction loss with a call to ``loss.backward()``. PyTorch deposits the gradients of the loss w.r.t. each parameter.
139
# * Once we have our gradients, we call ``optimizer.step()`` to adjust the parameters by the gradients collected in the backward pass.
140
141
142
########################################
143
# .. _full-impl-label:
144
#
145
# Full Implementation
146
# -----------------------
147
# We define ``train_loop`` that loops over our optimization code, and ``test_loop`` that
148
# evaluates the model's performance against our test data.
149
150
def train_loop(dataloader, model, loss_fn, optimizer):
151
size = len(dataloader.dataset)
152
# Set the model to training mode - important for batch normalization and dropout layers
153
# Unnecessary in this situation but added for best practices
154
model.train()
155
for batch, (X, y) in enumerate(dataloader):
156
# Compute prediction and loss
157
pred = model(X)
158
loss = loss_fn(pred, y)
159
160
# Backpropagation
161
loss.backward()
162
optimizer.step()
163
optimizer.zero_grad()
164
165
if batch % 100 == 0:
166
loss, current = loss.item(), batch * batch_size + len(X)
167
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
168
169
170
def test_loop(dataloader, model, loss_fn):
171
# Set the model to evaluation mode - important for batch normalization and dropout layers
172
# Unnecessary in this situation but added for best practices
173
model.eval()
174
size = len(dataloader.dataset)
175
num_batches = len(dataloader)
176
test_loss, correct = 0, 0
177
178
# Evaluating the model with torch.no_grad() ensures that no gradients are computed during test mode
179
# also serves to reduce unnecessary gradient computations and memory usage for tensors with requires_grad=True
180
with torch.no_grad():
181
for X, y in dataloader:
182
pred = model(X)
183
test_loss += loss_fn(pred, y).item()
184
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
185
186
test_loss /= num_batches
187
correct /= size
188
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
189
190
191
########################################
192
# We initialize the loss function and optimizer, and pass it to ``train_loop`` and ``test_loop``.
193
# Feel free to increase the number of epochs to track the model's improving performance.
194
195
loss_fn = nn.CrossEntropyLoss()
196
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
197
198
epochs = 10
199
for t in range(epochs):
200
print(f"Epoch {t+1}\n-------------------------------")
201
train_loop(train_dataloader, model, loss_fn, optimizer)
202
test_loop(test_dataloader, model, loss_fn)
203
print("Done!")
204
205
206
207
#################################################################
208
# Further Reading
209
# -----------------------
210
# - `Loss Functions <https://pytorch.org/docs/stable/nn.html#loss-functions>`_
211
# - `torch.optim <https://pytorch.org/docs/stable/optim.html>`_
212
# - `Warmstart Training a Model <https://pytorch.org/tutorials/recipes/recipes/warmstarting_model_using_parameters_from_a_different_model.html>`_
213
#
214
215