# coding: utf-8123import sys4from python_environment_check import check_packages5import torch6import torch.nn as nn7from torch.utils.data import DataLoader8from torchvision.datasets import MNIST9from torchvision import transforms10from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator11from ignite.metrics import Accuracy, Loss12from ignite.handlers import Checkpoint, DiskSaver13from ignite.contrib.handlers import TensorboardLogger, global_step_from_engine14151617181920# # Machine Learning with PyTorch and Scikit-Learn21# # -- Code Examples2223# ## Package version checks2425# Add folder to path in order to load from the check_packages.py script:26272829sys.path.insert(0, '..')303132# Check recommended package versions:333435363738d = {39'numpy': '1.21.2',40'matplotlib': '3.4.3',41'sklearn': '1.0',42}43check_packages(d)444546# # Chapter 13: Going Deeper -- the Mechanics of PyTorch4748# **Big thanks and credit to Victor Fomin for creating and helping with the original draft of this section!**4950# ## A short introduction to PyTorch-Ignite (Online Bonus Content)5152# 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.53#54#55# **Projects using PyTorch-Ignite**56#57#58# There is a list of research papers with code, blog articles, tutorials, toolkits, and other projects that use PyTorch-Ignite. Notable projects include59# - Medical Open Network for AI (MONAI) (https://monai.io)60# - Conversational AI with Transfer Learning (https://github.com/huggingface/transfer-learning-conv-ai)61# 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-ignite62#63#6465# ---66#67# 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.68#69# In a few words, PyTorch-Ignite provides70# - An extremely simple engine and event system (training loop abstraction)71# - Out-of-the-box metrics to easily evaluate models72# - Built-in handlers to compose training pipelines, save artifacts, and log parameters and metrics73# - Distributed training support74#75# Additional benefits of using PyTorch-Ignite are76# - Less code than pure PyTorch while ensuring maximum control and simplicity77# - More modular code78# In this section, we will build and train again a classifier for the MNIST dataset that we worked with in the previous section.79#8081# ---82#83# **Installing PyTorch-Ignite**84#85# 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:86#87# pip install pytorch-ignite88#89# Below, you can find the command for installing PyTorch-Ignite via conda:90#91# conda install ignite -c pytorch92#93# For the latest information on installing PyTorch-Ignite, please visit the official documentation at https://pytorch.org/ignite/#installation.9495# ### Setting up the PyTorch model9697# 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:9899100101102103104image_path = './'105torch.manual_seed(1)106107transform = transforms.Compose([108transforms.ToTensor()109])110111112mnist_train_dataset = MNIST(113root=image_path,114train=True,115transform=transform,116download=True117)118119mnist_val_dataset = MNIST(120root=image_path,121train=False,122transform=transform,123download=False124)125126batch_size = 64127train_loader = DataLoader(128mnist_train_dataset, batch_size, shuffle=True129)130131val_loader = DataLoader(132mnist_val_dataset, batch_size, shuffle=False133)134135136def get_model(image_shape=(1, 28, 28), hidden_units=(32, 16)):137input_size = image_shape[0] * image_shape[1] * image_shape[2]138all_layers = [nn.Flatten()]139for hidden_unit in hidden_units:140layer = nn.Linear(input_size, hidden_unit)141all_layers.append(layer)142all_layers.append(nn.ReLU())143input_size = hidden_unit144145all_layers.append(nn.Linear(hidden_units[-1], 10))146all_layers.append(nn.Softmax(dim=1))147model = nn.Sequential(*all_layers)148return model149150151device = "cuda" if torch.cuda.is_available() else "cpu"152153model = get_model().to(device)154loss_fn = nn.CrossEntropyLoss()155optimizer = torch.optim.Adam(model.parameters(), lr=0.001)156157158# 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.159#160# 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.161162# ### Setting up training and validation engines with PyTorch-Ignite163164# 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):165166167168169170trainer = create_supervised_trainer(171model, optimizer, loss_fn, device=device172)173174val_metrics = {175"accuracy": Accuracy(),176"loss": Loss(loss_fn)177}178179evaluator = create_supervised_evaluator(180model, metrics=val_metrics, device=device181)182183184# 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.185186# ### Creating event handlers for logging and validation187188# 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:189190191192# How many batches to wait before logging training status193log_interval = 100194195@trainer.on(Events.ITERATION_COMPLETED(every=log_interval))196def log_training_loss():197e = trainer.state.epoch198max_e = trainer.state.max_epochs199i = trainer.state.iteration200batch_loss = trainer.state.output201print(f"Epoch[{e}/{max_e}], Iter[{i}] Loss: {batch_loss:.2f}")202203204# 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).205#206# 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.207# Via the following code, we will run the `evaluator` on the validation set data loader, `val_loader`, when an epoch completes:208209210211@trainer.on(Events.EPOCH_COMPLETED)212def log_validation_results():213eval_state = evaluator.run(val_loader)214metrics = eval_state.metrics215e = trainer.state.epoch216max_e = trainer.state.max_epochs217acc = metrics['accuracy']218avg_loss = metrics['loss']219print(f"Validation Results - Epoch[{e}/{max_e}] Avg Accuracy: {acc:.2f} Avg Loss: {avg_loss:.2f}")220221222# ### Setting up training checkpoints and saving the best model223224# 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:225226227228229# We will save in the checkpoint the following:230to_save = {"model": model, "optimizer": optimizer, "trainer": trainer}231232# We will save checkpoints to the local disk233output_path = "./output"234save_handler = DiskSaver(dirname=output_path, require_empty=False)235236# Set up the handler:237checkpoint_handler = Checkpoint(238to_save, save_handler, filename_prefix="training")239240# Attach the handler to the trainer241trainer.add_event_handler(Events.EPOCH_COMPLETED, checkpoint_handler)242243244# 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.245#246# 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*.247#248# 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:249250251252# Store best model by validation accuracy253best_model_handler = Checkpoint(254{"model": model},255save_handler,256filename_prefix="best",257n_saved=1,258score_name="accuracy",259score_function=Checkpoint.get_default_score_fn("accuracy"),260)261262evaluator.add_event_handler(Events.COMPLETED, best_model_handler)263264265# ### Setting up TensorBoard as an experiment tracking system266267# 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:268269270271272273tb_logger = TensorboardLogger(log_dir=output_path)274275# Attach handler to plot trainer's loss every 100 iterations276tb_logger.attach_output_handler(277trainer,278event_name=Events.ITERATION_COMPLETED(every=100),279tag="training",280output_transform=lambda loss: {"batch_loss": loss},281)282283# Attach handler for plotting both evaluators' metrics after every epoch completes284tb_logger.attach_output_handler(285evaluator,286event_name=Events.EPOCH_COMPLETED,287tag="validation",288metric_names="all",289global_step_transform=global_step_from_engine(trainer),290)291292293# ### Executing the PyTorch-Ignite model training code294295# The trainer is now set up and ready to be executed. Let’s train the model for five epochs via the `run()` method:296297298299trainer.run(train_loader, max_epochs=5)300301302# We can start TensorBoard server with303# tensorboard --logdir='./output'304# and display the dashboard in the browser:305#306307308309310311# ---312#313# **Next steps with PyTorch-Ignite**314#315# To learn more about PyTorch-Ignite, please check out the official website containing and tutorials and how-to guides at https://pytorch-ignite.ai.316#317# 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.318#319# 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!320#321#322# ---323324# ---325#326# Readers may ignore the next cell.327328329330331332333