Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rasbt
GitHub Repository: rasbt/machine-learning-book
Path: blob/main/ch13/ch13_part4_ignite.py
1245 views
1
# coding: utf-8
2
3
4
import sys
5
from python_environment_check import check_packages
6
import torch
7
import torch.nn as nn
8
from torch.utils.data import DataLoader
9
from torchvision.datasets import MNIST
10
from torchvision import transforms
11
from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator
12
from ignite.metrics import Accuracy, Loss
13
from ignite.handlers import Checkpoint, DiskSaver
14
from ignite.contrib.handlers import TensorboardLogger, global_step_from_engine
15
16
17
18
19
20
21
# # Machine Learning with PyTorch and Scikit-Learn
22
# # -- Code Examples
23
24
# ## Package version checks
25
26
# Add folder to path in order to load from the check_packages.py script:
27
28
29
30
sys.path.insert(0, '..')
31
32
33
# Check recommended package versions:
34
35
36
37
38
39
d = {
40
'numpy': '1.21.2',
41
'matplotlib': '3.4.3',
42
'sklearn': '1.0',
43
}
44
check_packages(d)
45
46
47
# # Chapter 13: Going Deeper -- the Mechanics of PyTorch
48
49
# **Big thanks and credit to Victor Fomin for creating and helping with the original draft of this section!**
50
51
# ## A short introduction to PyTorch-Ignite (Online Bonus Content)
52
53
# In this section, we will explore PyTorch-Ignite, a library from the PyTorch ecosystem to help with training and evaluating neural networks in PyTorch flexibly and transparently.
54
#
55
#
56
# **Projects using PyTorch-Ignite**
57
#
58
#
59
# There is a list of research papers with code, blog articles, tutorials, toolkits, and other projects that use PyTorch-Ignite. Notable projects include
60
# - Medical Open Network for AI (MONAI) (https://monai.io)
61
# - Conversational AI with Transfer Learning (https://github.com/huggingface/transfer-learning-conv-ai)
62
# If you are interested in more projects using PyTorch-Ignite, please take a look at the detailed project list here: https://github.com/pytorch/ignite#projects-using-ignite
63
#
64
#
65
66
# ---
67
#
68
# As we saw in previous sections, PyTorch training code usually contains two nested for-loops, one iterating over epochs and one iterating over dataset batches. In addition, we evaluate the model on the training and validation set to track the performance during training. In general, we also would like to create training checkpoints (to resume from one in case of an accidental failure); save the best model; use an experiment tracking system to visualize metrics, predictions, and so forth; and perform other basic tasks. These are the kinds of things that PyTorch-Ignite easily handles for the user while keeping PyTorch-like flexibility. In this sense, PyTorch-Ignite aims to simplify the model training process while promoting best practices.
69
#
70
# In a few words, PyTorch-Ignite provides
71
# - An extremely simple engine and event system (training loop abstraction)
72
# - Out-of-the-box metrics to easily evaluate models
73
# - Built-in handlers to compose training pipelines, save artifacts, and log parameters and metrics
74
# - Distributed training support
75
#
76
# Additional benefits of using PyTorch-Ignite are
77
# - Less code than pure PyTorch while ensuring maximum control and simplicity
78
# - More modular code
79
# In this section, we will build and train again a classifier for the MNIST dataset that we worked with in the previous section.
80
#
81
82
# ---
83
#
84
# **Installing PyTorch-Ignite**
85
#
86
# The code in the following subsections is based on PyTorch-Ignite version 0.4.6. PyTorch-Ignite can be installed via pip or conda, depending on your preference. For instance, the command for installing PyTorch ignite via pip is as follows:
87
#
88
# pip install pytorch-ignite
89
#
90
# Below, you can find the command for installing PyTorch-Ignite via conda:
91
#
92
# conda install ignite -c pytorch
93
#
94
# For the latest information on installing PyTorch-Ignite, please visit the official documentation at https://pytorch.org/ignite/#installation.
95
96
# ### Setting up the PyTorch model
97
98
# First, to set the stage, we will repeat Steps 1, 2, and 3 from the section *Project two - classifying MNIST handwritten digits with minor restructuring*. We define the model, training, and validation datasets, optimizer, and loss function:
99
100
101
102
103
104
105
image_path = './'
106
torch.manual_seed(1)
107
108
transform = transforms.Compose([
109
transforms.ToTensor()
110
])
111
112
113
mnist_train_dataset = MNIST(
114
root=image_path,
115
train=True,
116
transform=transform,
117
download=True
118
)
119
120
mnist_val_dataset = MNIST(
121
root=image_path,
122
train=False,
123
transform=transform,
124
download=False
125
)
126
127
batch_size = 64
128
train_loader = DataLoader(
129
mnist_train_dataset, batch_size, shuffle=True
130
)
131
132
val_loader = DataLoader(
133
mnist_val_dataset, batch_size, shuffle=False
134
)
135
136
137
def get_model(image_shape=(1, 28, 28), hidden_units=(32, 16)):
138
input_size = image_shape[0] * image_shape[1] * image_shape[2]
139
all_layers = [nn.Flatten()]
140
for hidden_unit in hidden_units:
141
layer = nn.Linear(input_size, hidden_unit)
142
all_layers.append(layer)
143
all_layers.append(nn.ReLU())
144
input_size = hidden_unit
145
146
all_layers.append(nn.Linear(hidden_units[-1], 10))
147
all_layers.append(nn.Softmax(dim=1))
148
model = nn.Sequential(*all_layers)
149
return model
150
151
152
device = "cuda" if torch.cuda.is_available() else "cpu"
153
154
model = get_model().to(device)
155
loss_fn = nn.CrossEntropyLoss()
156
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
157
158
159
# As you can see, the code above only relies on PyTorch concepts we that we already introduced previously. Via the `get_model()` function, we define a reusable function to conveniently create a multilayer perceptron with a user-defined number of hidden layers, where each hidden layer is followed by a ReLU activation. The output layer is followed by a Softmax layer.
160
#
161
# Note that the MNIST dataset does not have a pre-defined validation set split. For simplicity, we assigned the test dataset as the validation set for simplicity. However, if we use the validation set for model selection, it does not provide an unbiased estimate of the model's performance.
162
163
# ### Setting up training and validation engines with PyTorch-Ignite
164
165
# When we are done setting up the most important parts, PyTorch-Ignite will handle all other boilerplate code. Next, we have to define a trainer engine by passing our model, optimizer, and loss function to the `ignite.engine.create_supervised_trainer()` function for creating a trainer object that is used to train supervised models conveniently (https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html). In addition, we create an *evaluator* engine by passing PyTorch-Ignite’s out-of-the-box metrics and the model to the `ignite.engine.create_supervised_evaluator()` function (https://pytorch.org/ignite/generated/ignite.engine.create_supervised_evaluator.html#create-supervised-evaluator):
166
167
168
169
170
171
trainer = create_supervised_trainer(
172
model, optimizer, loss_fn, device=device
173
)
174
175
val_metrics = {
176
"accuracy": Accuracy(),
177
"loss": Loss(loss_fn)
178
}
179
180
evaluator = create_supervised_evaluator(
181
model, metrics=val_metrics, device=device
182
)
183
184
185
# Both the `trainer` and `evaluator` objects are instances of the `Engine` class (https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html#ignite.engine.engine.Engine), which is one of the core components of PyTorch-Ignite. It is essentially an abstraction over the training or validation loops.
186
187
# ### Creating event handlers for logging and validation
188
189
# We can customize the code further by adding all kinds of event handlers. `Engine` allows adding handlers for various events that are triggered during the run. When an event is triggered, the attached handlers (functions) are executed. Thus, for logging purposes, we add a function that will be executed at the end of every `log_interval` iteration:
190
191
192
193
# How many batches to wait before logging training status
194
log_interval = 100
195
196
@trainer.on(Events.ITERATION_COMPLETED(every=log_interval))
197
def log_training_loss():
198
e = trainer.state.epoch
199
max_e = trainer.state.max_epochs
200
i = trainer.state.iteration
201
batch_loss = trainer.state.output
202
print(f"Epoch[{e}/{max_e}], Iter[{i}] Loss: {batch_loss:.2f}")
203
204
205
# Or, equivalently, without the decorator, we can attach the handler function to the trainer via an `add_event_handler()` call (https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html#ignite.engine.engine.Engine.add_event_handler).
206
#
207
# Similar to creating an event handler for logging the training status that we created above, we can create an event handler for computing validation metrics after each epoch.
208
# Via the following code, we will run the `evaluator` on the validation set data loader, `val_loader`, when an epoch completes:
209
210
211
212
@trainer.on(Events.EPOCH_COMPLETED)
213
def log_validation_results():
214
eval_state = evaluator.run(val_loader)
215
metrics = eval_state.metrics
216
e = trainer.state.epoch
217
max_e = trainer.state.max_epochs
218
acc = metrics['accuracy']
219
avg_loss = metrics['loss']
220
print(f"Validation Results - Epoch[{e}/{max_e}] Avg Accuracy: {acc:.2f} Avg Loss: {avg_loss:.2f}")
221
222
223
# ### Setting up training checkpoints and saving the best model
224
225
# It is a common practice to save the trainer, model, optimizer, and other related objects during the training process. This allows us to resume the model training from the checkpoint in case of an accidental training interruption. We will use an out-of-the-box PyTorch-Ignite handler to set up a training checkpointing for each epoch:
226
227
228
229
230
# We will save in the checkpoint the following:
231
to_save = {"model": model, "optimizer": optimizer, "trainer": trainer}
232
233
# We will save checkpoints to the local disk
234
output_path = "./output"
235
save_handler = DiskSaver(dirname=output_path, require_empty=False)
236
237
# Set up the handler:
238
checkpoint_handler = Checkpoint(
239
to_save, save_handler, filename_prefix="training")
240
241
# Attach the handler to the trainer
242
trainer.add_event_handler(Events.EPOCH_COMPLETED, checkpoint_handler)
243
244
245
# Via the code above, we created a `Checkpoint` object (https://pytorch.org/ignite/generated/ignite.handlers.checkpoint.Checkpoint.html#ignite.handlers.checkpoint.Checkpoint), which allows us to save and load a model later.
246
#
247
# Besides saving models to be able to resume an interrupted training run, we are primarily interested in saving the best model, for example, for making predictions later during the inference stage. We can then load a saved model via `torch.load` as explained in the section Saving and reloading the trained model in *Chapter 12, Parallelizing Neural Network Training with PyTorch*.
248
#
249
# Usually, the best model is determined by the value of a validation metric. We will use the same handler, `Checkpoint`, to save the best model according to the highest validation accuracy:
250
251
252
253
# Store best model by validation accuracy
254
best_model_handler = Checkpoint(
255
{"model": model},
256
save_handler,
257
filename_prefix="best",
258
n_saved=1,
259
score_name="accuracy",
260
score_function=Checkpoint.get_default_score_fn("accuracy"),
261
)
262
263
evaluator.add_event_handler(Events.COMPLETED, best_model_handler)
264
265
266
# ### Setting up TensorBoard as an experiment tracking system
267
268
# When running training with different configurations, another common practice is to use an experiment tracking system, for example, TensorBoard, to log parameters and metrics and to compare experiments. We will use the `TensorboardLogger` (https://pytorch.org/ignite/generated/ignite.contrib.handlers.tensorboard_logger.html#ignite.contrib.handlers.tensorboard_logger.TensorboardLogger) to log the trainer's loss and validation metrics:
269
270
271
272
273
274
tb_logger = TensorboardLogger(log_dir=output_path)
275
276
# Attach handler to plot trainer's loss every 100 iterations
277
tb_logger.attach_output_handler(
278
trainer,
279
event_name=Events.ITERATION_COMPLETED(every=100),
280
tag="training",
281
output_transform=lambda loss: {"batch_loss": loss},
282
)
283
284
# Attach handler for plotting both evaluators' metrics after every epoch completes
285
tb_logger.attach_output_handler(
286
evaluator,
287
event_name=Events.EPOCH_COMPLETED,
288
tag="validation",
289
metric_names="all",
290
global_step_transform=global_step_from_engine(trainer),
291
)
292
293
294
# ### Executing the PyTorch-Ignite model training code
295
296
# The trainer is now set up and ready to be executed. Let’s train the model for five epochs via the `run()` method:
297
298
299
300
trainer.run(train_loader, max_epochs=5)
301
302
303
# We can start TensorBoard server with
304
# tensorboard --logdir='./output'
305
# and display the dashboard in the browser:
306
#
307
308
309
310
311
312
# ---
313
#
314
# **Next steps with PyTorch-Ignite**
315
#
316
# To learn more about PyTorch-Ignite, please check out the official website containing and tutorials and how-to guides at https://pytorch-ignite.ai.
317
#
318
# Among others, the website also includes a handy PyTorch-Ignite code-generator application (https://code-generator.pytorch-ignite.ai/) so you can start working on tasks without rewriting everything from scratch.
319
#
320
# PyTorch-Ignite's code is available on GitHub: https://github.com/pytorch/ignite. The project is a community effort, and everyone is welcome to contribute and join the contributors’ community no matter your background and skills!
321
#
322
#
323
# ---
324
325
# ---
326
#
327
# Readers may ignore the next cell.
328
329
330
331
332
333