Files
pytorch-deep-learning/04_pytorch_custom_datasets.ipynb
T

731 KiB

TODO:

Next notebook... (keep them short and sweet)

  • Bring in custom dataset
  • Try TinyVGG on custom dataset (conv layers etc) - https://poloclub.github.io/cnn-explainer/
  • compare custom dataset on and off GPU
  • Use TensorBoard integration in VSCode - can sync this up with Weights & Biases
In [1]:
import torch
from torch import nn
In [2]:
print(torch.__version__)
1.10.0
In [3]:
device = "cuda" if torch.cuda.is_available() else "cpu"
device
Out [3]:
'cuda'

Load data

Option 1 - Using ImageFolder

In [4]:
import torch
import torchvision
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
In [5]:
train_dir = "10_whole_foods/train"
test_dir = "10_whole_foods/test"
In [6]:
# Write transform for image
data_transform = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.RandomHorizontalFlip(p=0.5),
    transforms.ToTensor()
])
In [7]:
# Import image and transform
from PIL import Image
import random
import matplotlib.pyplot as plt
import pathlib
# TK - Functionise this for viewing transformed images...
image_path_list = list(pathlib.Path("data/10_whole_foods/").glob("*/*/*.jpg"))
random_image_path = random.choice(image_path_list)
with Image.open(random_image_path) as f:
    plt.subplot(1, 2, 1)
    plt.imshow(f)
    plt.axis("off")
    plt.title("Original")
    plt.subplot(1, 2, 2)
    transformed_image = data_transform(f).permute(1, 2, 0) # change shape of image to suit matplotlib
    plt.imshow(transformed_image) 
    plt.title("Transformed")
    plt.axis("off")
    print(f"""
    Image class: {random_image_path.parent.stem}
    Original size: {f.size}
    New size: {transformed_image.shape}
    """)
    Image class: carrots
    Original size: (800, 571)
    New size: torch.Size([64, 64, 3])
    
In [8]:
# Use ImageFolder to create dataset(s)
train_data = datasets.ImageFolder(train_dir, transform=data_transform)
test_data = datasets.ImageFolder(test_dir, transform=data_transform)

train_data, test_data
Out [8]:
(Dataset ImageFolder
     Number of datapoints: 654
     Root location: 10_whole_foods/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: 164
     Root location: 10_whole_foods/test
     StandardTransform
 Transform: Compose(
                Resize(size=(64, 64), interpolation=bilinear, max_size=None, antialias=None)
                RandomHorizontalFlip(p=0.5)
                ToTensor()
            ))
In [9]:
class_names = train_data.classes
class_names
Out [9]:
['apple',
 'banana',
 'beef',
 'blueberries',
 'carrots',
 'chicken_wings',
 'egg',
 'honey',
 'mushrooms',
 'strawberries']
In [10]:
img, label = train_data[0][0], train_data[0][1]
img_permute = img.permute(1, 2, 0) # need to change shape for Matplotlib
print(f"Original shape: {img.shape}")
print(f"Image permute shape: {img_permute.shape}")
plt.imshow(img.permute(1, 2, 0))
plt.axis("off")
plt.title(class_names[label]);
Original shape: torch.Size([3, 64, 64])
Image permute shape: torch.Size([64, 64, 3])
In [11]:
img, label
Out [11]:
(tensor([[[0.9961, 0.6706, 0.2078,  ..., 0.1176, 0.1686, 0.1922],
          [0.9882, 0.7961, 0.2392,  ..., 0.1059, 0.1490, 0.2235],
          [0.6588, 0.5804, 0.2275,  ..., 0.1098, 0.1490, 0.2392],
          ...,
          [0.2275, 0.1647, 0.1373,  ..., 0.2549, 0.2588, 0.4784],
          [0.2275, 0.1686, 0.1490,  ..., 0.3020, 0.2314, 0.4510],
          [0.2275, 0.1686, 0.1490,  ..., 0.2980, 0.2235, 0.3804]],
 
         [[0.9961, 0.7216, 0.3490,  ..., 0.2235, 0.2471, 0.1882],
          [0.9922, 0.8314, 0.3765,  ..., 0.2157, 0.2196, 0.2196],
          [0.7451, 0.6784, 0.3765,  ..., 0.2157, 0.2039, 0.2471],
          ...,
          [0.3804, 0.3098, 0.2706,  ..., 0.3529, 0.3608, 0.5882],
          [0.3765, 0.3098, 0.2824,  ..., 0.4078, 0.3333, 0.5529],
          [0.3804, 0.3098, 0.2824,  ..., 0.4118, 0.3255, 0.4824]],
 
         [[0.9961, 0.6235, 0.0353,  ..., 0.0353, 0.0706, 0.0431],
          [0.9922, 0.7765, 0.0745,  ..., 0.0157, 0.0275, 0.0627],
          [0.5686, 0.4745, 0.0471,  ..., 0.0078, 0.0235, 0.0745],
          ...,
          [0.1255, 0.0431, 0.0196,  ..., 0.1412, 0.1765, 0.2824],
          [0.1176, 0.0431, 0.0275,  ..., 0.1255, 0.1608, 0.2980],
          [0.1098, 0.0392, 0.0275,  ..., 0.1137, 0.1451, 0.2314]]]),
 0)
In [12]:
# Turn images into data loaders
train_dataloader = DataLoader(train_data, batch_size=1, num_workers=1, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=1, num_workers=1, shuffle=True)
train_dataloader, test_dataloader
Out [12]:
(<torch.utils.data.dataloader.DataLoader at 0x7f1e1ba29d00>,
 <torch.utils.data.dataloader.DataLoader at 0x7f1e1ba29790>)
In [13]:
img, label = next(iter(train_dataloader))
img.shape, label.shape # batch size is now 1 (try changing the batch_size parameter above)
Out [13]:
(torch.Size([1, 3, 64, 64]), torch.Size([1]))

Option 2: Custom data loader

We're going to recreate torchvision.datasets.ImageFolder() - https://pytorch.org/vision/stable/datasets.html#torchvision.datasets.ImageFolder

  • TK - why use this?
  • TK - what's pros and cons? (e.g. more prone to errors but get full customization, have to write more code)
In [14]:
import pathlib
import random
import torch
import os

from PIL import Image
from torchvision import transforms
from typing import Tuple, Dict, List
In [15]:
# Make function to find classes in target directory
# (assumes target directory is in standard image format)
def find_classes(directory: str) -> Tuple[List[str], Dict[str, str]]:
    """Finds the class folder names in a target directory.

    Args:
        directory ([str]): target directory to load classnames from.

    Returns:
        Tuple[List[str], Dict[str, str]]: (list_of_class_names, dict(idx: class_name...))
    
    Example:
        find_classes("food_images/train")
        >>> (["class_1", "class_2"], {"class_1": 0, ...})
    """
    classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir())
    if not classes:
        raise FileNotFoundError(f"Couldn't find any classes in {directory}.")
    class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}
    return classes, class_to_idx
In [16]:
find_classes(train_dir)
Out [16]:
(['apple',
  'banana',
  'beef',
  'blueberries',
  'carrots',
  'chicken_wings',
  'egg',
  'honey',
  'mushrooms',
  'strawberries'],
 {'apple': 0,
  'banana': 1,
  'beef': 2,
  'blueberries': 3,
  'carrots': 4,
  'chicken_wings': 5,
  'egg': 6,
  'honey': 7,
  'mushrooms': 8,
  'strawberries': 9})
In [17]:
# Write a custom dataset class (inherits from torch.utils.data.Dataset)
from torch.utils.data import Dataset
class ImageFolderCustom(Dataset):
    def __init__(self, targ_dir, transform=None):
        self.paths = list(pathlib.Path(targ_dir).glob("*/*.jpg")) # note: you'd have to update this if you've got .png's or .jpeg's
        self.transform = transform
        self.class_names, self.class_to_idx = find_classes(targ_dir)

    # Make function to load images
    def load_image(self, index) -> Image.Image:
        image_path = self.paths[index]
        return Image.open(image_path) 

    def __len__(self):
        return len(self.paths)
    
    def __getitem__(self, index):
        img = self.load_image(index)
        class_name  = self.paths[index].parent.name # expects path in data_folder/class_name/image.jpeg
        class_idx = self.class_to_idx[class_name]

        # Transform if necessary
        if self.transform:
            return self.transform(img), class_idx # return data, label
        else:
            return img, class_idx
In [18]:
# Augment train data
train_transforms = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.RandomHorizontalFlip(p=0.5),
    transforms.ToTensor()
])

# Don't augment test data, only reshape
test_transforms = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.ToTensor()
])

train_data_custom = ImageFolderCustom(train_dir, transform=train_transforms)
test_data_custom = ImageFolderCustom(test_dir, transform=test_transforms)
len(train_data_custom), len(test_data_custom)
Out [18]:
(654, 164)

TK - Create a function to display random images

In [19]:
def display_random_images(dataset, n=10, classes=None, seed=None):
  if n > 10:
    n = 10
    print(f"For display purposes, n shouldn't be larger than 10, setting to 10.")

  if seed:
    random.seed(seed)  

  # Get random sample indexes
  random_samples_idx = random.sample(range(len(dataset)), k=n)

  # Setup plot
  plt.figure(figsize=(16, 8))

  # Loop through samples and display
  for i, targ_sample in enumerate(random_samples_idx):
    targ_image, targ_label = dataset[targ_sample][0], dataset[targ_sample][1]
    # Min-max scale
    sample_min, sample_max = targ_image.min(), targ_image.max()
    sample_scaled = (targ_image - sample_min)/(sample_max - sample_min)

    # Adjust for shape (colour, height, width) -> (height, width, colour)
    sample_adjust = sample_scaled.permute(1, 2, 0)
    # print(sample_adjust)

    # Plot adjusted samples
    plt.subplot(1, n, i+1)
    plt.imshow(sample_adjust)
    plt.axis("off")
    if classes:
      plt.title(classes[targ_label])
In [20]:
display_random_images(train_data, n=5, classes=class_names)
In [21]:
display_random_images(train_data_custom, n=12, classes=class_names)
For display purposes, n shouldn't be larger than 10, setting to 10.
In [22]:
# Turn image datasets into data loaders
train_dataloader_custom = DataLoader(train_data_custom, batch_size=1, num_workers=1, shuffle=True)
test_dataloader_custom = DataLoader(test_data_custom, batch_size=1, num_workers=1, shuffle=True)
train_dataloader, test_dataloader
Out [22]:
(<torch.utils.data.dataloader.DataLoader at 0x7f1e1ba29d00>,
 <torch.utils.data.dataloader.DataLoader at 0x7f1e1ba29790>)
In [23]:
img, label = next(iter(train_dataloader_custom))
img.shape, label.shape # batch size is now 1 (try changing the batch_size parameter above)
Out [23]:
(torch.Size([1, 3, 64, 64]), torch.Size([1]))

TK Other forms of Augmentation (transforms)

In [24]:
train_transforms = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.RandAugment(), 
    transforms.ToTensor() # use ToTensor() last to get everything between 0 & 1
])

test_transforms = transforms.Compose([
    transforms.Resize((64, 64)), 
    transforms.ToTensor()
])
In [25]:
# Import image and transform
from PIL import Image
import random
import matplotlib.pyplot as plt
import pathlib
image_path_list = list(pathlib.Path("data/10_whole_foods/").glob("*/*/*.jpg"))
random_image_path = random.choice(image_path_list)
with Image.open(random_image_path) as f:
    plt.subplot(1, 2, 1)
    plt.imshow(f)
    plt.axis("off")
    plt.title("Original")
    plt.subplot(1, 2, 2)
    transformed_image = train_transforms(f).permute(1, 2, 0) # change shape of image to suit matplotlib
    plt.imshow(transformed_image) 
    plt.title("Transformed")
    plt.axis("off")
    print(f"""
    Image class: {random_image_path.parent.stem}
    Original size: {f.size}
    New size: {transformed_image.shape}
    """)
    Image class: blueberries
    Original size: (800, 533)
    New size: torch.Size([64, 64, 3])
    

TK - Model without data augmentation

In [76]:
# Create simple transform
simple_transform = transforms.Compose([ 
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    # transforms.Normalize(mean=[0.485, 0.456, 0.406],
    #                  std=[0.229, 0.224, 0.225]) 
])
In [77]:
# Load data
train_data_simple = datasets.ImageFolder(train_dir, transform=simple_transform)
test_data_simple = datasets.ImageFolder(test_dir, transform=simple_transform)

# Turn data into DataLoaders
train_dataloader_simple = DataLoader(train_data_simple, 
                                     batch_size=32, 
                                     shuffle=True, 
                                     num_workers=4)
test_dataloader_simple = DataLoader(test_data_simple, 
                                    batch_size=32, 
                                    shuffle=True, 
                                    num_workers=4)

train_dataloader_simple, test_dataloader_simple
Out [77]:
(<torch.utils.data.dataloader.DataLoader at 0x7f1e1bbcfb50>,
 <torch.utils.data.dataloader.DataLoader at 0x7f1e1bb87ee0>)

Create model

In [78]:
class TinyVGG(nn.Module):
    def __init__(self, input_size, hidden_units, output_shape):
        super().__init__()
        self.conv_block_1 = nn.Sequential(
            nn.Conv2d(in_channels=input_size,
                out_channels=hidden_units,
                kernel_size=3),
            nn.ReLU(),
            nn.Conv2d(in_channels=hidden_units,
                out_channels=hidden_units,
                kernel_size=3),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        self.conv_block_2 = nn.Sequential(
            nn.Conv2d(in_channels=hidden_units,
                out_channels=hidden_units,
                kernel_size=3),
            nn.ReLU(),
            nn.Conv2d(in_channels=hidden_units,
                out_channels=hidden_units,
                kernel_size=3),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Linear(in_features=hidden_units*53*53, # get this by printing the shape of the outputs of each layer
                      out_features=hidden_units),
            nn.ReLU(),
            nn.Linear(in_features=hidden_units,
                      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(self.conv_block(x)))

model_0 = TinyVGG(input_size=3, # number of colour channels
    hidden_units=10,
    output_shape=len(train_data.classes)
).to(device)
model_0
Out [78]:
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=28090, out_features=10, bias=True)
    (2): ReLU()
    (3): Linear(in_features=10, out_features=10, bias=True)
  )
)
In [79]:
from torchinfo import summary
summary(model_0, input_size=[1, 3, 224, 224])
Out [79]:
==========================================================================================
Layer (type:depth-idx)                   Output Shape              Param #
==========================================================================================
TinyVGG                                  --                        --
├─Sequential: 1-1                        [1, 10, 110, 110]         --
│    └─Conv2d: 2-1                       [1, 10, 222, 222]         280
│    └─ReLU: 2-2                         [1, 10, 222, 222]         --
│    └─Conv2d: 2-3                       [1, 10, 220, 220]         910
│    └─ReLU: 2-4                         [1, 10, 220, 220]         --
│    └─MaxPool2d: 2-5                    [1, 10, 110, 110]         --
├─Sequential: 1-2                        [1, 10, 53, 53]           --
│    └─Conv2d: 2-6                       [1, 10, 108, 108]         910
│    └─ReLU: 2-7                         [1, 10, 108, 108]         --
│    └─Conv2d: 2-8                       [1, 10, 106, 106]         910
│    └─ReLU: 2-9                         [1, 10, 106, 106]         --
│    └─MaxPool2d: 2-10                   [1, 10, 53, 53]           --
├─Sequential: 1-3                        [1, 10]                   --
│    └─Flatten: 2-11                     [1, 28090]                --
│    └─Linear: 2-12                      [1, 10]                   280,910
│    └─ReLU: 2-13                        [1, 10]                   --
│    └─Linear: 2-14                      [1, 10]                   110
==========================================================================================
Total params: 284,030
Trainable params: 284,030
Non-trainable params: 0
Total mult-adds (M): 78.96
==========================================================================================
Input size (MB): 0.60
Forward/backward pass size (MB): 9.65
Params size (MB): 1.14
Estimated Total Size (MB): 11.39
==========================================================================================

Create train & test functions

TK - after 04, functionize everything

In [80]:
def train(data_loader, model, loss_fn, optimizer, print_freq=10):
    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)

        # print(y)
        
        # 1. Forward pass
        y_pred = model(X)
        # print(y_pred)
        # print(torch.softmax(y_pred, dim=1))
        # print(torch.softmax(y_pred, dim=1).argmax(dim=1))

        # 2. Calculate loss
        loss = loss_fn(y_pred, y)

        # 3. Optimizer zero grad
        optimizer.zero_grad()

        # 4. Loss backwards
        loss.backward()

        # 5. Optimizer step
        optimizer.step()

        # Print out what's happening
        if batch % print_freq == 0:
            sample_number = batch * len(X)
            print(f"Loss: {loss:.5f} | Looked at {sample_number}/{len(data_loader.dataset)} samples")
In [81]:
from helper_functions import accuracy_fn
In [82]:
def test(data_loader, model, loss_fn, accuracy_fn=None):
    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 (if necessary
            test_loss += loss_fn(test_pred, y)
            # print(test_pred.argmax(dim=1))
            if accuracy_fn is not None:
                test_acc += accuracy_fn(y_true=y,
                    y_pred=test_pred.argmax(dim=1))
            else:
                print("No accuracy_fn given, accuracy will show 0%")
            
        # 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 [83]:
# Setup loss and optimizer 
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(params=model_0.parameters(), lr=0.001)
In [84]:
# Train
from timeit import default_timer as timer 
start_time = timer()
epochs = 5
for epoch in range(epochs):
    print(f"Epoch: {epoch}\n----------")
    train(data_loader=train_dataloader_simple, 
        model=model_0,
        loss_fn=loss_fn,
        optimizer=optimizer)
    test(data_loader=test_dataloader_simple,
        model=model_0,
        loss_fn=loss_fn,
        accuracy_fn=accuracy_fn
    )
end_time = timer()
print(f"Total training time: {end_time-start_time}")
Epoch: 0
----------
Loss: 2.35703 | Looked at 0/654 samples
Loss: 2.32441 | Looked at 320/654 samples
Loss: 2.30014 | Looked at 280/654 samples
tensor([8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
        8, 8, 8, 8, 8, 8, 8, 8], device='cuda:0')
tensor([8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
        8, 8, 8, 8, 8, 8, 8, 8], device='cuda:0')
tensor([8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
        8, 8, 8, 8, 8, 8, 8, 8], device='cuda:0')
tensor([8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
        8, 8, 8, 8, 8, 8, 8, 8], device='cuda:0')
tensor([8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
        8, 8, 8, 8, 8, 8, 8, 8], device='cuda:0')
tensor([8, 8, 8, 8], device='cuda:0')

Testing for Epoch: 0
----------
Test loss: 2.32970 | Test accuracy: 5.73%

Epoch: 1
----------
Loss: 2.29623 | Looked at 0/654 samples
Loss: 2.34511 | Looked at 320/654 samples
Loss: 2.37775 | Looked at 280/654 samples
tensor([3, 3, 8, 3, 3, 3, 3, 3, 8, 3, 3, 8, 8, 3, 3, 8, 3, 3, 3, 8, 3, 3, 3, 3,
        3, 3, 3, 3, 3, 3, 3, 3], device='cuda:0')
tensor([3, 3, 3, 3, 3, 3, 3, 8, 3, 3, 3, 8, 3, 3, 8, 8, 8, 3, 3, 8, 3, 3, 8, 3,
        3, 3, 3, 3, 8, 8, 3, 8], device='cuda:0')
tensor([8, 3, 3, 8, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
        3, 3, 8, 3, 3, 3, 3, 8], device='cuda:0')
tensor([3, 3, 3, 3, 3, 3, 3, 3, 8, 8, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 8, 3,
        3, 8, 3, 8, 3, 8, 3, 3], device='cuda:0')
tensor([3, 8, 3, 3, 3, 3, 8, 9, 3, 3, 3, 3, 8, 8, 8, 3, 3, 8, 3, 3, 3, 3, 3, 3,
        3, 8, 3, 3, 8, 3, 3, 3], device='cuda:0')
tensor([3, 3, 3, 3], device='cuda:0')

Testing for Epoch: 1
----------
Test loss: 2.29934 | Test accuracy: 9.38%

Epoch: 2
----------
Loss: 2.30758 | Looked at 0/654 samples
Loss: 2.21940 | Looked at 320/654 samples
Loss: 2.34643 | Looked at 280/654 samples
tensor([8, 8, 3, 8, 3, 3, 8, 3, 3, 9, 3, 3, 3, 8, 8, 9, 3, 9, 9, 3, 3, 3, 8, 3,
        8, 9, 8, 3, 8, 3, 8, 8], device='cuda:0')
tensor([3, 3, 3, 8, 8, 3, 3, 9, 8, 8, 3, 8, 9, 8, 9, 3, 8, 3, 3, 3, 8, 8, 3, 8,
        8, 3, 9, 8, 8, 3, 3, 3], device='cuda:0')
tensor([8, 3, 3, 8, 3, 3, 8, 8, 8, 3, 8, 8, 3, 9, 3, 3, 3, 8, 8, 8, 3, 9, 8, 3,
        8, 8, 9, 3, 8, 3, 3, 8], device='cuda:0')
tensor([8, 8, 8, 8, 9, 8, 3, 9, 8, 3, 3, 9, 3, 3, 8, 3, 8, 9, 8, 3, 3, 8, 3, 3,
        8, 8, 9, 3, 9, 3, 3, 8], device='cuda:0')
tensor([8, 3, 9, 3, 3, 3, 3, 3, 3, 3, 8, 3, 8, 9, 9, 8, 8, 9, 3, 9, 8, 3, 3, 3,
        8, 8, 9, 8, 3, 8, 3, 3], device='cuda:0')
tensor([9, 8, 3, 9], device='cuda:0')

Testing for Epoch: 2
----------
Test loss: 2.26508 | Test accuracy: 8.85%

Epoch: 3
----------
Loss: 2.38322 | Looked at 0/654 samples
Loss: 2.22241 | Looked at 320/654 samples
Loss: 2.26243 | Looked at 280/654 samples
tensor([3, 8, 8, 9, 8, 8, 3, 8, 8, 3, 3, 3, 8, 3, 9, 8, 8, 9, 8, 8, 3, 8, 9, 3,
        8, 8, 3, 3, 8, 3, 8, 8], device='cuda:0')
tensor([8, 8, 9, 3, 3, 3, 9, 9, 3, 3, 8, 8, 8, 8, 8, 3, 3, 3, 8, 8, 3, 8, 9, 8,
        3, 8, 3, 9, 3, 8, 9, 8], device='cuda:0')
tensor([3, 9, 9, 3, 8, 9, 9, 8, 9, 3, 3, 9, 3, 3, 8, 3, 9, 9, 8, 3, 9, 8, 9, 8,
        9, 8, 8, 8, 8, 8, 8, 3], device='cuda:0')
tensor([9, 8, 3, 9, 3, 3, 8, 9, 8, 9, 9, 8, 8, 3, 8, 3, 8, 9, 8, 8, 3, 8, 3, 3,
        8, 8, 9, 8, 8, 8, 9, 9], device='cuda:0')
tensor([3, 8, 9, 3, 3, 3, 8, 9, 3, 9, 8, 9, 8, 3, 3, 8, 8, 3, 8, 8, 8, 8, 9, 3,
        8, 8, 8, 8, 8, 9, 3, 3], device='cuda:0')
tensor([8, 3, 9, 8], device='cuda:0')

Testing for Epoch: 3
----------
Test loss: 2.29451 | Test accuracy: 8.85%

Epoch: 4
----------
Loss: 2.24605 | Looked at 0/654 samples
Loss: 2.21941 | Looked at 320/654 samples
Loss: 2.19423 | Looked at 280/654 samples
tensor([9, 3, 8, 8, 9, 8, 9, 9, 3, 9, 8, 9, 9, 3, 8, 3, 9, 3, 3, 8, 9, 8, 3, 3,
        9, 3, 3, 8, 9, 8, 9, 8], device='cuda:0')
tensor([9, 8, 8, 3, 9, 9, 8, 8, 9, 9, 3, 8, 9, 8, 8, 9, 8, 9, 3, 9, 3, 9, 9, 8,
        9, 3, 9, 8, 8, 8, 8, 9], device='cuda:0')
tensor([8, 8, 9, 9, 3, 9, 8, 8, 9, 8, 9, 3, 8, 9, 8, 9, 9, 9, 8, 9, 3, 3, 3, 3,
        9, 8, 8, 9, 9, 9, 3, 9], device='cuda:0')
tensor([9, 3, 9, 8, 9, 8, 9, 8, 3, 9, 3, 9, 3, 3, 9, 8, 8, 9, 9, 9, 3, 9, 8, 3,
        8, 9, 3, 9, 3, 9, 8, 9], device='cuda:0')
tensor([3, 9, 9, 8, 9, 3, 9, 3, 9, 8, 8, 9, 3, 8, 3, 9, 9, 3, 3, 3, 8, 8, 8, 3,
        9, 9, 9, 8, 3, 9, 3, 9], device='cuda:0')
tensor([9, 8, 8, 3], device='cuda:0')

Testing for Epoch: 4
----------
Test loss: 2.29248 | Test accuracy: 8.33%

Total training time: 161.1517569271382
In [ ]:

TODO

Next notebook

  • Build a model on a small subset of the data (e.g. 10 images per class)
  • Build a model on a larger subset of the data (e.g. 100 images per class)
  • Track results with PyTorch profiler
  • Introduce transfer learning (beat the original model)
In [85]:
import os
def walk_through_dir(dir_path):
  """
  Walks through dir_path returning its contents.
  Args:
    dir_path (str): target directory
  
  Returns:
    A print out of:
      number of subdiretories in dir_path
      number of images (files) in each subdirectory
      name of each subdirectory
  """
  for dirpath, dirnames, filenames in os.walk(dir_path):
    print(f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.")
In [86]:
walk_through_dir("10_whole_foods")
There are 2 directories and 1 images in '10_whole_foods'.
There are 10 directories and 0 images in '10_whole_foods/test'.
There are 0 directories and 17 images in '10_whole_foods/test/carrots'.
There are 0 directories and 11 images in '10_whole_foods/test/mushrooms'.
There are 0 directories and 17 images in '10_whole_foods/test/apple'.
There are 0 directories and 10 images in '10_whole_foods/test/strawberries'.
There are 0 directories and 19 images in '10_whole_foods/test/blueberries'.
There are 0 directories and 20 images in '10_whole_foods/test/banana'.
There are 0 directories and 21 images in '10_whole_foods/test/beef'.
There are 0 directories and 15 images in '10_whole_foods/test/egg'.
There are 0 directories and 19 images in '10_whole_foods/test/honey'.
There are 0 directories and 15 images in '10_whole_foods/test/chicken_wings'.
There are 10 directories and 0 images in '10_whole_foods/train'.
There are 0 directories and 70 images in '10_whole_foods/train/carrots'.
There are 0 directories and 66 images in '10_whole_foods/train/mushrooms'.
There are 0 directories and 57 images in '10_whole_foods/train/apple'.
There are 0 directories and 64 images in '10_whole_foods/train/strawberries'.
There are 0 directories and 59 images in '10_whole_foods/train/blueberries'.
There are 0 directories and 58 images in '10_whole_foods/train/banana'.
There are 0 directories and 74 images in '10_whole_foods/train/beef'.
There are 0 directories and 65 images in '10_whole_foods/train/egg'.
There are 0 directories and 63 images in '10_whole_foods/train/honey'.
There are 0 directories and 78 images in '10_whole_foods/train/chicken_wings'.
In [ ]: