87 lines
2.9 KiB
Python
87 lines
2.9 KiB
Python
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
|
|
|
|
|
|
|