Dateien nach "01" hochladen
This commit is contained in:
+395
@@ -0,0 +1,395 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "bf2b1e8c",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Exercise 1 - Pytorch Basics\n",
|
||||
"In this task, basic concepts of deep learning will be reviewed and you will learn how to work\n",
|
||||
"with the widely used deep learning framework PyTorch. To do this, we will create simple mul-\n",
|
||||
"tilayer perceptron architectures, train them, and evaluate them on the FashionMNIST dataset.\n",
|
||||
"Furthermore, we will analyse how different training and architectural parameters influence the\n",
|
||||
"model.\n",
|
||||
"## 1.1 Installation\n",
|
||||
"For the first exercises a python version >3.11 and a venv with the following installed depen-\n",
|
||||
"dencies is needed:\n",
|
||||
"• torch\n",
|
||||
"• torchvision\n",
|
||||
"• matplotlib\n",
|
||||
"The training scripts and helpers needed for this exercise, as well as a requirements.txt\n",
|
||||
"including the mentioned dependencies are provided in the ziparchive exercise_1_code on\n",
|
||||
"moodle."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "e5e32ea4",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Helperfunctions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "df0165b5",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# imports\n",
|
||||
"from matplotlib import pyplot as plt \n",
|
||||
"import torch"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ab4dc9d1",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def plot_data(train_dataset, class_mapping):\n",
|
||||
" figure = plt.figure(figsize=(8, 8))\n",
|
||||
" cols, rows = 3, 3\n",
|
||||
" for i in range(1, cols * rows + 1):\n",
|
||||
" sample_idx = torch.randint(len(train_dataset), size=(1,)).item()\n",
|
||||
"\n",
|
||||
" img, label = train_dataset[sample_idx]\n",
|
||||
" figure.add_subplot(rows, cols, i)\n",
|
||||
" plt.title( class_mapping[label])\n",
|
||||
" plt.axis(\"off\")\n",
|
||||
" plt.imshow(img.squeeze(), cmap=\"gray\")\n",
|
||||
" plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "5965822a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def plot_acc_loss(acc_history, loss_history):\n",
|
||||
" fig, ax1 = plt.subplots()\n",
|
||||
" color= \"tab:red\"\n",
|
||||
" ax1.set_xlabel('epochs')\n",
|
||||
" ax1.set_ylabel('accuracy', color=color)\n",
|
||||
" ax1.plot(acc_history, color=color)\n",
|
||||
" ax1.tick_params(axis='y', labelcolor=color)\n",
|
||||
"\n",
|
||||
" ax2 = ax1.twinx() # instantiate a second Axes that shares the same x-axis\n",
|
||||
"\n",
|
||||
" color = 'tab:blue'\n",
|
||||
" ax2.set_ylabel('Avg Loss') # we already handled the x-label with ax1\n",
|
||||
" ax2.plot(loss_history, color=color)\n",
|
||||
" ax2.tick_params(axis='y', labelcolor=color)\n",
|
||||
"\n",
|
||||
" fig.tight_layout() # otherwise the right y-label is slightly clipped\n",
|
||||
" plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b711c0c3",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1.2 Dataset Analysis\n",
|
||||
"We use FashionMNIST as the dataset in this exercise. FashionMNIST is an image classification\n",
|
||||
"task in which images of different clothing items have to be classified. It can be downloaded in\n",
|
||||
"pytorch via torchvision using the following line:\n",
|
||||
"train_dataset= FashionMNIST(\"data\", train=True, download=True,\n",
|
||||
"transform=transforms.ToTensor())\n",
|
||||
"First, we want to get familiar with our data to understand how to handle it. To do this, you\n",
|
||||
"should programmatically determine the following properties:\n",
|
||||
"1. How many different classes are there?\n",
|
||||
"2. What is the mapping between labels and classes?\n",
|
||||
"3. How many samples does the training dataset contain in total?\n",
|
||||
"4. What is the dimension of a single sample and what does each dimension represent?\n",
|
||||
"Plot a few images using matplotlib for visualization. You can use the plot_data() function\n",
|
||||
"from [Helperfunctions](ex_01.ipynb#helperfunctions) for this purpose."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "573a9598",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"ename": "",
|
||||
"evalue": "",
|
||||
"output_type": "error",
|
||||
"traceback": [
|
||||
"\u001b[1;31mRunning cells with 'Python 3.12.3' requires the ipykernel package.\n",
|
||||
"\u001b[1;31m<a href='command:jupyter.createPythonEnvAndSelectController'>Create a Python Environment</a> with the required packages.\n",
|
||||
"\u001b[1;31mOr install 'ipykernel' using the command: '/usr/bin/python3 -m pip install ipykernel -U --user --force-reinstall'"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# solution goes here"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "5422a710",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## MLP"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f26b897c",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# imports\n",
|
||||
"import torch\n",
|
||||
"from torch import nn\n",
|
||||
"from torch.utils.data import random_split, DataLoader\n",
|
||||
"from torchvision import transforms\n",
|
||||
"from torchvision.datasets import FashionMNIST"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "449bcaab",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# device (if gpu available, use it)\n",
|
||||
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"mps\" if torch.mps.is_available() else \"cpu\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "adfea49b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# class definition\n",
|
||||
"class MLP(nn.Module):\n",
|
||||
" def __init__(self, input_size, num_classes):\n",
|
||||
" super().__init__()\n",
|
||||
" self.flatten = nn.Flatten()\n",
|
||||
" self.linear_relu_stack = nn.Sequential(\n",
|
||||
" nn.Linear(input_size, 32),\n",
|
||||
" nn.ReLU(),\n",
|
||||
" nn.Linear(32, num_classes)\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" def forward(self, x):\n",
|
||||
" x = self.flatten(x)\n",
|
||||
" x = self.linear_relu_stack(x)\n",
|
||||
" return x"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "be5e3a9e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# dataset related\n",
|
||||
"#you can use this function to download the train and test dataset\n",
|
||||
"def download_dataset():\n",
|
||||
" train_dataset = FashionMNIST(\"data\", train=True, download=True, transform=transforms.ToTensor())\n",
|
||||
" test_dataset = FashionMNIST(\"data\", train=False, download=True, transform=transforms.ToTensor())\n",
|
||||
" return train_dataset, test_dataset\n",
|
||||
"\n",
|
||||
"#you can use this function to split a dataset\n",
|
||||
"def split_dataset(dataset, split_ratio:list):\n",
|
||||
" return random_split(dataset, split_ratio)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f1b6c5ad",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# training related\n",
|
||||
"def train_one_epoch(dataloader, model, loss_fn, optimizer, device):\n",
|
||||
" size = len(dataloader.dataset)\n",
|
||||
" model.train()\n",
|
||||
" for batch, (sample, label) in enumerate(dataloader):\n",
|
||||
" sample, label = sample.to(device), label.to(device)\n",
|
||||
"\n",
|
||||
" # Compute prediction error\n",
|
||||
" pred = model(sample)\n",
|
||||
" loss = loss_fn(pred, label)\n",
|
||||
"\n",
|
||||
" # Backpropagation\n",
|
||||
" loss.backward()\n",
|
||||
" optimizer.step()\n",
|
||||
" optimizer.zero_grad()\n",
|
||||
"\n",
|
||||
" if batch % 100 == 0:\n",
|
||||
" loss, current = loss.item(), (batch + 1) * len(sample)\n",
|
||||
" print(f\"loss: {loss:>7f} [{current:>5d}/{size:>5d}]\")\n",
|
||||
"\n",
|
||||
"def train(epochs, train_dataloader,val_dataloader,model, loss_fn, optimizer, device ):\n",
|
||||
" model = model.to(device)\n",
|
||||
"\n",
|
||||
" for t in range(epochs):\n",
|
||||
" print(f\"Epoch {t + 1}\\n-------------------------------\")\n",
|
||||
" train_one_epoch(train_dataloader, model, loss_fn, optimizer, device)\n",
|
||||
" acc, loss=test(val_dataloader, model, loss_fn, device)\n",
|
||||
" print(\"Done!\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "888c9513",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# testing\n",
|
||||
"def test(dataloader: torch.Dataloader, model, loss_fn , device):\n",
|
||||
" size = len(dataloader.dataset)\n",
|
||||
" num_batches = len(dataloader)\n",
|
||||
" model.eval()\n",
|
||||
" test_loss, correct = 0, 0\n",
|
||||
" with torch.no_grad():\n",
|
||||
" for sample, label in dataloader:\n",
|
||||
" sample, label = sample.to(device), label.to(device)\n",
|
||||
" pred = model(sample)\n",
|
||||
" test_loss += loss_fn(pred, label).item()\n",
|
||||
" correct += (pred.argmax(1) == label).type(torch.float).sum().item()\n",
|
||||
" test_loss /= num_batches\n",
|
||||
" correct /= size\n",
|
||||
" print(f\"Test Error: \\n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \\n\")\n",
|
||||
" return correct, test_loss"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "ee367f3d",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1.3 Multilayer perceptron\n",
|
||||
"We now want to train and evaluate a multilayer perceptron(MLP) on the dataset in pytorch.\n",
|
||||
"For this, the provided zip archive includes the training loop and a very basic MLP (train.py).\n",
|
||||
"First split the train dataset into training and validation dataset with a split of 80-20. To load\n",
|
||||
"the dataset during training you can use the [pytorch dataloader class](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader).\n",
|
||||
"Then train the model for 30 epochs with torch.optim.SGD as optimizer, a learning rate of 0.001\n",
|
||||
"and the nn.CrossentropyLoss function. Plot the loss and validation accuracy over the epochs.\n",
|
||||
"Evaluate the final performance on the test set."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "754e0f58",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# solution goes here"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "25cf15b2",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1.4 Training Hyperparameters\n",
|
||||
"Change the learning rate first to 0.01, and then to 0.1. In which way does the plot change?\n",
|
||||
"Now change the optimizer to ADAM. Can you observe differences in Training behaviour? How\n",
|
||||
"does changing the batch size influence the training? What happens if you train for 200 epochs?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "57b4f40e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# solution goes here"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4b9b9dc4",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1.5 Early Stopping\n",
|
||||
"While the given training loop implementation works, it has important limitations:\n",
|
||||
"• The model parameters from the last epoch are used, even if the model performed better\n",
|
||||
"at an earlier stage. This can lead to the optimizer overshooting the minimum and a worse\n",
|
||||
"performing final model.\n",
|
||||
"• The training always takes the specified epochs, even if the model doesn’t get any better,\n",
|
||||
"leading to longer training times.\n",
|
||||
"• Although the validation accuracy is observed, it does not inform the model training which\n",
|
||||
"could lead to overfitting on the training data.\n",
|
||||
"Fix these problems by implementing the following behaviour:\n",
|
||||
"1. Track the best validation accuracy and best performing model state (Tipp: you may use\n",
|
||||
"state=model.state_dict() and model.load_state_dict(state) )\n",
|
||||
"2. After training, load the best model state.\n",
|
||||
"3. Introduce a patience parameter (e.g patience = 3)\n",
|
||||
"4. Track how many epochs have passed since the last validation performance improvement\n",
|
||||
"5. If the limit, given by the patience is reached, stop training early"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "49095c53",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1.6 Improvements to model architecture\n",
|
||||
"The given MLP only has a single hidden layer of 32 neurons. What happens if you change the\n",
|
||||
"number of layers, width or activation functions?\n",
|
||||
"Can you improve the model’s performance by changing the architecture?\n",
|
||||
"Which accuracy can you achieve?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "90331451",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1.7 Model analysis\n",
|
||||
"In the previous tasks we evaluated the models based on their loss and their accuracy. Accuracy\n",
|
||||
"is a good indication for model performance on balanced datasets, however it does not help us\n",
|
||||
"understand in which cases the model fails to predict the answer.\n",
|
||||
"For this create a confusion matrix on the test set. Are there classes which the model has more\n",
|
||||
"trouble to distinguish than others? Based on the confusion matrix, calculate the precision,\n",
|
||||
"recall and F1-Score for each class. Which class is hardest to predict, which one is easiest?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "5c1e2f28",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1.8 Model size\n",
|
||||
"Until now we did not care about the size of the model at all. However, as our goal is to\n",
|
||||
"eventually run the model on resource-constrained devices, we have to pay attention to the\n",
|
||||
"number of parameters a model has. For this, write a function to calculate the number of\n",
|
||||
"parameters your model has. How does it compare to the original model? How does the number\n",
|
||||
"of parameters relate to the accuracy?"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python",
|
||||
"version": "3.12.3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
from matplotlib import pyplot as plt
|
||||
import torch
|
||||
|
||||
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()
|
||||
|
||||
|
||||
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()
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
torch~=2.11.0
|
||||
matplotlib~=3.10.8
|
||||
torchvision~=0.26.0
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.utils.data import random_split, DataLoader
|
||||
from torchvision import transforms
|
||||
from torchvision.datasets import FashionMNIST
|
||||
|
||||
|
||||
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
|
||||
|
||||
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 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
|
||||
|
||||
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!")
|
||||
|
||||
#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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
#if gpu available, use it
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.mps.is_available() else "cpu")
|
||||
|
||||
# instantiate the given mlp, SGD optimizer and crossentropy loss. instantiate pytorch dataloaders with the dataset and run training
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user