# PyTorch-Quickstart

import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision import datasets
from torchvision.transforms import ToTensor
import matplotlib.pyplot as plt

# Working with data

  • PyTorch has two primitives to work with data: torch.utils.data.DataLoader and torch.utils.data.Dataset. Dataset stores the samples and their corresponding labels, and DataLoader wraps an iterable around the Dataset.
# Downloads dataset and automatically transforms and scales data
train_data = datasets.FashionMNIST(root="data", train=True, download=True, transform=ToTensor())
test_data = datasets.FashionMNIST(root="data", train=False, download=True, transform=ToTensor())
  • We pass the Dataset to a DataLoader. This wraps the iterable over the dataset and supports automatic batching, sampling, shuffling and multiprocess data loading. Each element in this iterable will be of the given batch size.
batch_size = 64

train_dl = DataLoader(train_data, batch_size=batch_size)
test_dl = DataLoader(test_data, batch_size=batch_size)

for X, y in test_dl:
    print(f"Shape of X [N, C, H, W]: {X.shape}")
    print(f"Shape of y: {y.shape} {y.dtype}")
    break
Shape of X [N, C, H, W]: torch.Size([64, 1, 28, 28])
Shape of y: torch.Size([64]) torch.int64

# Creating & training models

  • We use nn.Module to create a NN. Layers are defined in the __init__ fn and the process of data passage through the network is defined in the forward fn.
device = (
    "cuda"
    if torch.cuda.is_available()
    else "mps"
    if torch.backends.mps.is_available()
    else "cpu"
)
print(f"Using {device} device")
Using cuda device
class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),  # Takes in & out size
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10)
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

model = NeuralNetwork().to(device)
model
NeuralNetwork(
  (flatten): Flatten(start_dim=1, end_dim=-1)
  (linear_relu_stack): Sequential(
    (0): Linear(in_features=784, out_features=512, bias=True)
    (1): ReLU()
    (2): Linear(in_features=512, out_features=512, bias=True)
    (3): ReLU()
    (4): Linear(in_features=512, out_features=10, bias=True)
  )
)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    model.train()

    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)

        # Compute prediction error
        pred = model(X)
        loss = loss_fn(pred, y)

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

        if batch % 100 == 0:
            loss, current = loss.item(), (batch + 1) * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")
def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()

    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).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")
epochs = 5

for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train(train_dl, model, loss_fn, optimizer)
    test(test_dl, model, loss_fn)

print("Done!")
Epoch 1
-------------------------------
loss: 2.300023  [   64/60000]
loss: 2.282963  [ 6464/60000]
loss: 2.259477  [12864/60000]
loss: 2.255992  [19264/60000]
loss: 2.246285  [25664/60000]
loss: 2.212793  [32064/60000]
loss: 2.218766  [38464/60000]
loss: 2.177712  [44864/60000]
loss: 2.179352  [51264/60000]
loss: 2.145025  [57664/60000]
Test Error: 
 Accuracy: 45.6%, Avg loss: 2.136228 

Epoch 2
-------------------------------
loss: 2.152839  [   64/60000]
loss: 2.132048  [ 6464/60000]
loss: 2.064191  [12864/60000]
loss: 2.095134  [19264/60000]
loss: 2.041862  [25664/60000]
loss: 1.972970  [32064/60000]
loss: 2.008766  [38464/60000]
loss: 1.911095  [44864/60000]
loss: 1.924729  [51264/60000]
loss: 1.860631  [57664/60000]
Test Error: 
 Accuracy: 54.6%, Avg loss: 1.849374 

Epoch 3
-------------------------------
loss: 1.887922  [   64/60000]
loss: 1.845952  [ 6464/60000]
loss: 1.717600  [12864/60000]
loss: 1.783016  [19264/60000]
loss: 1.672628  [25664/60000]
loss: 1.619707  [32064/60000]
loss: 1.655750  [38464/60000]
loss: 1.541622  [44864/60000]
loss: 1.580325  [51264/60000]
loss: 1.482737  [57664/60000]
Test Error: 
 Accuracy: 62.3%, Avg loss: 1.491978 

Epoch 4
-------------------------------
loss: 1.564908  [   64/60000]
loss: 1.522284  [ 6464/60000]
loss: 1.362493  [12864/60000]
loss: 1.452010  [19264/60000]
loss: 1.341246  [25664/60000]
loss: 1.330601  [32064/60000]
loss: 1.354728  [38464/60000]
loss: 1.270351  [44864/60000]
loss: 1.313188  [51264/60000]
loss: 1.217961  [57664/60000]
Test Error: 
 Accuracy: 64.3%, Avg loss: 1.238418 

Epoch 5
-------------------------------
loss: 1.317977  [   64/60000]
loss: 1.295236  [ 6464/60000]
loss: 1.120098  [12864/60000]
loss: 1.234601  [19264/60000]
loss: 1.122686  [25664/60000]
loss: 1.140069  [32064/60000]
loss: 1.165707  [38464/60000]
loss: 1.098476  [44864/60000]
loss: 1.143580  [51264/60000]
loss: 1.057847  [57664/60000]
Test Error: 
 Accuracy: 65.2%, Avg loss: 1.077951 

Done!

# Saving and loading models

torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")
Saved PyTorch Model State to model.pth
model = NeuralNetwork().to(device)
model.load_state_dict(torch.load("model.pth"))
<All keys matched successfully>
classes = [
    "T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot",
]

model.eval()
x, y = test_data[0][0], test_data[0][1]

with torch.no_grad():
    x = x.to(device)
    pred = model(x)
    predicted, actual = classes[pred[0].argmax(0)], classes[y]
    print(f'Predicted: "{predicted}", Actual: "{actual}"')
Predicted: "Ankle boot", Actual: "Ankle boot"