pytorch-templates/pure-torch.ipynb
2025-05-29 20:18:21 -05:00

20 KiB

In [1]:
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
from tqdm import tqdm
In [2]:
training_data = datasets.FashionMNIST(
    root="data", train=True, download=True, transform=ToTensor()
)
test_data = datasets.FashionMNIST(
    root="data", train=False, download=True, transform=ToTensor()
)
In [3]:
batch_size = 64

# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size, shuffle=True)
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
In [4]:
# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")

# Define model
class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_stack = nn.Sequential(
            nn.Linear(28 * 28, 512),
            nn.Hardswish(),
            nn.Linear(512, 512),
            nn.Hardswish(),
            nn.Linear(512, 10)
        )

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


model = NeuralNetwork().to(device)
print(model)
Using cuda device
NeuralNetwork(
  (flatten): Flatten(start_dim=1, end_dim=-1)
  (linear_stack): Sequential(
    (0): Linear(in_features=784, out_features=512, bias=True)
    (1): Hardswish()
    (2): Linear(in_features=512, out_features=512, bias=True)
    (3): Hardswish()
    (4): Linear(in_features=512, out_features=10, bias=True)
  )
)
In [5]:
def train(
    dataloader: DataLoader,
    model: NeuralNetwork,
    loss_fn: nn.Module,
    optimizer: torch.optim.Optimizer,
    epoch: int,
    verbose: bool = True,
):
    model.train()
    for X, y in tqdm(
        dataloader, desc=f"Epoch {epoch+1}", disable=not verbose, unit=" batch"
    ):
        X, y = X.to(device), y.to(device)

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

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


def test(dataloader: DataLoader, model: NeuralNetwork, loss_fn: nn.Module):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.inference_mode():
        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 accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
In [6]:
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)

epochs = 10
for t in range(epochs):
    train(train_dataloader, model, loss_fn, optimizer, t)
    test(test_dataloader, model, loss_fn)
print("Done!")
Epoch 1: 100%|██████████| 938/938 [00:18<00:00, 51.42 batch/s]
Test accuracy: 84.6%, Avg loss: 0.416450 

Epoch 2: 100%|██████████| 938/938 [00:17<00:00, 53.97 batch/s]
Test accuracy: 86.8%, Avg loss: 0.379103 

Epoch 3: 100%|██████████| 938/938 [00:16<00:00, 56.64 batch/s]
Test accuracy: 87.3%, Avg loss: 0.358019 

Epoch 4: 100%|██████████| 938/938 [00:17<00:00, 53.37 batch/s]
Test accuracy: 86.9%, Avg loss: 0.356684 

Epoch 5: 100%|██████████| 938/938 [00:16<00:00, 57.66 batch/s]
Test accuracy: 87.5%, Avg loss: 0.342070 

Epoch 6: 100%|██████████| 938/938 [00:15<00:00, 60.13 batch/s]
Test accuracy: 88.3%, Avg loss: 0.331236 

Epoch 7: 100%|██████████| 938/938 [00:17<00:00, 53.23 batch/s]
Test accuracy: 88.4%, Avg loss: 0.316383 

Epoch 8: 100%|██████████| 938/938 [00:19<00:00, 48.65 batch/s]
Test accuracy: 88.7%, Avg loss: 0.316623 

Epoch 9: 100%|██████████| 938/938 [00:18<00:00, 49.89 batch/s]
Test accuracy: 88.8%, Avg loss: 0.326257 

Epoch 10: 100%|██████████| 938/938 [00:17<00:00, 55.03 batch/s]
Test accuracy: 89.2%, Avg loss: 0.328708 

Done!
In [7]:
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")

model = NeuralNetwork()
load_results = model.load_state_dict(torch.load("model.pth"))
Saved PyTorch Model State to model.pth
In [8]:
classes = [
    "T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot",
]

x, y = test_data[0][0], test_data[0][1]
plt.imshow(x.numpy()[0], cmap="gray")
plt.show()

model.eval()
with torch.inference_mode():
    logits = model(x)
    pred = torch.softmax(logits, dim=1)
    predicted, actual = classes[pred[0].argmax(0)], classes[y]
    print(f'Predicted: "{predicted}", Actual: "{actual}"')
No description has been provided for this image
Predicted: "Ankle boot", Actual: "Ankle boot"