Using Neural Networks to solve image classification¶

This project uses a neural network architecture to solve a popular image classification problem, miniImageNet (https://www.kaggle.com/datasets/arjunashok33/miniimagenet).

Step 1. Import relevant libraries¶

InĀ [1]:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR
from random import randint
from torch.utils.data import random_split, DataLoader

import matplotlib.pyplot as plt
import numpy as np
from torchvision import transforms
from torchvision.datasets import ImageFolder
from tqdm import tqdm
import os
InĀ [2]:
from google.colab import drive

drive.mount('/content/drive',force_remount=True)
Mounted at /content/drive
InĀ [3]:
!ls "/content/drive/MyDrive/Colab Datasets"
 a2.1_Ben_Redden_ComputerVision.ipynb
 a2725385_uomachinelearning_Assess2.ipynb
 a2725385_uoml_assessment1.2.ipynb
 a2725385_uoml_Assessment2.ipynb
'Anomaly Detection Solution.ipynb'
 Assessment2.1.ipynb
'Auditing&Mitigating with FairLearn.ipynb'
'AutoregressiveForecasting .ipynb'
'Ben_Redden_AdvancedAI(Final).ipynb'
 Ben_Redden_AdvancedAI.ipynb
 Ben_Redden_AdvancedAI_TimeSeries.ipynb
'Ben_Redden_AdvancedAI(TS Final).ipynb'
'BenRedden_TS_Project .ipynb'
'Copy of a2725385_uoml_Assessment2(exResult).ipynb'
'Copy of pytorch_introduction.ipynb'
 Data
 Kaggriculture_V10_Clean.ipynb
 Kaggriculture_V11_Clean.ipynb
 Kaggriculture_V11_Revised_Hybrid.ipynb
 Kaggriculture_V12.ipynb
 Kaggriculture_V12_Rebuilt_Clean.ipynb
 Kaggriculture_V12_Rebuilt_Livestock.ipynb
 Kaggriculture_V13_Daily_Workforce.ipynb
 Kaggriculture_V14_Workforce_Optimised.ipynb
 Kaggriculture_V15_Endgame_Optimised.ipynb
 Kaggriculture_V16_Leader_Inspired.ipynb
 Kaggriculture_V17_Crop_Throughput.ipynb
 Kaggriculture_V18_Crop_First_Livestock.ipynb
 Kaggriculture_V19_Leader_Scale.ipynb
 Kaggriculture_V20_Strategy_Optimiser.ipynb
 Kaggriculture_V21_RL_Training.ipynb
 Kaggriculture_V22_Throughput_Analyzer.ipynb
 Kaggriculture_V23_Expert_Imitation.ipynb
 Kaggriculture_V24_State_Aware_Expert.ipynb
 Kaggriculture_V25_ExpertA_Diagnostic.ipynb
 Kaggriculture_V26_Market_Price_Diagnostic.ipynb
 Kaggriculture_V27_Adaptive_Selling.ipynb
 Kaggriculture_V28_Expert_Planting_Diagnostic.ipynb
 Kaggriculture_V29b_Corrected_Economic_Planner.ipynb
 Kaggriculture_V30_Independent_State_Aware_Agent.ipynb
 Kaggriculture_V6_clean.ipynb
'Kaggriculture_V7_clean (1).ipynb'
 Kaggriculture_V7_clean.ipynb
 Kaggriculture_V8_Clean.ipynb
 Kaggriculture_V9_Clean.ipynb
 Kaggricuture_3_cleaned.ipynb
 Kaggricuture_3_cleaned_v2.ipynb
 Kaggricuture.ipynb
'lstm_solution (1).ipynb'
 lstm_solution.ipynb
 Machine_Learning
 miniImageNet
'miniImageNet (1).zip'
'Neural Networks - Image Classification.ipynb'
 OpenCV.ipynb
 PolyMArket.ipynb
'Propbing a Foundation Model.ipynb'
 ptb
'ptbdataset (Unzipped Files)'
 ptbdataset.zip
 __pycache__
 pytorch_introduction.ipynb
 Thermal_Dogs_People_Object_Detection.ipynb
'Time Series Naive PRediction.ipynb'
 transformer_solution.ipynb
 Untitled
 Untitled0.ipynb
 Untitled1.ipynb
 Untitled2.ipynb
 utils.py
'vrnn_demo (1).ipynb'
InĀ [4]:
import os

DATA_PATH = "/content/drive/MyDrive/Colab Datasets/miniImageNet/"

print(os.listdir(DATA_PATH))
['miniImageNet']
InĀ [5]:
DATA_PATH = "/content/drive/MyDrive/Colab Datasets/miniImageNet/miniImageNet"

print(os.listdir(DATA_PATH))
['n01532829', 'n01558993', 'n01704323', 'n01749939', 'n01770081', 'n01843383', 'n01855672', 'n01910747', 'n01930112', 'n01981276']

Step 2. Use a subset of miniImageNet dataset, create dataloaders for train, validate and test data with batch_size = 64 with a random split of the data into 50/20/30 for train/validate/test¶

InĀ [6]:
input_size = 227

data_transform = transforms.Compose([
    transforms.RandomRotation(10),
    transforms.RandomHorizontalFlip(),
    transforms.Resize(input_size),
    transforms.CenterCrop(input_size),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

dataset = ImageFolder(
    root=DATA_PATH,
    transform=data_transform)

#dataset = ImageFolder(root='/content/miniImageNet/miniImageNet', transform=data_transform)

dataset_size = len(dataset)

train_size = int(len(dataset) * 0.5)
test_size = int(len(dataset) * 0.3)
val_size = int(len(dataset) - train_size - test_size)

train_data, val_data, test_data = random_split(dataset, [train_size, val_size, test_size])

#define batch sizes
bs = 64

trainloader  = DataLoader(train_data, batch_size=bs, shuffle=True)
valloader = DataLoader(val_data, batch_size=bs, shuffle=False)
testloader = DataLoader(test_data, batch_size=bs, shuffle=False)

#print size of datasets
print("Total Dataset Size: ", dataset_size)
print("Total Train Dataset Size: ", train_size)
print("Total Test Size: ", len(test_data))
print("Total Train Size: ", len(train_data))
print("Total Validation Size: ", len(val_data))
Total Dataset Size:  5999
Total Train Dataset Size:  2999
Total Test Size:  1799
Total Train Size:  2999
Total Validation Size:  1201

Step 3. Visualise the a subset of the dataset that has been downloaded and present them in a grid-format. Using the subfolder names in miniImageNet as the class names and display the class name for each image.¶

InĀ [7]:
# get a batch  of training data
images, labels = next(iter(trainloader))

#create a list of classes from imagefolder dataset
class_names = dataset.classes

#create 64 subplots (8x8)
fig, axes = plt.subplots(8, 8,figsize=(20,20))

# extract batch properties
batch_size = images.shape[0]
height = images.shape[2]
width = images.shape[3]

fig.suptitle(
    f"A single batch consisting of {batch_size} pictures of size {height} Ɨ {width} pixels \n",
    fontsize=18
)



for i, ax in enumerate(axes.flatten()):

    # transformation to enable matplotlib to display properly  - need to go from c,h,w to h,w,c
    img = images[i].numpy().transpose((1, 2, 0))

    #matplotlib expects values between 0 and 1 so np.clip is required on normalised data
    img = np.clip(img, 0, 1)

    #show image at location ax
    ax.imshow(img)

    ax.set_title(class_names[labels[i]])

    ax.axis('off')

plt.tight_layout()
plt.show()
No description has been provided for this image

Step 4. Description of the CNN-based model¶

The model is an example of a convolution neural network that uses Rectified Linear Unit (ReLU) for nonlinearity. This model contains 7 learned layers (4 convolutional and 3 fully connected) with 2D batch normalisation and pooling layers (using Average Pooling) occuring after the early convolutions. Batch Normalisation is used to accelerate convergence.

The specific parameters adopted for convolutional layer 1 mean that RGB image data (3 channels) is accepted as input and transformed into 96 feature maps using an 11x11 convolution with a stride of 4. Using the formula ((input size - kernel)/stride)+1 the input tensor dimension changes from (64,3,227,227) to (64,96,55,55).

The ReLU and batch normalisation layers do not have any impact on tensor shape. Average Pooling layers have parameters kernel_size =3 and stride = 2 this creates overlapping as stride is less than kernel_size. The result is a reduction in spatial dimension from (64,96,55,55) to (64,96,27,27). Convolution layer 2 uses in_channels=96, out_channels=256, kernel_size=5, padding=2 and default stride = 1. After taking into account padding the tensor dimension reduction is ((27 - 5 + 2*2)/1)+1 = 27 meaning tensor dimension of (64,96,27,27) stays (64,256,27,27). Using the above logic the input -> outputs for remaining layers are pooling layer2 (64,256,27,27) to (64,256,13,13), convolution layer3 (64,256,13,13) -> (64,384,13,13), convolution layer4 (64,384,13,13) -> (64,256,13,13), pooling layer3 (64,256,13,13) -> (64,256,6,6).

The fully connected layers combine extracted features (256,6,6) for classification into 10 target classes. This model is effective for this dataset as CNN efficiently learn image features making them highly effective for image classification.

InĀ [8]:
#define model
class Model(nn.Module):

    def __init__(self, num_classes=10):

        super(Model, self).__init__()

        self.net = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4),
            nn.ReLU(),
            nn.BatchNorm2d(96),
            nn.AvgPool2d(kernel_size=3, stride=2),
            nn.Conv2d(96, 256, 5, padding=2),
            nn.ReLU(),
            nn.BatchNorm2d(256),
            nn.AvgPool2d(kernel_size=3, stride=2),
            nn.Conv2d(256, 384, 3, padding=1),
            nn.ReLU(),
            nn.Conv2d(384, 256, 3, padding=1),
            nn.ReLU(),
            nn.AvgPool2d(kernel_size=3, stride=2),
        )

        self.classifier = nn.Sequential(
            nn.Linear(in_features=(256 * 6 * 6), out_features=4096),

            nn.Linear(in_features=4096, out_features=4096),

            nn.Linear(in_features=4096, out_features=num_classes),
        )

    def forward(self, x):

        output = self.net(x)
        #flatten features prior to input into classifier
        output = output.view(output.size()[0],-1)
        output = self.classifier(output)

        return output

Step 5. Create the training environment to train the model provided in the previous step. Set the learning rate=0.01, weight_decay = 5e-4. Use the cross entropy loss function and the SGD optimizer.¶

InĀ [9]:
model = Model(num_classes=10)

criterion = nn.CrossEntropyLoss()

#optimizer
optimizer = torch.optim.SGD(model.parameters() , lr=0.01, weight_decay=5e-4)

#schedule decay of learning rate by 0.1 at epochs 20 and 30
scheduler = MultiStepLR(optimizer, milestones=[20, 30], gamma=0.1)


#check GPU details
print(torch.cuda.is_available())
print(torch.cuda.get_device_name(0))

#fallback if GPU not available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)

def train_model (model, trainloader,valloader, criterion, optimizer, num_epochs):
    train_losses =[]
    val_losses = []
    train_accs = []
    val_accs = []

    train_epochs = []
    val_epochs = []

    best_val_acc = 0


    for epoch in range(num_epochs):
        # set to training mode
        model.train()

        running_loss = 0.0
        correct  = 0
        total = 0


        progress_bar  = tqdm(trainloader, desc=f"Epoch: ,{epoch+1}/{num_epochs}")

        for images, labels in progress_bar:

            images = images.to(device)
            labels = labels.to(device)

            optimizer.zero_grad()
            outputs = model(images)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            running_loss += loss.item()

            prediction = outputs.argmax(dim=1)
            correct += (prediction== labels).sum().item()
            total += labels.size(0)

        #update learning rate with a change in
        scheduler.step()
        train_loss = running_loss / len(trainloader)
        train_acc = correct / total*100

        progress_bar.set_postfix({'Loss': train_loss, 'Accuracy': train_acc, })

        print(
            f"epoch: [{epoch+1}/{num_epochs}])"
            f"loss: {train_loss:.3f}"
            f"accuracy: {train_acc:.3f}%"
            f"correct: {correct}"
            f"total:{total}"
        )
        #save every 5th epoch
        if (epoch+1) % 5 == 0:
            torch.save(model.state_dict(), f'model_epoch_{epoch+1}.pth')

            print(f"Model saved: model_epoch_{epoch+1}.pth ")

            #set to eval mode
            model.eval()

            val_loss_total = 0.0
            val_correct = 0
            val_total = 0

            with torch.no_grad():

                for images, labels in valloader:
                    images = images.to(device)
                    labels = labels.to(device)

                    outputs = model(images)
                    loss = criterion(outputs, labels)
                    val_loss_total += loss.item()

                    prediction = outputs.argmax(dim=1)
                    val_correct += (prediction== labels).sum().item()
                    val_total += labels.size(0)

                val_loss = val_loss_total / len(valloader)
                val_acc = val_correct / val_total*100
                val_losses.append(val_loss)
                val_accs.append(val_acc)
                val_epochs.append(epoch + 1)

        train_losses.append(train_loss)
        train_accs.append(train_acc)
        train_epochs.append(epoch + 1)

    return train_losses, val_losses, train_accs, val_accs, train_epochs, val_epochs
True
Tesla T4

Step 6. Train the above model for 50 epochs, decay the learning rate by 0.1 at epoch=20 and epoch=30 and save the model for every five epoch. Training is performed under GPU. Monitor the progress of training process.¶

InĀ [10]:
#set number of epochs to 50
num_epochs = 50

#train model
train_losses, val_losses, train_accs, val_accs, train_epochs, val_epochs = train_model(model, trainloader,valloader, criterion, optimizer, num_epochs)
Epoch: ,1/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [25:39<00:00, 32.76s/it]
epoch: [1/50])loss: 2.211accuracy: 19.540%correct: 586total:2999
Epoch: ,2/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [2/50])loss: 2.015accuracy: 27.442%correct: 823total:2999
Epoch: ,3/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [3/50])loss: 1.859accuracy: 32.811%correct: 984total:2999
Epoch: ,4/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [4/50])loss: 1.744accuracy: 38.980%correct: 1169total:2999
Epoch: ,5/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:30<00:00,  1.56it/s]
epoch: [5/50])loss: 1.658accuracy: 42.481%correct: 1274total:2999
Model saved: model_epoch_5.pth 
Epoch: ,6/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [6/50])loss: 1.581accuracy: 44.782%correct: 1343total:2999
Epoch: ,7/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [7/50])loss: 1.511accuracy: 47.749%correct: 1432total:2999
Epoch: ,8/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [8/50])loss: 1.466accuracy: 48.383%correct: 1451total:2999
Epoch: ,9/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [9/50])loss: 1.438accuracy: 50.517%correct: 1515total:2999
Epoch: ,10/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [10/50])loss: 1.390accuracy: 51.751%correct: 1552total:2999
Model saved: model_epoch_10.pth 
Epoch: ,11/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [11/50])loss: 1.368accuracy: 51.951%correct: 1558total:2999
Epoch: ,12/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.63it/s]
epoch: [12/50])loss: 1.330accuracy: 55.018%correct: 1650total:2999
Epoch: ,13/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.63it/s]
epoch: [13/50])loss: 1.296accuracy: 55.385%correct: 1661total:2999
Epoch: ,14/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [14/50])loss: 1.265accuracy: 55.719%correct: 1671total:2999
Epoch: ,15/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [15/50])loss: 1.236accuracy: 57.386%correct: 1721total:2999
Model saved: model_epoch_15.pth 
Epoch: ,16/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [16/50])loss: 1.222accuracy: 57.619%correct: 1728total:2999
Epoch: ,17/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.62it/s]
epoch: [17/50])loss: 1.195accuracy: 59.120%correct: 1773total:2999
Epoch: ,18/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [18/50])loss: 1.153accuracy: 60.987%correct: 1829total:2999
Epoch: ,19/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [19/50])loss: 1.130accuracy: 61.721%correct: 1851total:2999
Epoch: ,20/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [20/50])loss: 1.143accuracy: 60.453%correct: 1813total:2999
Model saved: model_epoch_20.pth 
Epoch: ,21/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [21/50])loss: 1.011accuracy: 66.622%correct: 1998total:2999
Epoch: ,22/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [22/50])loss: 0.988accuracy: 67.189%correct: 2015total:2999
Epoch: ,23/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [23/50])loss: 0.981accuracy: 67.523%correct: 2025total:2999
Epoch: ,24/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [24/50])loss: 0.977accuracy: 67.723%correct: 2031total:2999
Epoch: ,25/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [25/50])loss: 0.967accuracy: 67.789%correct: 2033total:2999
Model saved: model_epoch_25.pth 
Epoch: ,26/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [26/50])loss: 0.961accuracy: 68.056%correct: 2041total:2999
Epoch: ,27/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [27/50])loss: 0.960accuracy: 68.723%correct: 2061total:2999
Epoch: ,28/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [28/50])loss: 0.948accuracy: 68.323%correct: 2049total:2999
Epoch: ,29/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [29/50])loss: 0.952accuracy: 68.089%correct: 2042total:2999
Epoch: ,30/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.57it/s]
epoch: [30/50])loss: 0.948accuracy: 68.423%correct: 2052total:2999
Model saved: model_epoch_30.pth 
Epoch: ,31/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [31/50])loss: 0.939accuracy: 68.523%correct: 2055total:2999
Epoch: ,32/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [32/50])loss: 0.932accuracy: 68.890%correct: 2066total:2999
Epoch: ,33/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [33/50])loss: 0.928accuracy: 69.256%correct: 2077total:2999
Epoch: ,34/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.57it/s]
epoch: [34/50])loss: 0.923accuracy: 69.490%correct: 2084total:2999
Epoch: ,35/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [35/50])loss: 0.923accuracy: 69.423%correct: 2082total:2999
Model saved: model_epoch_35.pth 
Epoch: ,36/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [36/50])loss: 0.921accuracy: 69.456%correct: 2083total:2999
Epoch: ,37/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [37/50])loss: 0.928accuracy: 68.956%correct: 2068total:2999
Epoch: ,38/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [38/50])loss: 0.921accuracy: 69.423%correct: 2082total:2999
Epoch: ,39/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [39/50])loss: 0.921accuracy: 69.156%correct: 2074total:2999
Epoch: ,40/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [40/50])loss: 0.924accuracy: 69.190%correct: 2075total:2999
Model saved: model_epoch_40.pth 
Epoch: ,41/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [41/50])loss: 0.923accuracy: 68.890%correct: 2066total:2999
Epoch: ,42/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [42/50])loss: 0.914accuracy: 69.823%correct: 2094total:2999
Epoch: ,43/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [43/50])loss: 0.924accuracy: 69.557%correct: 2086total:2999
Epoch: ,44/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:30<00:00,  1.55it/s]
epoch: [44/50])loss: 0.921accuracy: 70.157%correct: 2104total:2999
Epoch: ,45/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [45/50])loss: 0.923accuracy: 69.390%correct: 2081total:2999
Model saved: model_epoch_45.pth 
Epoch: ,46/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [46/50])loss: 0.922accuracy: 69.356%correct: 2080total:2999
Epoch: ,47/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [47/50])loss: 0.924accuracy: 68.823%correct: 2064total:2999
Epoch: ,48/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [48/50])loss: 0.923accuracy: 70.057%correct: 2101total:2999
Epoch: ,49/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [49/50])loss: 0.917accuracy: 69.657%correct: 2089total:2999
Epoch: ,50/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [50/50])loss: 0.916accuracy: 69.290%correct: 2078total:2999
Model saved: model_epoch_50.pth 

Step 7. Select the best model, i.e., the model having the best performance, from all the models saved in the previous step. Evaluate this best model on the testing set and calculate the prediction accuracy.¶

InĀ [11]:
# Select best model from saved models

#examine plots of validation v training

plt.figure(figsize=(10, 5))
plt.plot(train_epochs, train_losses, label="Training Loss")
plt.plot(val_epochs, val_losses, marker="o", label="Validation Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title("Training and Validation Loss")
plt.legend()
plt.grid(True)
plt.show()

plt.figure(figsize=(10, 5))
plt.plot(train_epochs, train_accs, label="Training Accuracy")
plt.plot(val_epochs, val_accs, marker = "o",label="Validation Accuracy")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.title("Training and Validation Accuracy")
plt.legend()
plt.grid(True)
plt.show()


# Find the validation checkpoint with the lowest validation loss
best_index = val_losses.index(min(val_losses))

best_val_loss = val_losses[best_index]
best_epoch = val_epochs[best_index]
best_model = f'model_epoch_{best_epoch}.pth'

print(f"lowest validation loss: {best_val_loss:.4f}")
print(f"corresponds to epoch: {best_epoch} so we will use that model")

def evaluate_model(model, dataloader):

    model.eval()

    test_correct = 0
    test_loss_total = 0.0
    test_total = 0

    with torch.no_grad():
      for images, labels in dataloader:
                    images = images.to(device)
                    labels = labels.to(device)

                    outputs = model(images)
                    loss = criterion(outputs, labels)


                    test_loss_total += loss.item() * labels.size(0)

                    prediction = outputs.argmax(dim=1)
                    test_correct += (prediction== labels).sum().item()
                    test_total += labels.size(0)

      test_loss = test_loss_total / test_total
      test_acc = test_correct / test_total * 100

      return test_acc

#load best model and classify unseen test data

model = Model(num_classes=10).to(device)
model.load_state_dict(torch.load(best_model))
result = evaluate_model(model,testloader)
print(f"The predictive accuracy of the chosen model is {result}%")

total_params = sum(p.numel() for p in model.parameters())

print(f"Total parameters: {total_params:,}")
No description has been provided for this image
No description has been provided for this image
lowest validation loss: 1.1218
corresponds to epoch: 50 so we will use that model
The predictive accuracy of the chosen model is 64.64702612562535%
Total parameters: 56,995,530

Step 9. Make improvements to model.¶

InĀ [12]:
import torch
import torch.nn as nn
import torch.optim as optim

#define modified model
class Model_mod(nn.Module):

    def __init__(self, num_classes=10):

        super(Model_mod, self).__init__()

        self.net = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4),
            nn.ReLU(),
            nn.BatchNorm2d(96),
            #change Ave to Max
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(96, 256, 5, padding=2),
            nn.ReLU(),
            nn.BatchNorm2d(256),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(256, 384, 3, padding=1),
            nn.ReLU(),
            nn.Conv2d(384, 256, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )

        self.classifier = nn.Sequential(
            nn.Linear(in_features=(256 * 6 * 6), out_features=4096),
            #add reLU and Dropout
            nn.ReLU(),
            nn.Dropout(0.5),
            nn.Linear(in_features=4096, out_features=4096),
            nn.ReLU(),
            nn.Dropout(0.5),
            nn.Linear(in_features=4096, out_features=num_classes),
        )

    def forward(self, x):

        output = self.net(x)
        output = output.view(output.size()[0],-1)
        output = self.classifier(output)

        return output


#set testing environment using the same set-up as previous model
net_mod = Model_mod(num_classes=10)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net_mod.parameters() , lr=0.01, weight_decay=5e-4)

#schedule decay of learning rate by 0.1 at epochs 20 and 30
scheduler = MultiStepLR(optimizer, milestones=[20, 30], gamma=0.1)


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net_mod = net_mod.to(device)


#train model using 50 epochs
train_losses, val_losses, train_accs, val_accs, train_epochs, val_epochs = train_model(net_mod, trainloader,valloader, criterion, optimizer, num_epochs)
Epoch: ,1/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [1/50])loss: 2.269accuracy: 12.738%correct: 382total:2999
Epoch: ,2/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.62it/s]
epoch: [2/50])loss: 2.112accuracy: 26.442%correct: 793total:2999
Epoch: ,3/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [3/50])loss: 1.880accuracy: 32.744%correct: 982total:2999
Epoch: ,4/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [4/50])loss: 1.762accuracy: 37.212%correct: 1116total:2999
Epoch: ,5/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.63it/s]
epoch: [5/50])loss: 1.636accuracy: 42.948%correct: 1288total:2999
Model saved: model_epoch_5.pth 
Epoch: ,6/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [6/50])loss: 1.563accuracy: 45.448%correct: 1363total:2999
Epoch: ,7/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [7/50])loss: 1.508accuracy: 47.983%correct: 1439total:2999
Epoch: ,8/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [8/50])loss: 1.428accuracy: 50.884%correct: 1526total:2999
Epoch: ,9/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [9/50])loss: 1.403accuracy: 51.884%correct: 1556total:2999
Epoch: ,10/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.62it/s]
epoch: [10/50])loss: 1.338accuracy: 52.618%correct: 1578total:2999
Model saved: model_epoch_10.pth 
Epoch: ,11/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [11/50])loss: 1.277accuracy: 55.685%correct: 1670total:2999
Epoch: ,12/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.63it/s]
epoch: [12/50])loss: 1.255accuracy: 56.852%correct: 1705total:2999
Epoch: ,13/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [13/50])loss: 1.184accuracy: 59.120%correct: 1773total:2999
Epoch: ,14/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.62it/s]
epoch: [14/50])loss: 1.161accuracy: 59.220%correct: 1776total:2999
Epoch: ,15/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [15/50])loss: 1.122accuracy: 63.254%correct: 1897total:2999
Model saved: model_epoch_15.pth 
Epoch: ,16/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.62it/s]
epoch: [16/50])loss: 1.071accuracy: 63.321%correct: 1899total:2999
Epoch: ,17/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [17/50])loss: 1.077accuracy: 63.321%correct: 1899total:2999
Epoch: ,18/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [18/50])loss: 1.024accuracy: 65.622%correct: 1968total:2999
Epoch: ,19/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.62it/s]
epoch: [19/50])loss: 0.986accuracy: 66.922%correct: 2007total:2999
Epoch: ,20/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [20/50])loss: 0.947accuracy: 68.223%correct: 2046total:2999
Model saved: model_epoch_20.pth 
Epoch: ,21/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [21/50])loss: 0.823accuracy: 72.057%correct: 2161total:2999
Epoch: ,22/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [22/50])loss: 0.778accuracy: 73.858%correct: 2215total:2999
Epoch: ,23/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [23/50])loss: 0.785accuracy: 74.525%correct: 2235total:2999
Epoch: ,24/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.62it/s]
epoch: [24/50])loss: 0.776accuracy: 73.791%correct: 2213total:2999
Epoch: ,25/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [25/50])loss: 0.771accuracy: 74.091%correct: 2222total:2999
Model saved: model_epoch_25.pth 
Epoch: ,26/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [26/50])loss: 0.751accuracy: 76.059%correct: 2281total:2999
Epoch: ,27/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.62it/s]
epoch: [27/50])loss: 0.755accuracy: 75.692%correct: 2270total:2999
Epoch: ,28/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.59it/s]
epoch: [28/50])loss: 0.742accuracy: 75.258%correct: 2257total:2999
Epoch: ,29/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.62it/s]
epoch: [29/50])loss: 0.729accuracy: 75.692%correct: 2270total:2999
Epoch: ,30/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.62it/s]
epoch: [30/50])loss: 0.719accuracy: 76.225%correct: 2286total:2999
Model saved: model_epoch_30.pth 
Epoch: ,31/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.62it/s]
epoch: [31/50])loss: 0.717accuracy: 76.726%correct: 2301total:2999
Epoch: ,32/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [32/50])loss: 0.711accuracy: 76.659%correct: 2299total:2999
Epoch: ,33/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [33/50])loss: 0.712accuracy: 76.259%correct: 2287total:2999
Epoch: ,34/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [34/50])loss: 0.704accuracy: 76.659%correct: 2299total:2999
Epoch: ,35/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [35/50])loss: 0.701accuracy: 76.726%correct: 2301total:2999
Model saved: model_epoch_35.pth 
Epoch: ,36/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [36/50])loss: 0.703accuracy: 76.726%correct: 2301total:2999
Epoch: ,37/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.62it/s]
epoch: [37/50])loss: 0.699accuracy: 77.126%correct: 2313total:2999
Epoch: ,38/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.62it/s]
epoch: [38/50])loss: 0.704accuracy: 76.592%correct: 2297total:2999
Epoch: ,39/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [39/50])loss: 0.713accuracy: 76.092%correct: 2282total:2999
Epoch: ,40/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:28<00:00,  1.63it/s]
epoch: [40/50])loss: 0.698accuracy: 77.559%correct: 2326total:2999
Model saved: model_epoch_40.pth 
Epoch: ,41/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.61it/s]
epoch: [41/50])loss: 0.692accuracy: 77.192%correct: 2315total:2999
Epoch: ,42/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [42/50])loss: 0.702accuracy: 77.059%correct: 2311total:2999
Epoch: ,43/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [43/50])loss: 0.698accuracy: 76.859%correct: 2305total:2999
Epoch: ,44/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [44/50])loss: 0.708accuracy: 76.492%correct: 2294total:2999
Epoch: ,45/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [45/50])loss: 0.697accuracy: 76.792%correct: 2303total:2999
Model saved: model_epoch_45.pth 
Epoch: ,46/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [46/50])loss: 0.707accuracy: 77.026%correct: 2310total:2999
Epoch: ,47/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.58it/s]
epoch: [47/50])loss: 0.695accuracy: 76.425%correct: 2292total:2999
Epoch: ,48/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [48/50])loss: 0.705accuracy: 75.859%correct: 2275total:2999
Epoch: ,49/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.57it/s]
epoch: [49/50])loss: 0.694accuracy: 76.492%correct: 2294total:2999
Epoch: ,50/50: 100%|ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ| 47/47 [00:29<00:00,  1.60it/s]
epoch: [50/50])loss: 0.698accuracy: 76.259%correct: 2287total:2999
Model saved: model_epoch_50.pth 
InĀ [13]:
import matplotlib.pyplot as plt


# Select best model from saved models

#examine plots of validation v training

plt.figure(figsize=(10, 5))
plt.plot(train_epochs, train_losses, label="Training Loss")
plt.plot(val_epochs, val_losses, marker="o", label="Validation Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title("Training and Validation Loss")
plt.legend()
plt.grid(True)
plt.show()

plt.figure(figsize=(10, 5))
plt.plot(train_epochs, train_accs, label="Training Accuracy")
plt.plot(val_epochs, val_accs, marker = "o",label="Validation Accuracy")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.title("Training and Validation Accuracy")
plt.legend()
plt.grid(True)
plt.show()


# Find the validation checkpoint with the lowest validation loss
best_index = val_losses.index(min(val_losses))

best_val_loss = val_losses[best_index]
best_epoch = val_epochs[best_index]
best_model = f'model_epoch_{best_epoch}.pth'

print(f"lowest validation loss: {best_val_loss:.4f}")
print(f"corresponds to epoch: {best_epoch} so we will use that model")


#load best model and classify unseen test data

model = Model_mod(num_classes=10).to(device)
model.load_state_dict(torch.load(best_model))
result = evaluate_model(model,testloader)
print(f"The predictive accuracy of the chosen model is {result}%")

total_params = sum(p.numel() for p in model.parameters())

print(f"Total parameters: {total_params:,}")
No description has been provided for this image
No description has been provided for this image
lowest validation loss: 0.8780
corresponds to epoch: 45 so we will use that model
The predictive accuracy of the chosen model is 72.04002223457476%
Total parameters: 56,995,530

Step 10. Report the classification performance of the two models in terms of the model complexity vs the predictive accuracy. .¶

The modified model achieved higher predictive accuracy than the original model with accuracy using test data of approx 72% and versus 64% for the original model.

This increase in predictive performance has been achieved without a significant increase in model complexity. In fact, the extra ReLU and Dropout layers have not increased the number of parameters (approx 57 million).

In addition the small gap between training and validation losses suggests that the modified model generalised reasonably well and overfitting does not appear to be a major concern. The original model showed lower training/validation and test performance suggesting lower leaning capacity and potentially some underfitting.

  1. Step 11 Create Visualisation to display an example prediction
InĀ [19]:
import torch
import matplotlib.pyplot as plt
from torchvision import transforms

# Select an image from the test dataset
sample_index = 1

dataset_index = test_data.indices[sample_index]

image_path, actual_label = dataset.samples[dataset_index]

# Load the original image
original_image = dataset.loader(image_path)

# Prepare image without random augmentation
display_transform = transforms.Compose([
    transforms.Resize(input_size),
    transforms.CenterCrop(input_size)
])

prediction_transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(
        [0.485, 0.456, 0.406],
        [0.229, 0.224, 0.225]
    )
])

display_image = display_transform(original_image)

image_tensor = prediction_transform(display_image)

# Add batch dimension
image_tensor = image_tensor.unsqueeze(0).to(device)

# Generate prediction
model.eval()

with torch.inference_mode():

    outputs = model(image_tensor)

    probabilities = torch.softmax(outputs, dim=1)[0]

# Identify the four most probable classes
top_probs, top_indices = torch.topk(probabilities, k=4)

top_probs = top_probs.cpu().numpy() * 100
top_indices = top_indices.cpu().numpy()

class_names = dataset.classes

predicted_class = class_names[top_indices[0]]
actual_class = class_names[actual_label]

print(f"Actual class: {actual_class}")
print(f"Predicted class: {predicted_class}")
print(f"Confidence: {top_probs[0]:.2f}%")

for idx, prob in zip(top_indices, top_probs):
    print(f"{class_names[idx]}: {prob:.2f}%")

plt.imshow(display_image)
plt.axis("off")
plt.show()
Actual class: n01749939
Predicted class: n01749939
Confidence: 90.43%
n01749939: 90.43%
n01770081: 7.25%
n01930112: 2.28%
n01532829: 0.02%
No description has been provided for this image
InĀ [20]:
import nltk

nltk.download("wordnet")

from nltk.corpus import wordnet as wn

def readable_class_name(class_id):

    synset = wn.synset_from_pos_and_offset(
        class_id[0],
        int(class_id[1:])
    )

    return synset.lemma_names()[0].replace("_", " ").title()
[nltk_data] Downloading package wordnet to /root/nltk_data...
[nltk_data]   Package wordnet is already up-to-date!
InĀ [21]:
class_names = [
    readable_class_name(c)
    for c in dataset.classes
]

predicted_class = class_names[top_indices[0]]
actual_class = class_names[actual_label]

print(class_names)
['House Finch', 'Robin', 'Triceratops', 'Green Mamba', 'Harvestman', 'Toucan', 'Goose', 'Jellyfish', 'Nematode', 'King Crab']
InĀ [22]:
import matplotlib.pyplot as plt
import numpy as np

red = "#C71E31"
grey = "#999999"
background = "#F5F4F0"

fig, (ax1, ax2) = plt.subplots(
    1, 2,
    figsize=(8, 4.5),
    gridspec_kw={"width_ratios": [1, 1.1]}
)

fig.patch.set_facecolor(background)

# Display the actual test image
ax1.imshow(display_image)
ax1.axis("off")

ax1.set_title(
    "INPUT IMAGE",
    fontsize=10,
    color="#666666",
    loc="left",
    pad=12
)

# Classification probabilities
ax2.set_facecolor(background)

labels = [class_names[i] for i in top_indices]

y = np.arange(len(labels))

# Background probability bars
ax2.barh(
    y,
    [100] * len(labels),
    color="#DDDDDD",
    height=0.15
)

# Actual probability bars
ax2.barh(
    y,
    top_probs,
    color=[red, grey, grey, grey],
    height=0.15
)

# Class labels and percentages
for i, (label, prob) in enumerate(zip(labels, top_probs)):

    ax2.text(
        0, i - 0.23,
        label,
        fontsize=10,
        color="#333333"
    )

    ax2.text(
        100, i - 0.23,
        f"{prob:.1f}%",
        ha="right",
        fontsize=10,
        color="#333333"
    )

ax2.set_xlim(0, 100)
ax2.set_ylim(len(labels) - 0.5, -0.7)
ax2.axis("off")

ax2.set_title(
    f"{predicted_class}\n{top_probs[0]:.1f}%",
    loc="left",
    fontsize=22,
    fontweight="bold",
    color=red,
    pad=20
)

fig.text(
    0.05, 0.94,
    "COMPUTER VISION / CNN",
    fontsize=9,
    color="#666666"
)

fig.text(
    0.05, 0.04,
    f"ACTUAL CLASS: {actual_class.upper()}",
    fontsize=9,
    color="#666666"
)

fig.text(
    0.95, 0.04,
    "ACTUAL MODEL PREDICTION",
    fontsize=9,
    color=red,
    ha="right"
)

plt.tight_layout(rect=[0.03, 0.09, 0.97, 0.89])

plt.savefig(
    "classification-prediction.png",
    dpi=200,
    bbox_inches="tight",
    facecolor=background
)

plt.show()
No description has been provided for this image
InĀ [23]:
from google.colab import files

files.download("classification-prediction.png")