mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
157 KiB
157 KiB
In [1]:
import torch
from torch import nnIn [2]:
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda
import matplotlib.pyplot as plt
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 [3]:
# Check out the data shapes
img, label = train_data[0]
img.shape, label # image is [1, 28, 28] and has int labelOut [3]:
(torch.Size([1, 28, 28]), 9)
In [4]:
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 [5]:
# Map labels to class names - https://github.com/zalandoresearch/fashion-mnist
# List format - https://gist.github.com/mrdbourke/e0b82c52a1b374a108a47ce21c7f4835
class_names = ["T-shirt/top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle boot"
]In [6]:
img, label = train_data[0]
plt.imshow(img.squeeze(), cmap="gray")
plt.title(class_names[label]);In [7]:
# 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 [8]:
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
)
train_dataloader, test_dataloader, len(train_dataloader), len(test_dataloader)Out [8]:
(<torch.utils.data.dataloader.DataLoader at 0x7fb53c290160>, <torch.utils.data.dataloader.DataLoader at 0x7fb53c221a90>, 1875, 313)
In [9]:
# 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 [9]:
(torch.Size([32, 1, 28, 28]), torch.Size([32]))
In [10]:
# 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 [11]:
flatten_model = nn.Sequential(nn.Flatten())
x = train_features_batch[0]
output = flatten_model(x)
x.shape, output.size()
Out [11]:
(torch.Size([1, 28, 28]), torch.Size([1, 784]))
In [12]:
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 [13]:
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_0Out [13]:
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 [14]:
# Setup loss, optimizer and accuracy metric
from helper_functions import accuracy_fn
loss_fn = nn.CrossEntropyLoss() # this is also called "criterion" in some places
optimizer = torch.optim.SGD(model_0.parameters(), lr=0.1)In [15]:
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 [16]:
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: 26.673 seconds
In [17]:
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 [17]:
{'model_name': 'FashionMNISTModelV0',
'model_loss': 0.46738308668136597,
'model_acc': 83.55630990415335}In [18]:
model_0.__class__.__name__Out [18]:
'FashionMNISTModelV0'
In [19]:
# Setup device agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
deviceOut [19]:
'cuda'
In [20]:
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 [21]:
torch.manual_seed(42)
model_1 = FashionMNISTModelV1(input_shape=784,
hidden_units=128,
output_shape=10
).to(device) # send model to GPU if it's available
next(model_1.parameters()).device # check model deviceOut [21]:
device(type='cuda', index=0)
In [22]:
from helper_functions import accuracy_fn
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model_1.parameters(), lr=0.1)In [23]:
def train(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(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 [24]:
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(data_loader=train_dataloader,
model=model_1,
loss_fn=loss_fn,
optimizer=optimizer
)
test(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: 28.596 seconds
In [25]:
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_60941/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_60941/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_60941/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 [26]:
# 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_resultsOut [26]:
{'model_name': 'FashionMNISTModelV1',
'model_loss': 0.37321436405181885,
'model_acc': 86.46166134185303}In [27]:
# UPTOHERE
# Write model v2 (conv net)
# Use same functions to train and evalIn [32]:
# 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.layer_stack = nn.Sequential(
# # nn.Flatten(), # flatten inputs into single vector
# nn.Conv2d(in_channels=1,
# out_channels=hidden_units,
# kernel_size=3),
# nn.ReLU(),
# nn.Conv2d(hidden_units,
# hidden_units,
# 3),
# nn.ReLU(),
# nn.MaxPool2d(2),
# nn.Conv2d(hidden_units, hidden_units, 3),
# nn.ReLU(),
# nn.MaxPool2d(2),
# nn.Linear(in_features=hidden_units, out_features=output_shape)
# )
# def forward(self, x):
# return self.layer_stack(x)
# model_2 = FashionMNISTModelV2(input_shape=784,
# hidden_units=128,
# output_shape=len(class_names)).to(device)
# model_2
### 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=1,
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
model_2 = FashionMNISTModelV2(input_shape=1,
hidden_units=10,
output_shape=len(class_names)).to(device)
model_2Out [32]:
FashionMNISTModelV2(
(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 [33]:
input, label = next(iter(train_dataloader))
input.shapeOut [33]:
torch.Size([32, 1, 28, 28])
In [34]:
torch.Size([32, 128, 4, 4])Out [34]:
torch.Size([32, 128, 4, 4])
In [35]:
32*128*4Out [35]:
16384
In [36]:
# Setup loss and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model_2.parameters(), lr=0.001)In [37]:
# 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(data_loader=train_dataloader,
model=model_2,
loss_fn=loss_fn,
optimizer=optimizer
)
test(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.30454 | Looked at 0/60000 samples Loss: 0.57641 | Looked at 8000/60000 samples Loss: 0.36825 | Looked at 16000/60000 samples Loss: 0.36582 | Looked at 24000/60000 samples Loss: 0.44872 | Looked at 32000/60000 samples Loss: 0.24972 | Looked at 40000/60000 samples Loss: 0.57585 | Looked at 48000/60000 samples Loss: 0.10089 | Looked at 56000/60000 samples Testing for Epoch: 0 ---------- Test loss: 0.38344 | Test accuracy: 86.22% Epoch: 1 --------- Loss: 0.36397 | Looked at 0/60000 samples Loss: 0.29526 | Looked at 8000/60000 samples Loss: 0.24492 | Looked at 16000/60000 samples Loss: 0.30383 | Looked at 24000/60000 samples Loss: 0.31548 | Looked at 32000/60000 samples Loss: 0.24291 | Looked at 40000/60000 samples Loss: 0.20189 | Looked at 48000/60000 samples Loss: 0.21553 | Looked at 56000/60000 samples Testing for Epoch: 1 ---------- Test loss: 0.35467 | Test accuracy: 86.94% Epoch: 2 --------- Loss: 0.27195 | Looked at 0/60000 samples Loss: 0.23987 | Looked at 8000/60000 samples Loss: 0.28975 | Looked at 16000/60000 samples Loss: 0.39636 | Looked at 24000/60000 samples Loss: 0.24336 | Looked at 32000/60000 samples Loss: 0.09933 | Looked at 40000/60000 samples Loss: 0.21368 | Looked at 48000/60000 samples Loss: 0.36726 | Looked at 56000/60000 samples Testing for Epoch: 2 ---------- Test loss: 0.30670 | Test accuracy: 89.16% Epoch: 3 --------- Loss: 0.17519 | Looked at 0/60000 samples Loss: 0.31724 | Looked at 8000/60000 samples Loss: 0.07558 | Looked at 16000/60000 samples Loss: 0.34291 | Looked at 24000/60000 samples Loss: 0.26814 | Looked at 32000/60000 samples Loss: 0.12187 | Looked at 40000/60000 samples Loss: 0.12363 | Looked at 48000/60000 samples Loss: 0.29629 | Looked at 56000/60000 samples Testing for Epoch: 3 ---------- Test loss: 0.28936 | Test accuracy: 89.63% Epoch: 4 --------- Loss: 0.09023 | Looked at 0/60000 samples Loss: 0.14286 | Looked at 8000/60000 samples Loss: 0.15002 | Looked at 16000/60000 samples Loss: 0.27805 | Looked at 24000/60000 samples Loss: 0.36720 | Looked at 32000/60000 samples Loss: 0.25269 | Looked at 40000/60000 samples Loss: 0.11466 | Looked at 48000/60000 samples Loss: 0.77091 | Looked at 56000/60000 samples Testing for Epoch: 4 ---------- Test loss: 0.27614 | Test accuracy: 89.97% Train time on cuda: 38.961 seconds
In [38]:
model_2_results = eval_model(
model=model_2,
data_loader=test_dataloader,
loss_fn=loss_fn,
accuracy_fn=accuracy_fn
)
model_2_resultsOut [38]:
{'model_name': 'FashionMNISTModelV2',
'model_loss': 0.27648669481277466,
'model_acc': 89.94608626198082}In [39]:
model_0_results, model_1_results, model_2_resultsOut [39]:
({'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.27648669481277466,
'model_acc': 89.94608626198082})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.223272 | 92.092652 |
In [ ]:
compare_results["model_acc"].plot(kind="bar")<AxesSubplot:>
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([1.8396e-12, 1.5738e-18, 5.4805e-12, 9.7204e-18, 1.9830e-14, 1.0000e+00,
3.4461e-12, 3.7136e-11, 5.5659e-13, 5.0743e-08]),
tensor([6.6449e-03, 9.8245e-01, 8.2975e-04, 1.7679e-03, 4.6107e-03, 7.3583e-05,
3.5653e-03, 2.4977e-06, 2.5370e-05, 2.5053e-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")
plt.title(f"Pred: {class_names[pred_classes[i]]} | Truth: {class_names[test_labels[i]]}")
plt.axis(False);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)
loaded_model_2 = FashionMNISTModelV2(input_shape=1, hidden_units=128, 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.223284050822258,
'model_acc': 92.0826677316294}In [ ]:
model_2_results{'model_name': 'FashionMNISTModelV2',
'model_loss': 0.22327210009098053,
'model_acc': 92.09265175718849}In [ ]:
# Check to see if results are close
torch.isclose(torch.tensor(model_2_results["model_loss"]),
torch.tensor(loaded_model_2_results["model_loss"]),
rtol=0.0001)tensor(True)