14 KiB
14 KiB
In [ ]:
# imports
from matplotlib import pyplot as plt
import torchIn [ ]:
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()In [ ]:
# solution goes here[1;31mRunning cells with 'Python 3.12.3' requires the ipykernel package. [1;31m<a href='command:jupyter.createPythonEnvAndSelectController'>Create a Python Environment</a> with the required packages. [1;31mOr install 'ipykernel' using the command: '/usr/bin/python3 -m pip install ipykernel -U --user --force-reinstall'
In [ ]:
# imports
import torch
from torch import nn
from torch.utils.data import random_split, DataLoader
from torchvision import transforms
from torchvision.datasets import FashionMNISTIn [ ]:
# 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 xIn [ ]:
# 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_lossIn [ ]:
# solution goes hereIn [ ]:
# solution goes here