Files
embedded_machine_learning/01/ex_01.ipynb
T
2026-04-29 11:51:37 +02:00

14 KiB

Exercise 1 - Pytorch Basics

In this task, basic concepts of deep learning will be reviewed and you will learn how to work with the widely used deep learning framework PyTorch. To do this, we will create simple mul- tilayer perceptron architectures, train them, and evaluate them on the FashionMNIST dataset. Furthermore, we will analyse how different training and architectural parameters influence the model.

1.1 Installation

For the first exercises a python version >3.11 and a venv with the following installed depen- dencies is needed: • torch • torchvision • matplotlib The training scripts and helpers needed for this exercise, as well as a requirements.txt including the mentioned dependencies are provided in the ziparchive exercise_1_code on moodle.

Helperfunctions

In [ ]:
# imports
from matplotlib import pyplot as plt 
import torch
In [ ]:
def plot_data(train_dataset, class_mapping):
    figure = plt.figure(figsize=(8, 8))
    cols, rows = 3, 3
    for i in range(1, cols * rows + 1):
        sample_idx = torch.randint(len(train_dataset), size=(1,)).item()

        img, label = train_dataset[sample_idx]
        figure.add_subplot(rows, cols, i)
        plt.title( class_mapping[label])
        plt.axis("off")
        plt.imshow(img.squeeze(), cmap="gray")
    plt.show()
In [ ]:
def plot_acc_loss(acc_history, loss_history):
    fig, ax1 = plt.subplots()
    color= "tab:red"
    ax1.set_xlabel('epochs')
    ax1.set_ylabel('accuracy', color=color)
    ax1.plot(acc_history, color=color)
    ax1.tick_params(axis='y', labelcolor=color)

    ax2 = ax1.twinx()  # instantiate a second Axes that shares the same x-axis

    color = 'tab:blue'
    ax2.set_ylabel('Avg Loss')  # we already handled the x-label with ax1
    ax2.plot(loss_history, color=color)
    ax2.tick_params(axis='y', labelcolor=color)

    fig.tight_layout()  # otherwise the right y-label is slightly clipped
    plt.show()

1.2 Dataset Analysis

We use FashionMNIST as the dataset in this exercise. FashionMNIST is an image classification task in which images of different clothing items have to be classified. It can be downloaded in pytorch via torchvision using the following line: train_dataset= FashionMNIST("data", train=True, download=True, transform=transforms.ToTensor()) First, we want to get familiar with our data to understand how to handle it. To do this, you should programmatically determine the following properties:

  1. How many different classes are there?
  2. What is the mapping between labels and classes?
  3. How many samples does the training dataset contain in total?
  4. What is the dimension of a single sample and what does each dimension represent? Plot a few images using matplotlib for visualization. You can use the plot_data() function from Helperfunctions for this purpose.
In [ ]:
# solution goes here
Running cells with 'Python 3.12.3' requires the ipykernel package.

<a href='command:jupyter.createPythonEnvAndSelectController'>Create a Python Environment</a> with the required packages.

Or install 'ipykernel' using the command: '/usr/bin/python3 -m pip install ipykernel -U --user --force-reinstall'

MLP

In [ ]:
# imports
import torch
from torch import nn
from torch.utils.data import random_split, DataLoader
from torchvision import transforms
from torchvision.datasets import FashionMNIST
In [ ]:
# device (if gpu available, use it)
device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.mps.is_available() else "cpu")
In [ ]:
# class definition
class MLP(nn.Module):
    def __init__(self, input_size, num_classes):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(input_size, 32),
            nn.ReLU(),
           nn.Linear(32, num_classes)
        )

    def forward(self, x):
        x = self.flatten(x)
        x = self.linear_relu_stack(x)
        return x
In [ ]:
# dataset related
#you can use this function to download the train and test dataset
def download_dataset():
    train_dataset = FashionMNIST("data", train=True, download=True, transform=transforms.ToTensor())
    test_dataset = FashionMNIST("data", train=False, download=True, transform=transforms.ToTensor())
    return train_dataset, test_dataset

#you can use this function to split a dataset
def split_dataset(dataset, split_ratio:list):
    return random_split(dataset, split_ratio)
In [ ]:
# training related
def train_one_epoch(dataloader, model, loss_fn, optimizer, device):
    size = len(dataloader.dataset)
    model.train()
    for batch, (sample, label) in enumerate(dataloader):
        sample, label = sample.to(device), label.to(device)

        # Compute prediction error
        pred = model(sample)
        loss = loss_fn(pred, label)

        # Backpropagation
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        if batch % 100 == 0:
            loss, current = loss.item(), (batch + 1) * len(sample)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

def train(epochs, train_dataloader,val_dataloader,model, loss_fn, optimizer, device ):
    model = model.to(device)

    for t in range(epochs):
        print(f"Epoch {t + 1}\n-------------------------------")
        train_one_epoch(train_dataloader, model, loss_fn, optimizer, device)
        acc, loss=test(val_dataloader, model, loss_fn, device)
    print("Done!")
In [ ]:
# testing
def test(dataloader: torch.Dataloader, model, loss_fn , device):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for sample, label in dataloader:
            sample, label = sample.to(device), label.to(device)
            pred = model(sample)
            test_loss += loss_fn(pred, label).item()
            correct += (pred.argmax(1) == label).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")
    return correct, test_loss

1.3 Multilayer perceptron

We now want to train and evaluate a multilayer perceptron(MLP) on the dataset in pytorch. For this, the provided zip archive includes the training loop and a very basic MLP (train.py). First split the train dataset into training and validation dataset with a split of 80-20. To load the dataset during training you can use the pytorch dataloader class. Then train the model for 30 epochs with torch.optim.SGD as optimizer, a learning rate of 0.001 and the nn.CrossentropyLoss function. Plot the loss and validation accuracy over the epochs. Evaluate the final performance on the test set.

In [ ]:
# solution goes here

1.4 Training Hyperparameters

Change the learning rate first to 0.01, and then to 0.1. In which way does the plot change? Now change the optimizer to ADAM. Can you observe differences in Training behaviour? How does changing the batch size influence the training? What happens if you train for 200 epochs?

In [ ]:
# solution goes here

1.5 Early Stopping

While the given training loop implementation works, it has important limitations: • The model parameters from the last epoch are used, even if the model performed better at an earlier stage. This can lead to the optimizer overshooting the minimum and a worse performing final model. • The training always takes the specified epochs, even if the model doesn’t get any better, leading to longer training times. • Although the validation accuracy is observed, it does not inform the model training which could lead to overfitting on the training data. Fix these problems by implementing the following behaviour:

  1. Track the best validation accuracy and best performing model state (Tipp: you may use state=model.state_dict() and model.load_state_dict(state) )
  2. After training, load the best model state.
  3. Introduce a patience parameter (e.g patience = 3)
  4. Track how many epochs have passed since the last validation performance improvement
  5. If the limit, given by the patience is reached, stop training early

1.6 Improvements to model architecture

The given MLP only has a single hidden layer of 32 neurons. What happens if you change the number of layers, width or activation functions? Can you improve the model’s performance by changing the architecture? Which accuracy can you achieve?

1.7 Model analysis

In the previous tasks we evaluated the models based on their loss and their accuracy. Accuracy is a good indication for model performance on balanced datasets, however it does not help us understand in which cases the model fails to predict the answer. For this create a confusion matrix on the test set. Are there classes which the model has more trouble to distinguish than others? Based on the confusion matrix, calculate the precision, recall and F1-Score for each class. Which class is hardest to predict, which one is easiest?

1.8 Model size

Until now we did not care about the size of the model at all. However, as our goal is to eventually run the model on resource-constrained devices, we have to pay attention to the number of parameters a model has. For this, write a function to calculate the number of parameters your model has. How does it compare to the original model? How does the number of parameters relate to the accuracy?