mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
168 KiB
168 KiB
In [123]:
# Import PyTorch
import torch
from torch import nn
# Import torchvision
import torchvision
from torchvision import datasets
from torchvision.transforms import ToTensor
# Import matplotlib for visualization
import matplotlib.pyplot as plt
# Check versions
# Note: your PyTorch version shouldn't be lower than 1.10.0 and torchvision version shouldn't be lower than 0.11)
print(f"PyTorch version: {torch.__version__}\ntorchvision version: {torchvision.__version__}")PyTorch version: 1.10.0 torchvision version: 0.11.1
In [120]:
train_data = datasets.FashionMNIST(
root="data", # where to download data to?
train=True, # get training data
download=True, # download data if it doesn't exist on disk
transform=ToTensor(), # images come as PIL format, we want to turn into Torch tensors
target_transform=None # you can transform labels as well
)
test_data = datasets.FashionMNIST(
root="data",
train=False, # get test data
download=True,
transform=ToTensor()
)In [95]:
# See labels
train_data.targetsOut [95]:
tensor([9, 0, 0, ..., 3, 0, 5])
In [96]:
# See classes
class_names = train_data.classes
class_namesOut [96]:
['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
In [97]:
# Check out the data shapes
img, label = train_data[0]
img.shape, label # image is [1, 28, 28] and has int labelOut [97]:
(torch.Size([1, 28, 28]), 9)
In [98]:
import matplotlib.pyplot as plt
img, label = train_data[0]
plt.imshow(img.squeeze()) # image shape is [1, 28, 28] (batch, height, width)
plt.title(label);In [99]:
img, label = train_data[0]
plt.imshow(img.squeeze(), cmap="gray")
plt.title(class_names[label]);In [100]:
# Plot more images
torch.manual_seed(42)
fig = plt.figure(figsize=(9, 9))
rows, cols = 4, 4
for i in range(1, rows * cols + 1):
random_idx = torch.randint(0, len(train_data), size=[1]).item()
img, label = train_data[random_idx]
fig.add_subplot(rows, cols, i)
plt.imshow(img.squeeze(), cmap="gray")
plt.title(class_names[label])
plt.axis(False);In [101]:
from torch.utils.data import DataLoader
# Turn datasets into iterables (batches)
train_dataloader = DataLoader(train_data, # dataset to turn into iterable
batch_size=32, # how many samples per batch?
shuffle=True # shuffle data every epoch?
)
test_dataloader = DataLoader(test_data,
batch_size=32,
shuffle=True
)
# TK - these lengths are of the number of batch sizes...
train_dataloader, test_dataloader, len(train_dataloader), len(test_dataloader)Out [101]:
(<torch.utils.data.dataloader.DataLoader at 0x7f423501bdf0>, <torch.utils.data.dataloader.DataLoader at 0x7f4228649970>, 1875, 313)
In [102]:
# Check out dataloader
# TK - If using VSCode, be sure to check these out in the Data Viewer (go to Variables -> pick the variable you want to inspect)
train_features_batch, train_labels_batch = next(iter(train_dataloader))
train_features_batch.shape, train_labels_batch.shapeOut [102]:
(torch.Size([32, 1, 28, 28]), torch.Size([32]))
In [103]:
# Show a sample
torch.manual_seed(42)
random_idx = torch.randint(0, len(train_features_batch), size=[1]).item()
img, label = train_features_batch[random_idx], train_labels_batch[random_idx]
plt.imshow(img.squeeze(), cmap="gray")
plt.title(class_names[label])
plt.axis("Off");
print(f"Image size: {img.shape}")
print(f"Label: {label}, label size: {label.shape}")Image size: torch.Size([1, 28, 28]) Label: 6, label size: torch.Size([])
In [104]:
flatten_model = nn.Flatten() # all nn modules function as a model (can do a forward pass)
x = train_features_batch[0]
output = flatten_model(x) # perform forward pass
x.shape, output.size()
Out [104]:
(torch.Size([1, 28, 28]), torch.Size([1, 784]))
In [105]:
from torch import nn
class FashionMNISTModelV0(nn.Module):
def __init__(self, input_shape, hidden_units, output_shape):
super().__init__()
self.layer_stack = nn.Sequential(
nn.Flatten(), # neural networks like their inputs in vector form
nn.Linear(in_features=input_shape, out_features=hidden_units), # TK - explain in and out features (could use TF playground for this)
nn.Linear(in_features=hidden_units, out_features=output_shape)
)
def forward(self, x):
return self.layer_stack(x)In [106]:
torch.manual_seed(42)
# Need to setup model with input parameters
model_0 = FashionMNISTModelV0(input_shape=784, # one for every pixel (28x28)
hidden_units=128, # how many units in the hiden layer
output_shape=len(class_names) # one for every class
)
model_0.to("cpu") # keep model on CPU to begin wtih Out [106]:
FashionMNISTModelV0(
(layer_stack): Sequential(
(0): Flatten(start_dim=1, end_dim=-1)
(1): Linear(in_features=784, out_features=128, bias=True)
(2): Linear(in_features=128, out_features=10, bias=True)
)
)In [107]:
# TK - Write code here to download helper functions
import requests
from pathlib import Path
# Download helper functions from Learn PyTorch repo (if not already downloaded)
if Path("helper_functions.py").is_file():
print("helper_functions.py already exists, skipping download")
else:
print("Downloading helper_functions.py")
request = requests.get("https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/helper_functions.py")
with open("helper_functions.py", "wb") as f:
f.write(request.content)helper_functions.py already exists, skipping download
In [108]:
# Setup loss, optimizer and accuracy metric
from helper_functions import accuracy_fn
loss_fn = nn.CrossEntropyLoss() # this is also called "criterion"/"cost function" in some places
optimizer = torch.optim.SGD(model_0.parameters(), lr=0.1)In [109]:
from timeit import default_timer as timer
def print_train_time(start, end, device=None):
"""Prints difference between start and end time.
Args:
start (float): Start time of computation (preferred in timeit format).
end (float): End time of computation.
device ([type], optional): Device that compute is running on. Defaults to None.
Returns:
float: time between start and end in seconds (higher is longer).
"""
total_time = end - start
print(f"\nTrain time on {device}: {total_time:.3f} seconds")
return total_timeIn [110]:
torch.manual_seed(42)
train_time_start_on_cpu = timer()
# Create training loop
epochs = 5
for epoch in range(epochs):
print(f"\nEpoch {epoch+1}\n----------")
for batch, (X, y) in enumerate(train_dataloader):
# Training
# 1. Forward pass
y_pred = model_0(X)
# 2. Calculate loss
loss = loss_fn(y_pred, y)
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backward
loss.backward()
# 5. Optimizer step
optimizer.step()
# Print out what's happening
if batch % 250 == 0:
batch_number = batch * len(X)
print(f"Loss: {loss:.5f} | Looked at {batch_number}/{len(train_dataloader.dataset)} samples")
# Testing
test_loss, test_acc = 0, 0
model_0.eval()
with torch.inference_mode():
for X, y in test_dataloader:
# 1. Forward pass
test_pred = model_0(X)
# print(test_pred)
# 2. Calculate loss (accumatively)
test_loss += loss_fn(test_pred, y)
# 3. Calculate accuracy (preds need to be same as y_true)
test_acc += accuracy_fn(y_true=y, y_pred=test_pred.argmax(dim=1))
# print(test_acc)
# Divide total loss by length of test dataloader (per batch)
test_loss /= len(test_dataloader)
# Divide total accuracy by length of test dataloader (per batch)
test_acc /= len(test_dataloader)
print(f"\nTesting for Epoch: {epoch}\n----------")
print(f"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%\n")
# Calculate training time
train_time_end_on_cpu = timer()
total_train_time_on_cpu = print_train_time(start=train_time_start_on_cpu,
end=train_time_end_on_cpu,
device=str(next(model_0.parameters()).device))Epoch 1 ---------- Loss: 2.34053 | Looked at 0/60000 samples Loss: 0.63385 | Looked at 8000/60000 samples Loss: 0.49907 | Looked at 16000/60000 samples Loss: 0.26303 | Looked at 24000/60000 samples Loss: 0.53534 | Looked at 32000/60000 samples Loss: 0.36563 | Looked at 40000/60000 samples Loss: 0.68232 | Looked at 48000/60000 samples Loss: 0.18253 | Looked at 56000/60000 samples Testing for Epoch: 0 ---------- Test loss: 0.50175 | Test accuracy: 82.47% Epoch 2 ---------- Loss: 0.57853 | Looked at 0/60000 samples Loss: 0.36582 | Looked at 8000/60000 samples Loss: 0.36852 | Looked at 16000/60000 samples Loss: 0.35338 | Looked at 24000/60000 samples Loss: 0.36890 | Looked at 32000/60000 samples Loss: 0.34529 | Looked at 40000/60000 samples Loss: 0.33107 | Looked at 48000/60000 samples Loss: 0.46185 | Looked at 56000/60000 samples Testing for Epoch: 1 ---------- Test loss: 0.52408 | Test accuracy: 81.76% Epoch 3 ---------- Loss: 0.38698 | Looked at 0/60000 samples Loss: 0.34827 | Looked at 8000/60000 samples Loss: 0.42298 | Looked at 16000/60000 samples Loss: 0.53404 | Looked at 24000/60000 samples Loss: 0.48242 | Looked at 32000/60000 samples Loss: 0.22668 | Looked at 40000/60000 samples Loss: 0.45466 | Looked at 48000/60000 samples Loss: 0.41813 | Looked at 56000/60000 samples Testing for Epoch: 2 ---------- Test loss: 0.51340 | Test accuracy: 82.92% Epoch 4 ---------- Loss: 0.37360 | Looked at 0/60000 samples Loss: 0.33119 | Looked at 8000/60000 samples Loss: 0.20297 | Looked at 16000/60000 samples Loss: 0.39649 | Looked at 24000/60000 samples Loss: 0.51343 | Looked at 32000/60000 samples Loss: 0.50143 | Looked at 40000/60000 samples Loss: 0.36421 | Looked at 48000/60000 samples Loss: 0.51659 | Looked at 56000/60000 samples Testing for Epoch: 3 ---------- Test loss: 0.47379 | Test accuracy: 83.18% Epoch 5 ---------- Loss: 0.26910 | Looked at 0/60000 samples Loss: 0.16825 | Looked at 8000/60000 samples Loss: 0.23860 | Looked at 16000/60000 samples Loss: 0.24782 | Looked at 24000/60000 samples Loss: 0.36713 | Looked at 32000/60000 samples Loss: 0.31626 | Looked at 40000/60000 samples Loss: 0.24531 | Looked at 48000/60000 samples Loss: 0.52060 | Looked at 56000/60000 samples Testing for Epoch: 4 ---------- Test loss: 0.46712 | Test accuracy: 83.57% Train time on cpu: 27.108 seconds
In [111]:
torch.manual_seed(42)
def eval_model(model, data_loader, loss_fn, accuracy_fn):
loss, acc = 0, 0
model.eval()
with torch.inference_mode():
for X, y in data_loader:
y_pred = model(X)
loss += loss_fn(y_pred, y)
acc += accuracy_fn(y_true=y, y_pred=y_pred.argmax(dim=1))
# Scale loss and acc
loss /= len(data_loader)
acc /= len(data_loader)
return {"model_name": model.__class__.__name__, # only works when model was created with a class
"model_loss": loss.item(),
"model_acc": acc}
model_0_results = eval_model(model=model_0, data_loader=test_dataloader,
loss_fn=loss_fn, accuracy_fn=accuracy_fn
)
model_0_resultsOut [111]:
{'model_name': 'FashionMNISTModelV0',
'model_loss': 0.46738308668136597,
'model_acc': 83.55630990415335}In [112]:
model_0.__class__.__name__Out [112]:
'FashionMNISTModelV0'
In [113]:
# Setup device agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
deviceOut [113]:
'cuda'
In [114]:
class FashionMNISTModelV1(nn.Module):
def __init__(self, input_shape, hidden_units, output_shape):
super().__init__()
self.layer_stack = nn.Sequential(
nn.Flatten(), # flatten inputs into single vector
nn.Linear(in_features=input_shape, out_features=hidden_units),
nn.ReLU(),
nn.Linear(in_features=hidden_units, out_features=output_shape),
nn.ReLU()
)
def forward(self, x):
return self.layer_stack(x)In [115]:
torch.manual_seed(42)
model_1 = FashionMNISTModelV1(input_shape=784,
hidden_units=128,
output_shape=len(class_names)
).to(device) # send model to GPU if it's available
next(model_1.parameters()).device # check model deviceOut [115]:
device(type='cuda', index=0)
In [116]:
from helper_functions import accuracy_fn
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model_1.parameters(), lr=0.1)In [117]:
def train_step(data_loader, model, loss_fn, optimizer):
for batch, (X, y) in enumerate(data_loader):
# Send data to GPU
X, y = X.to(device, non_blocking=True), y.to(device, non_blocking=True)
# 1. Forward pass
y_pred = model(X)
# 2. Calculate loss
loss = loss_fn(y_pred, y)
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backward
loss.backward()
# 5. Optimizer step
optimizer.step()
# Print what's happening
if batch % 250 == 0:
sample_number = batch * len(X)
print(f"Loss: {loss:.5f} | Looked at {sample_number}/{len(data_loader.dataset)} samples")
def test_step(data_loader, model, loss_fn):
test_loss, test_acc = 0, 0
model.eval() # put model in eval mode
# Turn on inference context manager
with torch.inference_mode():
for X, y in data_loader:
# Send data to GPU
X, y = X.to(device, non_blocking=True), y.to(device, non_blocking=True)
# 1. Forward pass
test_pred = model(X)
# 2. Calculate loss and accuracy
test_loss += loss_fn(test_pred, y)
test_acc += accuracy_fn(y_true=y,
y_pred=test_pred.argmax(dim=1)
)
# Adjust metrics and print out
test_loss /= len(data_loader)
test_acc /= len(data_loader)
print(f"\nTesting for Epoch: {epoch}\n----------")
print(f"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%\n")In [118]:
torch.manual_seed(42)
# Measure time
from timeit import default_timer as timer
train_time_start_on_gpu = timer()
epochs=5
for epoch in range(epochs):
print(f"Epoch: {epoch}\n---------")
train_step(data_loader=train_dataloader,
model=model_1,
loss_fn=loss_fn,
optimizer=optimizer
)
test_step(data_loader=test_dataloader,
model=model_1,
loss_fn=loss_fn
)
train_time_end_on_gpu = timer()
total_train_time_on_gpu = print_train_time(start=train_time_start_on_gpu,
end=train_time_end_on_gpu,
device=device)Epoch: 0 --------- Loss: 2.31576 | Looked at 0/60000 samples Loss: 0.84441 | Looked at 8000/60000 samples Loss: 0.72745 | Looked at 16000/60000 samples Loss: 0.48854 | Looked at 24000/60000 samples Loss: 0.48070 | Looked at 32000/60000 samples Loss: 0.34006 | Looked at 40000/60000 samples Loss: 0.60718 | Looked at 48000/60000 samples Loss: 0.17817 | Looked at 56000/60000 samples Testing for Epoch: 0 ---------- Test loss: 0.46140 | Test accuracy: 83.58% Epoch: 1 --------- Loss: 0.56453 | Looked at 0/60000 samples Loss: 0.34874 | Looked at 8000/60000 samples Loss: 0.34462 | Looked at 16000/60000 samples Loss: 0.28178 | Looked at 24000/60000 samples Loss: 0.34664 | Looked at 32000/60000 samples Loss: 0.35043 | Looked at 40000/60000 samples Loss: 0.28332 | Looked at 48000/60000 samples Loss: 0.34145 | Looked at 56000/60000 samples Testing for Epoch: 1 ---------- Test loss: 0.44406 | Test accuracy: 84.48% Epoch: 2 --------- Loss: 0.28065 | Looked at 0/60000 samples Loss: 0.27538 | Looked at 8000/60000 samples Loss: 0.32969 | Looked at 16000/60000 samples Loss: 0.50899 | Looked at 24000/60000 samples Loss: 0.35316 | Looked at 32000/60000 samples Loss: 0.20153 | Looked at 40000/60000 samples Loss: 0.30891 | Looked at 48000/60000 samples Loss: 0.33071 | Looked at 56000/60000 samples Testing for Epoch: 2 ---------- Test loss: 0.40107 | Test accuracy: 85.62% Epoch: 3 --------- Loss: 0.26100 | Looked at 0/60000 samples Loss: 0.28107 | Looked at 8000/60000 samples Loss: 0.06934 | Looked at 16000/60000 samples Loss: 0.32541 | Looked at 24000/60000 samples Loss: 0.33877 | Looked at 32000/60000 samples Loss: 0.24971 | Looked at 40000/60000 samples Loss: 0.25175 | Looked at 48000/60000 samples Loss: 0.32383 | Looked at 56000/60000 samples Testing for Epoch: 3 ---------- Test loss: 0.38116 | Test accuracy: 86.37% Epoch: 4 --------- Loss: 0.20655 | Looked at 0/60000 samples Loss: 0.18057 | Looked at 8000/60000 samples Loss: 0.14731 | Looked at 16000/60000 samples Loss: 0.17487 | Looked at 24000/60000 samples Loss: 0.35683 | Looked at 32000/60000 samples Loss: 0.25929 | Looked at 40000/60000 samples Loss: 0.19088 | Looked at 48000/60000 samples Loss: 0.46857 | Looked at 56000/60000 samples Testing for Epoch: 4 ---------- Test loss: 0.37307 | Test accuracy: 86.46% Train time on cuda: 27.904 seconds
In [119]:
torch.manual_seed(42)
#UPTOHERE
# Make sure model eval code can run on CPU...
model_1_results = eval_model(model=model_1,
data_loader=test_dataloader,
loss_fn=loss_fn,
accuracy_fn=accuracy_fn) # will error due to `eval_model()` not using device agnostic code
model_1_results [0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) [0;32m/tmp/ipykernel_5140/3686544492.py[0m in [0;36m<module>[0;34m[0m [1;32m 3[0m [0;31m#UPTOHERE[0m[0;34m[0m[0;34m[0m[0m [1;32m 4[0m [0;31m# Make sure model eval code can run on CPU...[0m[0;34m[0m[0;34m[0m[0m [0;32m----> 5[0;31m model_1_results = eval_model(model=model_1, [0m[1;32m 6[0m [0mdata_loader[0m[0;34m=[0m[0mtest_dataloader[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m [1;32m 7[0m [0mloss_fn[0m[0;34m=[0m[0mloss_fn[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m [0;32m/tmp/ipykernel_5140/1274930794.py[0m in [0;36meval_model[0;34m(model, data_loader, loss_fn, accuracy_fn)[0m [1;32m 5[0m [0;32mwith[0m [0mtorch[0m[0;34m.[0m[0minference_mode[0m[0;34m([0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 6[0m [0;32mfor[0m [0mX[0m[0;34m,[0m [0my[0m [0;32min[0m [0mdata_loader[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m----> 7[0;31m [0my_pred[0m [0;34m=[0m [0mmodel[0m[0;34m([0m[0mX[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 8[0m [0mloss[0m [0;34m+=[0m [0mloss_fn[0m[0;34m([0m[0my_pred[0m[0;34m,[0m [0my[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [1;32m 9[0m [0macc[0m [0;34m+=[0m [0maccuracy_fn[0m[0;34m([0m[0my_true[0m[0;34m=[0m[0my[0m[0;34m,[0m [0my_pred[0m[0;34m=[0m[0my_pred[0m[0;34m.[0m[0margmax[0m[0;34m([0m[0mdim[0m[0;34m=[0m[0;36m1[0m[0;34m)[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/module.py[0m in [0;36m_call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1100[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks [1;32m 1101[0m or _global_forward_hooks or _global_forward_pre_hooks): [0;32m-> 1102[0;31m [0;32mreturn[0m [0mforward_call[0m[0;34m([0m[0;34m*[0m[0minput[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1103[0m [0;31m# Do not call functions when jit is used[0m[0;34m[0m[0;34m[0m[0m [1;32m 1104[0m [0mfull_backward_hooks[0m[0;34m,[0m [0mnon_full_backward_hooks[0m [0;34m=[0m [0;34m[[0m[0;34m][0m[0;34m,[0m [0;34m[[0m[0;34m][0m[0;34m[0m[0;34m[0m[0m [0;32m/tmp/ipykernel_5140/2755272479.py[0m in [0;36mforward[0;34m(self, x)[0m [1;32m 11[0m [0;34m[0m[0m [1;32m 12[0m [0;32mdef[0m [0mforward[0m[0;34m([0m[0mself[0m[0;34m,[0m [0mx[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m---> 13[0;31m [0;32mreturn[0m [0mself[0m[0;34m.[0m[0mlayer_stack[0m[0;34m([0m[0mx[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m [0;32m~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/module.py[0m in [0;36m_call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1100[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks [1;32m 1101[0m or _global_forward_hooks or _global_forward_pre_hooks): [0;32m-> 1102[0;31m [0;32mreturn[0m [0mforward_call[0m[0;34m([0m[0;34m*[0m[0minput[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1103[0m [0;31m# Do not call functions when jit is used[0m[0;34m[0m[0;34m[0m[0m [1;32m 1104[0m [0mfull_backward_hooks[0m[0;34m,[0m [0mnon_full_backward_hooks[0m [0;34m=[0m [0;34m[[0m[0;34m][0m[0;34m,[0m [0;34m[[0m[0;34m][0m[0;34m[0m[0;34m[0m[0m [0;32m~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/container.py[0m in [0;36mforward[0;34m(self, input)[0m [1;32m 139[0m [0;32mdef[0m [0mforward[0m[0;34m([0m[0mself[0m[0;34m,[0m [0minput[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 140[0m [0;32mfor[0m [0mmodule[0m [0;32min[0m [0mself[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m--> 141[0;31m [0minput[0m [0;34m=[0m [0mmodule[0m[0;34m([0m[0minput[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 142[0m [0;32mreturn[0m [0minput[0m[0;34m[0m[0;34m[0m[0m [1;32m 143[0m [0;34m[0m[0m [0;32m~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/module.py[0m in [0;36m_call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1100[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks [1;32m 1101[0m or _global_forward_hooks or _global_forward_pre_hooks): [0;32m-> 1102[0;31m [0;32mreturn[0m [0mforward_call[0m[0;34m([0m[0;34m*[0m[0minput[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1103[0m [0;31m# Do not call functions when jit is used[0m[0;34m[0m[0;34m[0m[0m [1;32m 1104[0m [0mfull_backward_hooks[0m[0;34m,[0m [0mnon_full_backward_hooks[0m [0;34m=[0m [0;34m[[0m[0;34m][0m[0;34m,[0m [0;34m[[0m[0;34m][0m[0;34m[0m[0;34m[0m[0m [0;32m~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/linear.py[0m in [0;36mforward[0;34m(self, input)[0m [1;32m 101[0m [0;34m[0m[0m [1;32m 102[0m [0;32mdef[0m [0mforward[0m[0;34m([0m[0mself[0m[0;34m,[0m [0minput[0m[0;34m:[0m [0mTensor[0m[0;34m)[0m [0;34m->[0m [0mTensor[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m--> 103[0;31m [0;32mreturn[0m [0mF[0m[0;34m.[0m[0mlinear[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mself[0m[0;34m.[0m[0mweight[0m[0;34m,[0m [0mself[0m[0;34m.[0m[0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 104[0m [0;34m[0m[0m [1;32m 105[0m [0;32mdef[0m [0mextra_repr[0m[0;34m([0m[0mself[0m[0;34m)[0m [0;34m->[0m [0mstr[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/functional.py[0m in [0;36mlinear[0;34m(input, weight, bias)[0m [1;32m 1846[0m [0;32mif[0m [0mhas_torch_function_variadic[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 1847[0m [0;32mreturn[0m [0mhandle_torch_function[0m[0;34m([0m[0mlinear[0m[0;34m,[0m [0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m,[0m [0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m=[0m[0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m-> 1848[0;31m [0;32mreturn[0m [0mtorch[0m[0;34m.[0m[0m_C[0m[0;34m.[0m[0m_nn[0m[0;34m.[0m[0mlinear[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1849[0m [0;34m[0m[0m [1;32m 1850[0m [0;34m[0m[0m [0;31mRuntimeError[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)
In [ ]:
# Move values to device
torch.manual_seed(42)
def eval_model(model, data_loader, loss_fn, accuracy_fn):
loss, acc = 0, 0
model.eval()
with torch.inference_mode():
for X, y in data_loader:
X, y = X.to(device, non_blocking=True), y.to(device, non_blocking=True)
y_pred = model(X)
loss += loss_fn(y_pred, y)
acc += accuracy_fn(y_true=y, y_pred=y_pred.argmax(dim=1))
# Scale loss and acc
loss /= len(data_loader)
acc /= len(data_loader)
return {"model_name": model.__class__.__name__, # only works when model was created with a class
"model_loss": loss.item(),
"model_acc": acc}
model_1_results = eval_model(model=model_1, data_loader=test_dataloader,
loss_fn=loss_fn, accuracy_fn=accuracy_fn
)
model_1_results{'model_name': 'FashionMNISTModelV1',
'model_loss': 0.37321436405181885,
'model_acc': 86.46166134185303}In [ ]:
# UPTOHERE
# Write model v2 (conv net)
# Use same functions to train and evalIn [ ]:
### Model 2 line by line
class FashionMNISTModelV2(nn.Module):
"""
Model architecture copying TinyVGG from:
https://poloclub.github.io/cnn-explainer/
"""
def __init__(self, input_shape, hidden_units, output_shape):
super().__init__()
self.block_1 = nn.Sequential(
nn.Conv2d(in_channels=input_shape,
out_channels=hidden_units,
kernel_size=3,
padding=1),
nn.ReLU(),
nn.Conv2d(hidden_units,
hidden_units,
3,
padding=1),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.block_2 = nn.Sequential(
nn.Conv2d(hidden_units, hidden_units, 3, padding=1),
nn.ReLU(),
nn.Conv2d(hidden_units, hidden_units, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(in_features=hidden_units*7*7,
out_features=output_shape)
)
def forward(self, x):
x = self.block_1(x)
# print(x.shape)
x = self.block_2(x)
# print(x.shape)
x = self.classifier(x)
# print(x.shape)
return x
torch.manual_seed(42)
model_2 = FashionMNISTModelV2(input_shape=1,
hidden_units=10,
output_shape=len(class_names)).to(device)
model_2FashionMNISTModelV2(
(block_1): Sequential(
(0): Conv2d(1, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU()
(2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU()
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(block_2): Sequential(
(0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU()
(2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU()
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(classifier): Sequential(
(0): Flatten(start_dim=1, end_dim=-1)
(1): Linear(in_features=490, out_features=10, bias=True)
)
)In [ ]:
input, label = next(iter(train_dataloader))
input.shapetorch.Size([32, 1, 28, 28])
In [ ]:
# Setup loss and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model_2.parameters(), lr=0.001)In [ ]:
# Train and test model
torch.manual_seed(42)
# Measure time
from timeit import default_timer as timer
train_time_start_model_2 = timer()
epochs=5
for epoch in range(epochs):
print(f"Epoch: {epoch}\n---------")
train_step(data_loader=train_dataloader,
model=model_2,
loss_fn=loss_fn,
optimizer=optimizer
)
test_step(data_loader=test_dataloader,
model=model_2,
loss_fn=loss_fn
)
train_time_end_model_2 = timer()
total_train_time_model_2 = print_train_time(start=train_time_start_model_2,
end=train_time_end_model_2,
device=device)Epoch: 0 --------- Loss: 2.30730 | Looked at 0/60000 samples Loss: 0.62103 | Looked at 8000/60000 samples Loss: 0.38208 | Looked at 16000/60000 samples Loss: 0.25257 | Looked at 24000/60000 samples Loss: 0.48798 | Looked at 32000/60000 samples Loss: 0.28136 | Looked at 40000/60000 samples Loss: 0.49253 | Looked at 48000/60000 samples Loss: 0.13826 | Looked at 56000/60000 samples Testing for Epoch: 0 ---------- Test loss: 0.39309 | Test accuracy: 86.28% Epoch: 1 --------- Loss: 0.35944 | Looked at 0/60000 samples Loss: 0.31443 | Looked at 8000/60000 samples Loss: 0.16342 | Looked at 16000/60000 samples Loss: 0.27778 | Looked at 24000/60000 samples Loss: 0.40699 | Looked at 32000/60000 samples Loss: 0.32541 | Looked at 40000/60000 samples Loss: 0.24685 | Looked at 48000/60000 samples Loss: 0.20693 | Looked at 56000/60000 samples Testing for Epoch: 1 ---------- Test loss: 0.35872 | Test accuracy: 86.67% Epoch: 2 --------- Loss: 0.29864 | Looked at 0/60000 samples Loss: 0.27326 | Looked at 8000/60000 samples Loss: 0.34129 | Looked at 16000/60000 samples Loss: 0.55446 | Looked at 24000/60000 samples Loss: 0.27312 | Looked at 32000/60000 samples Loss: 0.11713 | Looked at 40000/60000 samples Loss: 0.35022 | Looked at 48000/60000 samples Loss: 0.35892 | Looked at 56000/60000 samples Testing for Epoch: 2 ---------- Test loss: 0.33255 | Test accuracy: 87.96% Epoch: 3 --------- Loss: 0.21655 | Looked at 0/60000 samples Loss: 0.31527 | Looked at 8000/60000 samples Loss: 0.12757 | Looked at 16000/60000 samples Loss: 0.40286 | Looked at 24000/60000 samples Loss: 0.26378 | Looked at 32000/60000 samples Loss: 0.17067 | Looked at 40000/60000 samples Loss: 0.17987 | Looked at 48000/60000 samples Loss: 0.31484 | Looked at 56000/60000 samples Testing for Epoch: 3 ---------- Test loss: 0.30930 | Test accuracy: 89.15% Epoch: 4 --------- Loss: 0.14142 | Looked at 0/60000 samples Loss: 0.16058 | Looked at 8000/60000 samples Loss: 0.11565 | Looked at 16000/60000 samples Loss: 0.14372 | Looked at 24000/60000 samples Loss: 0.40148 | Looked at 32000/60000 samples Loss: 0.25676 | Looked at 40000/60000 samples Loss: 0.15010 | Looked at 48000/60000 samples Loss: 0.63361 | Looked at 56000/60000 samples Testing for Epoch: 4 ---------- Test loss: 0.30139 | Test accuracy: 89.36% Train time on cuda: 38.946 seconds
In [ ]:
model_2_results = eval_model(
model=model_2,
data_loader=test_dataloader,
loss_fn=loss_fn,
accuracy_fn=accuracy_fn
)
model_2_results{'model_name': 'FashionMNISTModelV2',
'model_loss': 0.3016848862171173,
'model_acc': 89.3370607028754}In [ ]:
model_0_results, model_1_results, model_2_results({'model_name': 'FashionMNISTModelV0',
'model_loss': 0.46738308668136597,
'model_acc': 83.55630990415335},
{'model_name': 'FashionMNISTModelV1',
'model_loss': 0.37321436405181885,
'model_acc': 86.46166134185303},
{'model_name': 'FashionMNISTModelV2',
'model_loss': 0.3016848862171173,
'model_acc': 89.3370607028754})In [ ]:
import pandas as pd
compare_results = pd.DataFrame([model_0_results, model_1_results, model_2_results])
compare_results| model_name | model_loss | model_acc | |
|---|---|---|---|
| 0 | FashionMNISTModelV0 | 0.467383 | 83.556310 |
| 1 | FashionMNISTModelV1 | 0.373214 | 86.461661 |
| 2 | FashionMNISTModelV2 | 0.301685 | 89.337061 |
In [ ]:
compare_results.set_index("model_name")["model_acc"].plot(kind="bar", xlabel="model", ylabel="accuracy (%)");In [ ]:
def make_predictions(model, data):
preds = []
model.eval()
with torch.inference_mode():
for sample in data:
# 1. Forward pass
sample = torch.unsqueeze(sample, dim=0).to(device) # Add an extra dimension and send sample to device
pred = model(sample)
preds.append(torch.softmax(pred[0], dim=0)) # Convert to pred probabilities
# Get off GPU for further calculations
pred_probs = [pred_prob.cpu() for pred_prob in preds]
return pred_probsIn [ ]:
len(test_data)10000
In [ ]:
import random
random.seed(42)
test_samples = []
test_labels = []
for sample, label in random.sample(list(test_data), k=9):
test_samples.append(sample)
test_labels.append(label)In [ ]:
pred_probs= make_predictions(model=model_2, data=test_samples)
pred_probs[:2][tensor([5.3556e-10, 9.2350e-14, 5.6806e-11, 2.9492e-11, 1.2458e-11, 9.9918e-01,
2.0111e-08, 4.8111e-07, 5.7852e-06, 8.1268e-04]),
tensor([6.4424e-02, 7.4795e-01, 2.5071e-04, 1.3002e-01, 1.7794e-02, 3.4507e-06,
3.9502e-02, 3.0148e-06, 3.2876e-05, 1.8275e-05])]In [ ]:
pred_classes = torch.stack(pred_probs).argmax(dim=1)In [ ]:
test_labels, pred_classes([5, 1, 7, 4, 3, 0, 4, 7, 1], tensor([5, 1, 7, 4, 3, 0, 4, 7, 1]))
In [ ]:
class_names['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
In [ ]:
# Plot predictions
plt.figure(figsize=(9, 9))
nrows = 3
ncols = 3
for i, sample in enumerate(test_samples):
plt.subplot(3, 3, i+1)
plt.imshow(sample.squeeze(), cmap="gray")
pred_label = class_names[pred_classes[i]]
truth_label = class_names[test_labels[i]]
title_text = f"Pred: {pred_label} | Truth: {truth_label}"
# Check for equality and change title colour accordingly
if pred_label == truth_label:
plt.title(title_text, fontsize=10, c="g") # green text if correct
else:
plt.title(title_text, fontsize=10, c="r") # red text if wrong
plt.axis(False);In [ ]:
# See if torchmetrics exists, if not, install it
try:
import torchmetrics
except:
%pip install torchmetrics
import torchmetrics In [ ]:
import torchmetrics In [ ]:
torch.save(model_2.state_dict(), "models/03_pytorch_computer_vision_model_2.pth")In [ ]:
# Load in model state dict to new model instance (need class instance to load into)
# Note: loading model will error if the shapes here aren't the same as the saved version
loaded_model_2 = FashionMNISTModelV2(input_shape=1,
hidden_units=10, # try changing this to 128 and seeing what happens
output_shape=10)
loaded_model_2.load_state_dict(torch.load("models/03_pytorch_computer_vision_model_2.pth"))
# Send model to GPU
loaded_model_2 = loaded_model_2.to(device)In [ ]:
# Evaluate loaded model
torch.manual_seed(42)
loaded_model_2_results = eval_model(
model=loaded_model_2,
data_loader=test_dataloader,
loss_fn=loss_fn,
accuracy_fn=accuracy_fn
)
loaded_model_2_results{'model_name': 'FashionMNISTModelV2',
'model_loss': 0.30141106247901917,
'model_acc': 89.3570287539936}In [ ]:
model_2_results{'model_name': 'FashionMNISTModelV2',
'model_loss': 0.3016848862171173,
'model_acc': 89.3370607028754}In [ ]:
# Check to see if results are close to each other (if they are very far away, there may be an error)
torch.isclose(torch.tensor(model_2_results["model_loss"]),
torch.tensor(loaded_model_2_results["model_loss"]),
rtol=0.001)tensor(True)