mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
2.7 MiB
2.7 MiB
In [1]:
import torch
from torch import nn
# Note: PyTorch 1.10.0+ is required for this course
torch.__version__Out [1]:
'1.11.0+cu113'
In [2]:
# Setup device-agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
deviceOut [2]:
'cuda'
In [3]:
!nvidia-smiThu Apr 28 02:21:26 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 Tesla P100-PCIE... Off | 00000000:00:04.0 Off | 0 |
| N/A 44C P0 28W / 250W | 2MiB / 16280MiB | 0% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| No running processes found |
+-----------------------------------------------------------------------------+
In [4]:
import requests
import zipfile
from pathlib import Path
# Setup path to a data folder
data_path = Path("data/")
image_path = data_path / "pizza_steak_sushi"
# If the image folder doesn't exist, download it and prepare it...
if image_path.is_dir():
print(f"{image_path} directory already exists... skipping download")
else:
print(f"{image_path} does not exist, creating one...")
image_path.mkdir(parents=True, exist_ok=True)
# Download pizza, steak and suhsi data
with open(data_path / "pizza_steak_sushi.zip", "wb") as f:
request = requests.get("https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip")
print("Downloading pizza, steak, suhsi data...")
f.write(request.content)
# Unzip pizza, steak, sushi data
with zipfile.ZipFile(data_path / "pizza_steak_sushi.zip", "r") as zip_ref:
print("Unzipping pizza, steak and sushi data...")
zip_ref.extractall(image_path)data/pizza_steak_sushi does not exist, creating one... Downloading pizza, steak, suhsi data... Unzipping pizza, steak and sushi data...
In [5]:
import os
def walk_through_dir(dir_path):
"""Walks through dir_path returning its contents."""
for dirpath, dirnames, filenames in os.walk(dir_path):
print(f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.")In [6]:
walk_through_dir(image_path)There are 2 directories and 0 images in 'data/pizza_steak_sushi'. There are 3 directories and 0 images in 'data/pizza_steak_sushi/test'. There are 0 directories and 31 images in 'data/pizza_steak_sushi/test/sushi'. There are 0 directories and 19 images in 'data/pizza_steak_sushi/test/steak'. There are 0 directories and 25 images in 'data/pizza_steak_sushi/test/pizza'. There are 3 directories and 0 images in 'data/pizza_steak_sushi/train'. There are 0 directories and 72 images in 'data/pizza_steak_sushi/train/sushi'. There are 0 directories and 75 images in 'data/pizza_steak_sushi/train/steak'. There are 0 directories and 78 images in 'data/pizza_steak_sushi/train/pizza'.
In [7]:
# Setup train and testing paths
train_dir = image_path / "train"
test_dir = image_path / "test"
train_dir, test_dirOut [7]:
(PosixPath('data/pizza_steak_sushi/train'),
PosixPath('data/pizza_steak_sushi/test'))In [8]:
image_pathOut [8]:
PosixPath('data/pizza_steak_sushi')In [9]:
# /content/data/pizza_steak_sushiIn [10]:
import random
from PIL import Image
# Set seed
# random.seed(42)
# 1. Get all image paths
image_path_list = list(image_path.glob("*/*/*.jpg"))
# 2. Pick a random image path
random_image_path = random.choice(image_path_list)
# 3. Get image class from path name (the image class is the name of the directory where the image is stored)
image_class = random_image_path.parent.stem
# 4. Open image
img = Image.open(random_image_path)
# 5. Print metadata
print(f"Random image path: {random_image_path}")
print(f"Image class: {image_class}")
print(f"Image height: {img.height}")
print(f"Image width: {img.width}")
imgOut [10]:
Random image path: data/pizza_steak_sushi/train/steak/1615395.jpg Image class: steak Image height: 384 Image width: 512
In [11]:
import numpy as np
import matplotlib.pyplot as plt
# Turn the image into an array
img_as_array = np.asarray(img)
# Plot the image with matplotlib
plt.figure(figsize=(10, 7))
plt.imshow(img_as_array)
plt.title(f"Image class: {image_class} | Image shape: {img_as_array.shape} -> [height, width, color_channels] (HWC)")
plt.axis(False);In [12]:
img_as_arrayOut [12]:
array([[[ 17, 12, 16],
[ 16, 11, 15],
[ 14, 9, 13],
...,
[ 29, 14, 9],
[ 26, 12, 9],
[ 24, 10, 9]],
[[ 16, 11, 17],
[ 15, 10, 16],
[ 14, 9, 15],
...,
[ 26, 10, 10],
[ 24, 10, 9],
[ 23, 9, 9]],
[[ 15, 10, 17],
[ 15, 10, 17],
[ 14, 9, 16],
...,
[ 25, 9, 12],
[ 22, 7, 12],
[ 21, 6, 11]],
...,
[[134, 125, 66],
[136, 126, 67],
[141, 126, 69],
...,
[ 39, 62, 76],
[ 37, 63, 78],
[ 34, 62, 76]],
[[135, 126, 67],
[135, 124, 68],
[137, 122, 67],
...,
[ 37, 60, 74],
[ 33, 61, 75],
[ 30, 58, 72]],
[[141, 132, 75],
[138, 127, 71],
[138, 123, 68],
...,
[ 37, 60, 74],
[ 31, 59, 73],
[ 28, 56, 70]]], dtype=uint8)In [13]:
import torch
from torch.utils.data import DataLoader
from torchvision import datasets, transformsIn [14]:
# Write a transform for image
data_transform = transforms.Compose([
# Resize our images to 64x64
transforms.Resize(size=(64, 64)),
# Flip the images randomly on the horizontal
transforms.RandomHorizontalFlip(p=0.5),
# Turn the image into a torch.Tensor
transforms.ToTensor()
])In [15]:
data_transform(img).shapeOut [15]:
torch.Size([3, 64, 64])
In [16]:
def plot_transformed_images(image_paths: list, transform, n=3, seed=None):
"""
Selects random images from a path of images and loads/transforms
them then plots the original vs the transformed version.
"""
if seed:
random.seed(seed)
random_image_paths = random.sample(image_paths, k=n)
for image_path in random_image_paths:
with Image.open(image_path) as f:
fig, ax = plt.subplots(nrows=1, ncols=2)
ax[0].imshow(f)
ax[0].set_title(f"Original\nSize: {f.size}")
ax[0].axis(False)
# Transform and plot target image
transformed_image = transform(f).permute(1, 2, 0) # note we will need to change shape for matplotlib (C, H, W) -> (H, W, C)
ax[1].imshow(transformed_image)
ax[1].set_title(f"Transformed\nShape: {transformed_image.shape}")
ax[1].axis("off")
fig.suptitle(f"Class: {image_path.parent.stem}", fontsize=16)
plot_transformed_images(image_paths=image_path_list,
transform=data_transform,
n=3,
seed=None)In [17]:
# Use ImageFolder to create dataset(s)
from torchvision import datasets
train_data = datasets.ImageFolder(root=train_dir,
transform=data_transform, # a transform for the data
target_transform=None) # a transform for the label/target
test_data = datasets.ImageFolder(root=test_dir,
transform=data_transform)
train_data, test_dataOut [17]:
(Dataset ImageFolder
Number of datapoints: 225
Root location: data/pizza_steak_sushi/train
StandardTransform
Transform: Compose(
Resize(size=(64, 64), interpolation=bilinear, max_size=None, antialias=None)
RandomHorizontalFlip(p=0.5)
ToTensor()
), Dataset ImageFolder
Number of datapoints: 75
Root location: data/pizza_steak_sushi/test
StandardTransform
Transform: Compose(
Resize(size=(64, 64), interpolation=bilinear, max_size=None, antialias=None)
RandomHorizontalFlip(p=0.5)
ToTensor()
))In [18]:
train_dir, test_dirOut [18]:
(PosixPath('data/pizza_steak_sushi/train'),
PosixPath('data/pizza_steak_sushi/test'))In [19]:
# Get class names as list
class_names = train_data.classes
class_namesOut [19]:
['pizza', 'steak', 'sushi']
In [20]:
# Get class names as dict
class_dict = train_data.class_to_idx
class_dictOut [20]:
{'pizza': 0, 'steak': 1, 'sushi': 2}In [21]:
# Check the lengths of our dataset
len(train_data), len(test_data)Out [21]:
(225, 75)
In [22]:
train_data.samples[0]Out [22]:
('data/pizza_steak_sushi/train/pizza/1008844.jpg', 0)In [23]:
# Index on the train_data Dataset to get a single image and label
img, label = train_data[0][0], train_data[0][1]
print(f"Image tensor:\n {img}")
print(f"Image shape: {img.shape}")
print(f"Image datatype: {img.dtype}")
print(f"Image label: {label}")
print(f"Label datatype: {type(label)}")Image tensor:
tensor([[[0.1137, 0.1020, 0.0980, ..., 0.1255, 0.1216, 0.1176],
[0.1059, 0.0980, 0.0980, ..., 0.1294, 0.1294, 0.1294],
[0.1020, 0.0980, 0.0941, ..., 0.1333, 0.1333, 0.1333],
...,
[0.1098, 0.1098, 0.1255, ..., 0.1686, 0.1647, 0.1686],
[0.0863, 0.0941, 0.1098, ..., 0.1686, 0.1647, 0.1686],
[0.0863, 0.0863, 0.0980, ..., 0.1686, 0.1647, 0.1647]],
[[0.0745, 0.0706, 0.0745, ..., 0.0588, 0.0588, 0.0588],
[0.0706, 0.0706, 0.0745, ..., 0.0627, 0.0627, 0.0627],
[0.0706, 0.0745, 0.0745, ..., 0.0706, 0.0706, 0.0706],
...,
[0.1255, 0.1333, 0.1373, ..., 0.2510, 0.2392, 0.2392],
[0.1098, 0.1176, 0.1255, ..., 0.2510, 0.2392, 0.2314],
[0.1020, 0.1059, 0.1137, ..., 0.2431, 0.2353, 0.2275]],
[[0.0941, 0.0902, 0.0902, ..., 0.0196, 0.0196, 0.0196],
[0.0902, 0.0863, 0.0902, ..., 0.0196, 0.0157, 0.0196],
[0.0902, 0.0902, 0.0902, ..., 0.0157, 0.0157, 0.0196],
...,
[0.1294, 0.1333, 0.1490, ..., 0.1961, 0.1882, 0.1804],
[0.1098, 0.1137, 0.1255, ..., 0.1922, 0.1843, 0.1804],
[0.1059, 0.1020, 0.1059, ..., 0.1843, 0.1804, 0.1765]]])
Image shape: torch.Size([3, 64, 64])
Image datatype: torch.float32
Image label: 0
Label datatype: <class 'int'>
In [24]:
# Rearrange the order dimensions
img_permute = img.permute(1, 2, 0)
# Print out different shapes
print(f"Original shape: {img.shape} -> [color_channels, height, width]")
print(f"Image permute: {img_permute.shape} -> [height, width, color_channels]")
# Plot the image
plt.figure(figsize=(10, 7))
plt.imshow(img_permute)
plt.axis("off")
plt.title(class_names[label], fontsize=14)Out [24]:
Original shape: torch.Size([3, 64, 64]) -> [color_channels, height, width] Image permute: torch.Size([64, 64, 3]) -> [height, width, color_channels]
Text(0.5, 1.0, 'pizza')
In [25]:
import os
os.cpu_count()Out [25]:
2
In [26]:
# Turn train and test datasets into DataLoader's
from torch.utils.data import DataLoader
BATCH_SIZE=1
train_dataloader = DataLoader(dataset=train_data,
batch_size=BATCH_SIZE,
num_workers=1,
shuffle=True)
test_dataloader = DataLoader(dataset=test_data,
batch_size=BATCH_SIZE,
num_workers=1,
shuffle=False)
train_dataloader, test_dataloaderOut [26]:
(<torch.utils.data.dataloader.DataLoader at 0x7f2a1bf8b490>, <torch.utils.data.dataloader.DataLoader at 0x7f2a1bf8bb50>)
In [27]:
len(train_dataloader), len(test_dataloader)Out [27]:
(225, 75)
In [28]:
img, label = next(iter(train_dataloader))
# Batch size will now be 1, you can change the batch size if you like
print(f"Image shape: {img.shape} -> [batch_size, color_channels, height, width]")
print(f"Label shape: {label.shape}")Image shape: torch.Size([1, 3, 64, 64]) -> [batch_size, color_channels, height, width] Label shape: torch.Size([1])
In [29]:
import os
import pathlib
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from typing import Tuple, Dict, ListIn [30]:
# Instance of torchvision.datasets.ImageFolder()
train_data.classes, train_data.class_to_idxOut [30]:
(['pizza', 'steak', 'sushi'], {'pizza': 0, 'steak': 1, 'sushi': 2})In [31]:
# Setup path for target directory
target_directory = train_dir
print(f"Target dir: {target_directory}")
# Get the class names from the target directory
class_names_found = sorted([entry.name for entry in list(os.scandir(target_directory))])
class_names_foundOut [31]:
Target dir: data/pizza_steak_sushi/train
['pizza', 'steak', 'sushi']
In [32]:
list(os.scandir(target_directory))Out [32]:
[<DirEntry 'sushi'>, <DirEntry 'steak'>, <DirEntry 'pizza'>]
In [33]:
def find_classes(directory: str) -> Tuple[List[str], Dict[str, int]]:
"""Finds the class folder names in a target directory."""
# 1. Get the class names by scanning the target directory
classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir())
# 2. Raise an error if class names could not be found
if not classes:
raise FileNotFoundError(f"Couldn't find any classes in {directory}... please check file structure.")
# 3. Create a dictionary of index labels (computers prefer numbers rather than strings as labels)
class_to_idx = {class_name: i for i, class_name in enumerate(classes)}
return classes, class_to_idxIn [34]:
find_classes(target_directory)Out [34]:
(['pizza', 'steak', 'sushi'], {'pizza': 0, 'steak': 1, 'sushi': 2})In [35]:
# 0. Write a custom dataset class
from torch.utils.data import Dataset
# 1. Subclass torch.utils.data.Dataset
class ImageFolderCustom(Dataset):
# 2. Initialize our custom dataset
def __init__(self,
targ_dir: str,
transform=None):
# 3. Create class attributes
# Get all of the image paths
self.paths = list(pathlib.Path(targ_dir).glob("*/*.jpg"))
# Setup transform
self.transform = transform
# Create classes and class_to_idx attributes
self.classes, self.class_to_idx = find_classes(targ_dir)
# 4. Create a function to load images
def load_image(self, index: int) -> Image.Image:
"Opens an image via a path and returns it."
image_path = self.paths[index]
return Image.open(image_path)
# 5. Overwrite __len__()
def __len__(self) -> int:
"Returns the total number of samples."
return len(self.paths)
# 6. Overwrite __getitem__() method to return a particular sample
def __getitem__(self, index: int) -> Tuple[torch.Tensor, int]:
"Returns one sample of data, data and label (X, y)."
img = self.load_image(index)
class_name = self.paths[index].parent.name # expects path in format: data_folder/class_name/image.jpg
class_idx = self.class_to_idx[class_name]
# Transform if necessary
if self.transform:
return self.transform(img), class_idx # return data, label (X, y)
else:
return img, class_idx # return untransformed image and labelIn [36]:
img, label = train_data[0]In [37]:
img, labelOut [37]:
(tensor([[[0.1176, 0.1216, 0.1255, ..., 0.0980, 0.1020, 0.1137],
[0.1294, 0.1294, 0.1294, ..., 0.0980, 0.0980, 0.1059],
[0.1333, 0.1333, 0.1333, ..., 0.0941, 0.0980, 0.1020],
...,
[0.1686, 0.1647, 0.1686, ..., 0.1255, 0.1098, 0.1098],
[0.1686, 0.1647, 0.1686, ..., 0.1098, 0.0941, 0.0863],
[0.1647, 0.1647, 0.1686, ..., 0.0980, 0.0863, 0.0863]],
[[0.0588, 0.0588, 0.0588, ..., 0.0745, 0.0706, 0.0745],
[0.0627, 0.0627, 0.0627, ..., 0.0745, 0.0706, 0.0706],
[0.0706, 0.0706, 0.0706, ..., 0.0745, 0.0745, 0.0706],
...,
[0.2392, 0.2392, 0.2510, ..., 0.1373, 0.1333, 0.1255],
[0.2314, 0.2392, 0.2510, ..., 0.1255, 0.1176, 0.1098],
[0.2275, 0.2353, 0.2431, ..., 0.1137, 0.1059, 0.1020]],
[[0.0196, 0.0196, 0.0196, ..., 0.0902, 0.0902, 0.0941],
[0.0196, 0.0157, 0.0196, ..., 0.0902, 0.0863, 0.0902],
[0.0196, 0.0157, 0.0157, ..., 0.0902, 0.0902, 0.0902],
...,
[0.1804, 0.1882, 0.1961, ..., 0.1490, 0.1333, 0.1294],
[0.1804, 0.1843, 0.1922, ..., 0.1255, 0.1137, 0.1098],
[0.1765, 0.1804, 0.1843, ..., 0.1059, 0.1020, 0.1059]]]), 0)In [38]:
# Create a transform
from torchvision import transforms
train_transforms = transforms.Compose([
transforms.Resize(size=(64, 64)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor()
])
test_transforms = transforms.Compose([
transforms.Resize(size=(64, 64)),
transforms.ToTensor()
])In [39]:
# Test out ImageFolderCustom
train_data_custom = ImageFolderCustom(targ_dir=train_dir,
transform=train_transforms)
test_data_custom = ImageFolderCustom(targ_dir=test_dir,
transform=test_transforms)In [40]:
train_data_custom, test_data_customOut [40]:
(<__main__.ImageFolderCustom at 0x7f2a1c032590>, <__main__.ImageFolderCustom at 0x7f2a1c032990>)
In [41]:
len(train_data), len(train_data_custom)Out [41]:
(225, 225)
In [42]:
len(test_data), len(test_data_custom)Out [42]:
(75, 75)
In [43]:
train_data_custom.classesOut [43]:
['pizza', 'steak', 'sushi']
In [44]:
train_data_custom.class_to_idxOut [44]:
{'pizza': 0, 'steak': 1, 'sushi': 2}In [45]:
# Check for equality between original ImageFolder Dataset and ImageFolderCustom Dataset
print(train_data_custom.classes==train_data.classes)
print(test_data_custom.classes==test_data.classes)True True
In [46]:
# 1. Create a function to take in a dataset
def display_random_images(dataset: torch.utils.data.Dataset,
classes: List[str] = None,
n: int = 10,
display_shape: bool = True,
seed: int = None):
# 2. Adjust display if n is too high
if n > 10:
n = 10
display_shape = False
print(f"For display, purposes, n shouldn't be larger than 10, setting to 10 and removing shape display.")
# 3. Set the seed
if seed:
random.seed(seed)
# 4. Get random sample indexes
random_samples_idx = random.sample(range(len(dataset)), k=n)
# 5. Setup plot
plt.figure(figsize=(16, 8))
# 6. Loop through random indexes and plot them with matplotlib
for i, targ_sample in enumerate(random_samples_idx):
targ_image, targ_label = dataset[targ_sample][0], dataset[targ_sample][1]
# 7. Adjust tensor dimensions for plotting
targ_image_adjust = targ_image.permute(1, 2, 0) # [color_channels, height, width] -> [height, width, color_channels]
# Plot adjusted samples
plt.subplot(1, n, i+1)
plt.imshow(targ_image_adjust)
plt.axis("off")
if classes:
title = f"Class: {classes[targ_label]}"
if display_shape:
title = title + f"\nshape: {targ_image_adjust.shape}"
plt.title(title) In [47]:
# Display random images from the ImageFolder created Dataset
display_random_images(train_data,
n=5,
classes=class_names,
seed=None)In [48]:
# Display random images from the ImageFolderCustom Dataset
display_random_images(train_data_custom,
n=5,
classes=class_names,
seed=None)In [49]:
from torch.utils.data import DataLoader
BATCH_SIZE = 1
NUM_WORKERS = os.cpu_count()
train_dataloader_custom = DataLoader(dataset=train_data_custom,
batch_size=BATCH_SIZE,
num_workers=NUM_WORKERS,
shuffle=True)
test_dataloader_custom = DataLoader(dataset=test_data_custom,
batch_size=BATCH_SIZE,
num_workers=NUM_WORKERS,
shuffle=False)
train_dataloader_custom, test_dataloader_customOut [49]:
(<torch.utils.data.dataloader.DataLoader at 0x7f2a1b61aa10>, <torch.utils.data.dataloader.DataLoader at 0x7f2a1b61aed0>)
In [50]:
# Get image and label from custom datloader
img_custom, label_custom = next(iter(train_dataloader_custom))
# Print out the shapes
img_custom.shape, label_custom.shapeOut [50]:
(torch.Size([1, 3, 64, 64]), torch.Size([1]))
In [51]:
# Let's look at trivailaugment - https://pytorch.org/vision/stable/auto_examples/plot_transforms.html#trivialaugmentwide
from torchvision import transforms
train_transform = transforms.Compose([
transforms.Resize(size=(224, 224)),
transforms.TrivialAugmentWide(num_magnitude_bins=31),
transforms.ToTensor()
])
test_transform = transforms.Compose([
transforms.Resize(size=(224, 224)),
transforms.ToTensor()
])In [52]:
image_pathOut [52]:
PosixPath('data/pizza_steak_sushi')In [53]:
# Get all image paths
image_path_list = list(image_path.glob("*/*/*.jpg"))
image_path_list[:10]Out [53]:
[PosixPath('data/pizza_steak_sushi/test/sushi/2521706.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/499605.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/988559.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/1987407.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/1172255.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/479711.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/1742201.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/1230335.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/3837522.jpg'),
PosixPath('data/pizza_steak_sushi/test/sushi/207578.jpg')]In [54]:
# Plot random transformed images
plot_transformed_images(
image_paths=image_path_list,
transform=train_transform,
n=3,
seed=None
)In [55]:
# Create simple transform
simple_transform = transforms.Compose([
transforms.Resize(size=(64, 64)),
transforms.ToTensor()
])In [56]:
# 1. Load and transform data
from torchvision import datasets
train_data_simple = datasets.ImageFolder(root=train_dir,
transform=simple_transform)
test_data_simple = datasets.ImageFolder(root=test_dir,
transform=simple_transform)
# 2. Turn the datasets into DataLoaders
import os
from torch.utils.data import DataLoader
# Setup batch size and number of works
BATCH_SIZE = 32
NUM_WORKERS = os.cpu_count()
# Create DataLoader's
train_dataloader_simple = DataLoader(dataset=train_data_simple,
batch_size=BATCH_SIZE,
shuffle=True,
num_workers=NUM_WORKERS)
test_dataloader_simple = DataLoader(dataset=test_data_simple,
batch_size=BATCH_SIZE,
shuffle=False,
num_workers=NUM_WORKERS)In [57]:
class TinyVGG(nn.Module):
"""
Model architecture copying TinyVGG from CNN Explainer: https://poloclub.github.io/cnn-explainer/
"""
def __init__(self,
input_shape: int,
hidden_units: int,
output_shape: int) -> None:
super().__init__()
self.conv_block_1 = nn.Sequential(
nn.Conv2d(in_channels=input_shape,
out_channels=hidden_units,
kernel_size=3,
stride=1,
padding=0),
nn.ReLU(),
nn.Conv2d(in_channels=hidden_units,
out_channels=hidden_units,
kernel_size=3,
stride=1,
padding=0),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,
stride=2) # default stride value is same as kernel_size
)
self.conv_block_2 = nn.Sequential(
nn.Conv2d(in_channels=hidden_units,
out_channels=hidden_units,
kernel_size=3,
stride=1,
padding=0),
nn.ReLU(),
nn.Conv2d(in_channels=hidden_units,
out_channels=hidden_units,
kernel_size=3,
stride=1,
padding=0),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,
stride=2) # default stride value is same as kernel_size
)
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(in_features=hidden_units*13*13,
out_features=output_shape)
)
def forward(self, x):
x = self.conv_block_1(x)
# print(x.shape)
x = self.conv_block_2(x)
# print(x.shape)
x = self.classifier(x)
# print(x.shape)
return x
# return self.classifier(self.conv_block_2(self.conv_block_1(x))) # benefits from operator fusion: https://horace.io/brrr_intro.htmlIn [58]:
torch.manual_seed(42)
model_0 = TinyVGG(input_shape=3, # number of color channels in our image data
hidden_units=10,
output_shape=len(class_names)).to(device)
model_0Out [58]:
TinyVGG(
(conv_block_1): Sequential(
(0): Conv2d(3, 10, kernel_size=(3, 3), stride=(1, 1))
(1): ReLU()
(2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
(3): ReLU()
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(conv_block_2): Sequential(
(0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
(1): ReLU()
(2): Conv2d(10, 10, kernel_size=(3, 3), stride=(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=1690, out_features=3, bias=True)
)
)In [59]:
# Get a single image batch
image_batch, label_batch = next(iter(train_dataloader_simple))
image_batch.shape, label_batch.shapeOut [59]:
(torch.Size([32, 3, 64, 64]), torch.Size([32]))
In [60]:
# Try a forward pass
model_0(image_batch.to(device))Out [60]:
tensor([[ 2.0789e-02, -1.9351e-03, 9.5318e-03],
[ 1.8427e-02, 2.4670e-03, 6.6757e-03],
[ 1.7699e-02, 1.0262e-03, 9.4657e-03],
[ 2.4441e-02, -3.3526e-03, 9.6011e-03],
[ 1.9930e-02, 6.6316e-04, 1.0779e-02],
[ 2.1281e-02, 2.0434e-03, 5.0046e-03],
[ 2.0999e-02, 1.2870e-04, 1.2473e-02],
[ 2.1577e-02, -1.9507e-03, 9.6941e-03],
[ 2.4504e-02, -4.7745e-03, 8.5280e-03],
[ 2.0252e-02, -4.7293e-04, 1.0908e-02],
[ 2.2215e-02, -4.1837e-04, 9.8123e-03],
[ 2.2313e-02, -2.1622e-03, 9.4455e-03],
[ 2.1841e-02, -3.7132e-03, 8.3783e-03],
[ 2.2863e-02, -1.7723e-03, 1.0287e-02],
[ 2.1647e-02, -4.4139e-03, 9.5022e-03],
[ 2.2096e-02, -4.1426e-03, 9.3853e-03],
[ 2.1209e-02, -4.4219e-03, 1.1475e-02],
[ 2.1711e-02, -2.7656e-03, 8.5006e-03],
[ 1.9951e-02, 2.8268e-05, 8.4380e-03],
[ 1.8298e-02, 1.6306e-03, 8.5499e-03],
[ 2.0768e-02, 1.7942e-03, 7.9412e-03],
[ 1.9834e-02, -3.9071e-03, 9.8740e-03],
[ 2.0893e-02, 1.3043e-04, 8.4190e-03],
[ 2.3202e-02, -3.4329e-03, 9.4937e-03],
[ 2.0501e-02, -2.5545e-03, 8.4874e-03],
[ 1.8145e-02, 2.0844e-03, 8.2223e-03],
[ 2.0304e-02, -1.7637e-03, 7.8751e-03],
[ 1.7263e-02, -3.3585e-04, 1.2474e-02],
[ 1.8347e-02, -1.5215e-03, 9.4640e-03],
[ 1.9868e-02, -2.3248e-03, 9.0062e-03],
[ 2.2065e-02, -4.6434e-03, 1.2666e-02],
[ 1.8059e-02, 2.6858e-03, 5.7899e-03]], device='cuda:0',
grad_fn=<AddmmBackward0>)In [61]:
# Install torchinfo, import if it's available
try:
import torchinfo
except:
!pip install torchinfo
import torchinfo
from torchinfo import summary
summary(model_0, input_size=[1, 3, 64, 64])Out [61]:
Collecting torchinfo Downloading torchinfo-1.6.5-py3-none-any.whl (21 kB) Installing collected packages: torchinfo Successfully installed torchinfo-1.6.5
========================================================================================== Layer (type:depth-idx) Output Shape Param # ========================================================================================== TinyVGG -- -- ├─Sequential: 1-1 [1, 10, 30, 30] -- │ └─Conv2d: 2-1 [1, 10, 62, 62] 280 │ └─ReLU: 2-2 [1, 10, 62, 62] -- │ └─Conv2d: 2-3 [1, 10, 60, 60] 910 │ └─ReLU: 2-4 [1, 10, 60, 60] -- │ └─MaxPool2d: 2-5 [1, 10, 30, 30] -- ├─Sequential: 1-2 [1, 10, 13, 13] -- │ └─Conv2d: 2-6 [1, 10, 28, 28] 910 │ └─ReLU: 2-7 [1, 10, 28, 28] -- │ └─Conv2d: 2-8 [1, 10, 26, 26] 910 │ └─ReLU: 2-9 [1, 10, 26, 26] -- │ └─MaxPool2d: 2-10 [1, 10, 13, 13] -- ├─Sequential: 1-3 [1, 3] -- │ └─Flatten: 2-11 [1, 1690] -- │ └─Linear: 2-12 [1, 3] 5,073 ========================================================================================== Total params: 8,083 Trainable params: 8,083 Non-trainable params: 0 Total mult-adds (M): 5.69 ========================================================================================== Input size (MB): 0.05 Forward/backward pass size (MB): 0.71 Params size (MB): 0.03 Estimated Total Size (MB): 0.79 ==========================================================================================
In [62]:
# Create train_step()
def train_step(model: torch.nn.Module,
dataloader: torch.utils.data.DataLoader,
loss_fn: torch.nn.Module,
optimizer:torch.optim.Optimizer,
device=device):
# Put the model in train mode
model.train()
# Setup train loss and train accuracy values
train_loss, train_acc = 0, 0
# Loop through data loader data batches
for batch, (X, y) in enumerate(dataloader):
# Send data to the target device
X, y = X.to(device), y.to(device)
# 1. Forward pass
y_pred = model(X) # output model logits
# 2. Calculate the loss
loss = loss_fn(y_pred, y)
train_loss += loss.item()
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backward
loss.backward()
# 5. Optimizer step
optimizer.step()
# Calculate accuracy metric
y_pred_class = torch.argmax(torch.softmax(y_pred, dim=1), dim=1)
train_acc += (y_pred_class==y).sum().item()/len(y_pred)
# Adjust metrics to get average loss and accuracy per batch
train_loss = train_loss / len(dataloader)
train_acc = train_acc / len(dataloader)
return train_loss, train_acc In [63]:
# Create a test step
def test_step(model: torch.nn.Module,
dataloader: torch.utils.data.DataLoader,
loss_fn: torch.nn.Module,
device=device):
# Put model in eval mode
model.eval()
# Setup test loss and test accuracy values
test_loss, test_acc = 0, 0
# Turn on inference mode
with torch.inference_mode():
# Loop through DataLoader batches
for batch, (X, y) in enumerate(dataloader):
# Send data to the target device
X, y = X.to(device), y.to(device)
# 1. Forward pass
test_pred_logits = model(X)
# 2. Calculate the loss
loss = loss_fn(test_pred_logits, y)
test_loss += loss.item()
# Calculate the accuracy
test_pred_labels = test_pred_logits.argmax(dim=1)
test_acc += ((test_pred_labels == y).sum().item()/len(test_pred_labels))
# Adjust metrics to get average loss and accuracy per batch
test_loss = test_loss / len(dataloader)
test_acc = test_acc / len(dataloader)
return test_loss, test_accIn [64]:
from tqdm.auto import tqdm
# 1. Create a train function that takes in various model parameters + optimizer + dataloaders + loss function
def train(model: torch.nn.Module,
train_dataloader,
test_dataloader,
optimizer,
loss_fn: torch.nn.Module = nn.CrossEntropyLoss(),
epochs: int = 5,
device=device):
# 2. Create empty results dictionary
results = {"train_loss": [],
"train_acc": [],
"test_loss": [],
"test_acc": []}
# 3. Loop through training and testing steps for a number of epochs
for epoch in tqdm(range(epochs)):
train_loss, train_acc = train_step(model=model,
dataloader=train_dataloader,
loss_fn=loss_fn,
optimizer=optimizer,
device=device)
test_loss, test_acc = test_step(model=model,
dataloader=test_dataloader,
loss_fn=loss_fn,
device=device)
# 4. Print out what's happening
print(f"Epoch: {epoch} | Train loss: {train_loss:.4f} | Train acc: {train_acc:.4f} | Test loss: {test_loss:.4f} | Test acc: {test_acc:.4f}")
# 5. Update results dictionary
results["train_loss"].append(train_loss)
results["train_acc"].append(train_acc)
results["test_loss"].append(test_loss)
results["test_acc"].append(test_acc)
# 6. Return the filled results at the end of the epochs
return resultsIn [65]:
# Set random seeds
torch.manual_seed(42)
torch.cuda.manual_seed(42)
# Set number of epochs
NUM_EPOCHS = 5
# Recreate an instance of TinyVGG
model_0 = TinyVGG(input_shape=3, # number of color channels of our target images
hidden_units=10,
output_shape=len(train_data.classes)).to(device)
# Setup loss function and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(params=model_0.parameters(),
lr=0.001)
# Start the timer
from timeit import default_timer as timer
start_time = timer()
# Train model_0
model_0_results = train(model=model_0,
train_dataloader=train_dataloader_simple,
test_dataloader=test_dataloader_simple,
optimizer=optimizer,
loss_fn=loss_fn,
epochs=NUM_EPOCHS)
# End the timer and print out how long it took
end_time = timer()
print(f"Total training time: {end_time-start_time:.3f} seconds")0%| | 0/5 [00:00<?, ?it/s]
Epoch: 0 | Train loss: 1.1063 | Train acc: 0.3047 | Test loss: 1.0983 | Test acc: 0.3116 Epoch: 1 | Train loss: 1.0995 | Train acc: 0.3320 | Test loss: 1.0698 | Test acc: 0.5417 Epoch: 2 | Train loss: 1.0862 | Train acc: 0.4922 | Test loss: 1.0799 | Test acc: 0.5227 Epoch: 3 | Train loss: 1.0826 | Train acc: 0.4102 | Test loss: 1.0598 | Test acc: 0.5729 Epoch: 4 | Train loss: 1.0631 | Train acc: 0.4141 | Test loss: 1.0612 | Test acc: 0.5540 Total training time: 10.171 seconds
In [66]:
model_0_resultsOut [66]:
{'test_acc': [0.31155303030303033,
0.5416666666666666,
0.5227272727272728,
0.5729166666666666,
0.5539772727272728],
'test_loss': [1.098314603169759,
1.069807728131612,
1.0799124638239543,
1.0598418315251668,
1.0611690680185955],
'train_acc': [0.3046875, 0.33203125, 0.4921875, 0.41015625, 0.4140625],
'train_loss': [1.1063424944877625,
1.0995023548603058,
1.0862251669168472,
1.0826159715652466,
1.0630627423524857]}In [67]:
# Get the model_0_results keys
model_0_results.keys()Out [67]:
dict_keys(['train_loss', 'train_acc', 'test_loss', 'test_acc'])
In [68]:
def plot_loss_curves(results: Dict[str, List[float]]):
"""Plots training curves of a results dictionary."""
# Get the loss values of the results dictionary(training and test)
loss = results["train_loss"]
test_loss = results["test_loss"]
# Get the accuracy values of the results dictionary (training and test)
accuracy = results["train_acc"]
test_accuracy = results["test_acc"]
# Figure out how mnay epochs there were
epochs = range(len(results["train_loss"]))
# Setup a plot
plt.figure(figsize=(15, 7))
# Plot the loss
plt.subplot(1, 2, 1)
plt.plot(epochs, loss, label="train_loss")
plt.plot(epochs, test_loss, label="test_loss")
plt.title("Loss")
plt.xlabel("Epochs")
plt.legend()
# Plot the accuracy
plt.subplot(1, 2, 2)
plt.plot(epochs, accuracy, label="train_accuracy")
plt.plot(epochs, test_accuracy, label="test_accuracy")
plt.title("Accuracy")
plt.xlabel("Epochs")
plt.legend();In [69]:
plot_loss_curves(model_0_results) In [70]:
# Create training transform with TriviailAugment
from torchvision import transforms
train_transform_trivial = transforms.Compose([
transforms.Resize(size=(64, 64)),
transforms.TrivialAugmentWide(num_magnitude_bins=31),
transforms.ToTensor()
])
test_transform_simple = transforms.Compose([
transforms.Resize(size=(64, 64)),
transforms.ToTensor()
])In [71]:
# Turn image folders into Datasets
from torchvision import datasets
train_data_augmented = datasets.ImageFolder(root=train_dir,
transform=train_transform_trivial)
test_data_simple = datasets.ImageFolder(root=test_dir,
transform=test_transform_simple)Warning:
Output truncated. This notebook contains too many cells to display efficiently.