First pytorch tutorial

Python
Published

July 21, 2023

library('tidyverse')
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.2     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.0
✔ purrr     1.0.1     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
set.seed(1)

library('reticulate')
use_condaenv('machine_learning')
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
/Users/seb/Library/r-miniconda-arm64/envs/machine_learning/lib/python3.9/site-packages/torchvision/io/image.py:13: UserWarning: Failed to load image Python extension: 'dlopen(/Users/seb/Library/r-miniconda-arm64/envs/machine_learning/lib/python3.9/site-packages/torchvision/image.so, 0x0006): Symbol not found: __ZN3c106detail19maybe_wrap_dim_slowIxEET_S2_S2_b
  Referenced from: <8CBD0B78-6C7C-3C8B-8C76-ACA7B6112818> /Users/seb/Library/r-miniconda-arm64/envs/machine_learning/lib/python3.9/site-packages/torchvision/image.so
  Expected in:     <07CB8E54-8386-3606-A01E-B92223F93B74> /Users/seb/Library/r-miniconda-arm64/envs/machine_learning/lib/python3.9/site-packages/torch/lib/libc10.dylib'If you don't plan on using image functionality from `torchvision.io`, you can ignore this warning. Otherwise, there might be something wrong with your environment. Did you have `libjpeg` or `libpng` installed before building `torchvision` from source?
  warn(
from torchvision.transforms import ToTensor

# Download training data from open datasets.
training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor(),
)

# Download test data from open datasets.
test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor(),
)


training_data.data.shape
torch.Size([60000, 28, 28])
test_data.data.shape
torch.Size([10000, 28, 28])
batch_size = 64

# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)

for X, y in test_dataloader:
    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
# Get cpu, gpu or mps device for training.
device = (
    "cuda"
    if torch.cuda.is_available()
    else "mps"
    if torch.backends.mps.is_available()
    else "cpu"
)
print(f"Using {device} device")
Using mps device
# Define model
class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            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)
print(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_dataloader, model, loss_fn, optimizer)
    test(test_dataloader, model, loss_fn)
Epoch 1
-------------------------------
loss: 2.293884  [   64/60000]
loss: 2.280516  [ 6464/60000]
loss: 2.254215  [12864/60000]
loss: 2.257743  [19264/60000]
loss: 2.241249  [25664/60000]
loss: 2.206033  [32064/60000]
loss: 2.222995  [38464/60000]
loss: 2.183638  [44864/60000]
loss: 2.180845  [51264/60000]
loss: 2.147983  [57664/60000]
Test Error: 
 Accuracy: 40.3%, Avg loss: 2.137891 

Epoch 2
-------------------------------
loss: 2.147081  [   64/60000]
loss: 2.142349  [ 6464/60000]
loss: 2.073414  [12864/60000]
loss: 2.100391  [19264/60000]
loss: 2.053971  [25664/60000]
loss: 1.983526  [32064/60000]
loss: 2.020415  [38464/60000]
loss: 1.931436  [44864/60000]
loss: 1.939984  [51264/60000]
loss: 1.877790  [57664/60000]
Test Error: 
 Accuracy: 56.7%, Avg loss: 1.862921 

Epoch 3
-------------------------------
loss: 1.894928  [   64/60000]
loss: 1.875024  [ 6464/60000]
loss: 1.740222  [12864/60000]
loss: 1.794675  [19264/60000]
loss: 1.693364  [25664/60000]
loss: 1.631936  [32064/60000]
loss: 1.665979  [38464/60000]
loss: 1.550617  [44864/60000]
loss: 1.587191  [51264/60000]
loss: 1.492842  [57664/60000]
Test Error: 
 Accuracy: 60.1%, Avg loss: 1.494139 

Epoch 4
-------------------------------
loss: 1.558476  [   64/60000]
loss: 1.533684  [ 6464/60000]
loss: 1.366379  [12864/60000]
loss: 1.457518  [19264/60000]
loss: 1.342172  [25664/60000]
loss: 1.323192  [32064/60000]
loss: 1.354460  [38464/60000]
loss: 1.258602  [44864/60000]
loss: 1.304382  [51264/60000]
loss: 1.218093  [57664/60000]
Test Error: 
 Accuracy: 63.1%, Avg loss: 1.229637 

Epoch 5
-------------------------------
loss: 1.300160  [   64/60000]
loss: 1.291894  [ 6464/60000]
loss: 1.113367  [12864/60000]
loss: 1.240308  [19264/60000]
loss: 1.116215  [25664/60000]
loss: 1.128032  [32064/60000]
loss: 1.166063  [38464/60000]
loss: 1.082035  [44864/60000]
loss: 1.127863  [51264/60000]
loss: 1.062129  [57664/60000]
Test Error: 
 Accuracy: 64.9%, Avg loss: 1.068099 
print("Done!")
Done!
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()
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)
  )
)
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"