Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
---
title: Create a PyTorch model for digit classification
draft: true
cascade:
draft: true

minutes_to_complete: 40

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
# ================================================================================

next_step_guidance: >
Proceed to Get Started with Arm Performance Studio for mobile to continue learning about Android performance analysis.
Continue to learn how to train the model with PyTorch and use it for inference.

# 1-3 sentence recommendation outlining how the reader can generally keep learning about these topics, and a specific explanation of why the next step is being recommended.

recommended_path: "/learning-paths/smartphones-and-mobile/ams/"
recommended_path: "/learning-paths/cross-platform/pytorch-digit-classification-training/"

# Link to the next learning path being recommended(For example this could be /learning-paths/servers-and-cloud-computing/mongodb).

Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,40 @@
---
title: Learn how to train the PyTorch model for digit classification
title: Train a PyTorch model for digit classification
minutes_to_complete: 40

who_is_this_for: This is an introductory topic for software developers interested in learning how to use PyTorch to train a feedforward neural network for digit classification.

learning_objectives:
- Download and prepare the dataset.
- Download and prepare the MNIST dataset.
- Train a neural network using PyTorch.

prerequisites:
- A x86_64 or Apple development machine with Code Editor (we recommend Visual Studio Code).
- Any computer which can run Python3 and Visual Studio Code, this can be Windows, Linux, or macOS.
- You should complete [Create a PyTorch model for digit classification](/learning-paths/cross-platform/pytorch-digit-classification-architecture/) before starting this Learning Path.

author_primary: Dawid Borycki

### Tags
skilllevels: Introductory
subjects: Neural Networks
subjects: ML
armips:
- Cortex-A
- Cortex-X
- Neoverse
operatingsystems:
- Windows
- Linux
- MacOS
- macOS
tools_software_languages:
- Android Studio
- Coding

shared_path: true
shared_between:
- servers-and-cloud-computing
- laptops-and-desktops
- smartphones-and-mobile


### FIXED, DO NOT MODIFY
# ================================================================================
weight: 1 # _index.md always has weight of 1 to order correctly
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
# ================================================================================

next_step_guidance: >
Proceed to Get Started with Arm Performance Studio for mobile to continue learning about Android performance analysis.
Proceed to Use Keras Core with TensorFlow, PyTorch, and JAX backends to continue exploring Machine Learning.

# 1-3 sentence recommendation outlining how the reader can generally keep learning about these topics, and a specific explanation of why the next step is being recommended.

recommended_path: "/learning-paths/smartphones-and-mobile/ams/"
recommended_path: "/learning-paths/servers-and-cloud-computing/keras-core/"

# Link to the next learning path being recommended(For example this could be /learning-paths/servers-and-cloud-computing/mongodb).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ weight: 3
layout: "learningpathall"
---

We start by downloading the MNIST dataset. Proceed as follows:
1. Open, the pytorch-digits.ipynb you created in this [Learning Path](learning-paths/cross-platform/pytorch-digit-classification-architecture).
Start by downloading the MNIST dataset. Proceed as follows:

1. Open, the pytorch-digits.ipynb you created in [Create a PyTorch model for digit classification](/learning-paths/cross-platform/pytorch-digit-classification-architecture/).

2. Add the following statements:

```Python
```python
from torchvision import transforms, datasets
from torch.utils.data import DataLoader

Expand All @@ -38,31 +40,33 @@ train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
```

The above code snippet downloads the MNIST dataset, transforms the images into tensors, and sets up data loaders for training and testing. Specifically, the datasets.MNIST function is used to download the MNIST dataset, with train=True indicating training data and train=False indicating test data. The transform=transforms.ToTensor() argument converts each image in the dataset into a PyTorch tensor, which is necessary for model training and evaluation.
The above code snippet downloads the MNIST dataset, transforms the images into tensors, and sets up data loaders for training and testing. Specifically, the `datasets.MNIST` function is used to download the MNIST dataset, with `train=True` indicating training data and `train=False` indicating test data. The `transform=transforms.ToTensor()` argument converts each image in the dataset into a PyTorch tensor, which is necessary for model training and evaluation.

The DataLoader wraps the datasets and allows efficient loading of data in batches. It handles data shuffling, batching, and parallel loading. Here, the train_dataloader and test_dataloader are created with a batch_size of 32, meaning they will load 32 images per batch during training and testing.

This setup prepares the training and test datasets for use in a machine learning model, enabling efficient data handling and model training in PyTorch.

To run the above code, you will need to install certifi package:

```console
pip install certifi
```

certifi is a Python package that provides the Mozilla’s root certificates, which are essential for ensuring the SSL connections are secure. If you’re using macOS, you may also need to install the certificates by running:
The certifi Python package provides the Mozilla root certificates, which are essential for ensuring the SSL connections are secure. If you’re using macOS, you may also need to install the certificates by running:

```console
/Applications/Python\ 3.x/Install\ Certificates.command
```

Make sure to replace `x` by the number of Python version you have installed.
Make sure to replace `x` with the number of Python version you have installed.

After running the code you will see the output that might look like shown below:

![image](Figures/01.png)

# Training
Now, we have all the tools needed to train the model. We first specify the loss function and the optimizer:
# Train the model

To train the model, specify the loss function and the optimizer:

```Python
learning_rate = 1e-3
Expand All @@ -71,9 +75,9 @@ loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
```

We use CrossEntropyLoss as the loss function and the Adam optimizer for training. The learning rate is set to 1e-3.
Use CrossEntropyLoss as the loss function and the Adam optimizer for training. The learning rate is set to 1e-3.

Next, we define the methods for training and evaluating our feedforward neural network:
Next, define the methods for training and evaluating the feedforward neural network:

```Python
def train_loop(dataloader, model, loss_fn, optimizer):
Expand Down Expand Up @@ -105,9 +109,9 @@ def test_loop(dataloader, model, loss_fn):
print(f"Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
```

The first method, train_loop, uses the backpropagation algorithm to optimize the trainable parameters and minimize the prediction error of the neural network. The second method, test_loop, calculates the neural network error using the test images and displays the accuracy and loss values.
The first method, `train_loop`, uses the backpropagation algorithm to optimize the trainable parameters and minimize the prediction error of the neural network. The second method, `test_loop`, calculates the neural network error using the test images and displays the accuracy and loss values.

We can now invoke these methods to train and evaluate the model. Similarly to TensorFlow, we use 10 epochs.
You can now invoke these methods to train and evaluate the model using 10 epochs.

```Python
epochs = 10
Expand All @@ -131,20 +135,21 @@ Accuracy: 95.4%, Avg loss: 1.507491

which shows the model achieved around 95% of accuracy.

# Saving the model
Once the model is trained, we can save it. There are various approaches for this. In PyTorch, you can save both the model’s structure and its weights to the same file using the torch.save() function. Alternatively, you can save only the weights (parameters) of the model, not the model architecture itself. This requires you to have the model’s architecture defined separately when loading. To save the model weights, you can use the following command:
# Save the model

Once the model is trained, you can save it. There are various approaches for this. In PyTorch, you can save both the model’s structure and its weights to the same file using the `torch.save()` function. Alternatively, you can save only the weights (parameters) of the model, not the model architecture itself. This requires you to have the model’s architecture defined separately when loading. To save the model weights, you can use the following command:

```Python
torch.save(model.state_dict(), "model_weights.pth").
```

However, PyTorch does not save the definition of the class itself. When you load the model using torch.load(), PyTorch needs to know the class definition to recreate the model object.
However, PyTorch does not save the definition of the class itself. When you load the model using `torch.load()`, PyTorch needs to know the class definition to recreate the model object.

Therefore, when you later want to use the saved model for inference, you will need to provide the definition of the model class.

Alternatively, you can use TorchScript, which serializes both the architecture and weights into a single file that can be loaded without needing the original class definition. This is particularly useful for deploying models to production or sharing models without code dependencies.

Here, we use TorchScript and save the model using the following commands:
Use TorchScript to save the model using the following commands:

```Python
# Set model to evaluation mode
Expand All @@ -157,15 +162,16 @@ traced_model = torch.jit.trace(model, torch.rand(1, 1, 28, 28))
traced_model.save("model.pth")
```

The above commands set the model to evaluation mode (model.eval()), then trace the model, and save it. Tracing is useful for converting models with static computation graphs to TorchScript, making them portable and independent of the original class definition.
The above commands set the model to evaluation mode, trace the model, and save it. Tracing is useful for converting models with static computation graphs to TorchScript, making them portable and independent of the original class definition.

Setting the model to evaluation mode before tracing is important for several reasons:

1. Behavior of Layers like Dropout and BatchNorm:
* Dropout. During training (model.train()), dropout randomly zeroes out some of the activations to prevent overfitting. During evaluation (model.eval()), dropout is turned off, and all activations are used.
* BatchNorm. During training, Batch Normalization layers use batch statistics to normalize the input. During evaluation, they use running averages calculated during training.
* Dropout. During training, dropout randomly zeroes out some of the activations to prevent overfitting. During evaluation dropout is turned off, and all activations are used.
* BatchNorm. During training, Batch Normalization layers use batch statistics to normalize the input. During evaluation, they use running averages calculated during training.

2. Consistent Inference Behavior. By setting the model to eval() mode, you ensure that the traced model will behave consistently during inference, as it will not use dropout or batch statistics that are inappropriate for inference.
2. Consistent Inference Behavior. By setting the model to eval mode, you ensure that the traced model will behave consistently during inference, as it will not use dropout or batch statistics that are inappropriate for inference.

3. Correct Tracing. Tracing captures the operations performed by the model using a given input. If the model is in training mode, the traced graph may include operations related to dropout and batch normalization updates. These operations can affect the correctness and performance of the model during inference.

In the next step, we will use the saved model for inference.
In the next step, you will use the saved model for inference.
Loading