Pages


<aside>

Home | Model Architechture | Model Training | Datasets | Data Preprocessing | Libraries | Training Analysis | Full Code Breakdown

</aside>


<aside>

First, we import the libraries that will be used.

import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
import seaborn as sns
import requests
import gradio as gr

from io import BytesIO
from PIL import Image
from sklearn import preprocessing
from sklearn.metrics import classification_report, confusion_matrix
from torchvision import datasets, transforms

Then, we define the transformation composition that will be used for train data.

More explaination on Data Preprocessing.

transform = transforms.Compose([
    transforms.RandomHorizontalFlip(),
    transforms.RandomAffine(30, fill=0),  
    transforms.RandomVerticalFlip(),
    transforms.RandomRotation(30),
    transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
    transforms.GaussianBlur(kernel_size=(5, 5), sigma=(0.1, 2.0)),
    transforms.RandomGrayscale(p=0.2),
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

Define the transformation composition for test data

transform_test = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

Set the training and test data to the correct path

data_dir = "C:\\Users\\danis\\Local\\Tutorial Week 7_Working with Python\\Sample Data\\archive\\animals\\animals\\resized128"
test_dir = os.path.join(os.path.expanduser("~"), "Downloads", "Test128_Trimmed")

Now we apply the data transformation for training data with train_data = datasets.ImageFolder(root=data_dir, transform=transform) and put it into train data.

We will do the same for test data with test_data = datasets.ImageFolder(root=test_dir, transform=transform_test).

train_data = datasets.ImageFolder(root=data_dir, transform=transform)
test_data = datasets.ImageFolder(root=test_dir, transform=transform_test)

Next, we insert train_data and test_data into memory for faster processing.

train_data_in_memory = [(img, label) for img, label in train_data]
test_data_in_memory = [(img, label) for img, label in test_data]

Then, we create dataloader for train_data and test_data. Using 32 as our batch size, shuffle=true to randomize the data order, num_worker=2 for faster I/O, prefetch_factor=2 to ensure there is no downtime in data loading, pin_memory=True to lock data in memory for faster fetching and persistent_workers=true so we dont need to initializes dataloader multiple time.

train_loader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=True, num_workers=2, prefetch_factor=2, pin_memory=True, persistent_workers=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=32, shuffle=True, num_workers=2, prefetch_factor=2, pin_memory=True, persistent_workers=True)

Define an array with the class names and print the class name from train_data to check if the order is correct.

class_names = ['badger','elephant','penguin','shark','tiger']
print(train_data.class_to_idx)

Create the class for model architechture. This includes both the model definitions and forward pass.

More information at Model Architechture.

class NeuralNet(nn.Module):
    def __init__(self):
        super().__init__()

        # Convolutional layers with batch normalization
        self.conv1 = nn.Conv2d(3, 32, 5)  # 128x128 -> 124x124
        self.bn1 = nn.BatchNorm2d(32)  # Batch normalization for first conv layer
        self.pool = nn.MaxPool2d(2, 2)  # Pooling layer

        self.conv2 = nn.Conv2d(32, 64, 5)  # 124x124 -> 120x120
        self.bn2 = nn.BatchNorm2d(64)  # Batch normalization for second conv layer

        self.conv3 = nn.Conv2d(64, 128, 3)  # 60x60 -> 56x56
        self.bn3 = nn.BatchNorm2d(128)  # Batch normalization for third conv layer

        # Fully connected layers with batch normalization
        self.fc1 = nn.Linear(128 * 13 * 13, 512)  # Adjust based on the final output shape
        self.bn_fc1 = nn.BatchNorm1d(512)  # Batch normalization for first fully connected layer

        self.fc2 = nn.Linear(512, 256)
        self.bn_fc2 = nn.BatchNorm1d(256)  # Batch normalization for second fully connected layer

        self.fc3 = nn.Linear(256, 5)
        self.dropout = nn.Dropout(0.5)

    def forward(self, x):
        x = self.pool(F.relu(self.bn1(self.conv1(x))))  # Conv1 + BatchNorm + ReLU + Pool
        x = self.pool(F.relu(self.bn2(self.conv2(x))))  # Conv2 + BatchNorm + ReLU + Pool
        x = self.pool(F.relu(self.bn3(self.conv3(x))))  # Conv3 + BatchNorm + ReLU + Pool

        x = torch.flatten(x, 1)  # Flatten from (batch_size, 128, 14, 14) to (batch_size, 25088)

        x = F.relu(self.bn_fc1(self.fc1(x)))  # FC1 + BatchNorm + ReLU
        x = self.dropout(x)  # Dropout
        x = F.relu(self.bn_fc2(self.fc2(x)))  # FC2 + BatchNorm + ReLU
        x = self.fc3(x)  # Output layer

        return x

Insert our model into variable net to be used later on training loop. Then define our loss_function, we will be using Cross Entropy. Set the optimizer as Adam with initial learning rate of 0.001 and trhe scheduler as ReduceLROnPlateau.

More explaination on Model Training.

net = NeuralNet()
loss_function = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=5)

Now, we check if the current device have CUDA-supported GPU. If it returned true, then we will move the model to the GPU.

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

Define our EarlyStopper class. It will be executed when the validation loss result plateaud for too long.

More explaination on Model Training.

class EarlyStopper:
    def __init__(self, patience=1, min_delta=0):
        self.patience = patience
        self.min_delta = min_delta
        self.counter = 0
        self.min_validation_loss = float('inf')

    def early_stop(self, validation_loss):
        if validation_loss < self.min_validation_loss:
            self.min_validation_loss = validation_loss
            self.counter = 0
        elif validation_loss > (self.min_validation_loss + self.min_delta):
            self.counter += 1
            if self.counter >= self.patience:
                return True
        return False

This is the model training loop with epoch 100, however since we are using early_stopper, it will stop the loop when validation loss plateaud for 10 times. More explaination on Model Training.

early_stopper = EarlyStopper(patience=10, min_delta=0.001)

for epoch in range(100):
    print(f'Training epoch {epoch}...')
    running_loss = 0.0

    net.train()
    for i, data in enumerate(train_loader):
        inputs, labels = data[0].to(device, non_blocking=True), data[1].to(device, non_blocking=True)

        optimizer.zero_grad()
        outputs = net(inputs)
        loss = loss_function(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()

    print(f'Loss: {running_loss / len(train_loader):.4f}')

    # Validation step
    val_loss = 0.0
    net.eval()
    with torch.no_grad():
        for i, data in enumerate(test_loader):
            inputs, labels = data[0].to(device, non_blocking=True), data[1].to(device, non_blocking=True)
            outputs = net(inputs)
            loss = loss_function(outputs, labels)
            val_loss += loss.item()

    avg_val_loss = val_loss / len(test_loader)
    print(f'Validation Loss: {avg_val_loss:.4f}')

    if early_stopper.early_stop(avg_val_loss):             
        print("Early stopping triggered.")
        break

    # Scheduler step
    scheduler.step(avg_val_loss)

    # Log learning rate
    current_lr = optimizer.param_groups[0]['lr']
    print(f'Current Learning Rate: {current_lr:.6f}')

After the model finished the training, save the model as a .pth file.

torch.save(net.state_dict(), 'Model Save\\trained_netv6.pth')

Now, load our saved model for evaluation purposes.

net = NeuralNet()
net.load_state_dict(torch.load('Model Save\\trained_netv6.pth', weights_only=True))

By using the data in test_loader, generate an accuracy percentage by inputting the data into our model.

correct = 0
total = 0

net.eval()

with torch.no_grad():
    for data in test_loader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

accuracy = 100 * correct/total

print(f'Accuracy: {accuracy}%')

Generate precision, recall, f1-score, support using classification_report to get more insights on which class is performing well or worse.

net= net.to(device)

true_labels = []
predicted_labels = []

net.eval()

with torch.no_grad():
    for data in test_loader:
        images, labels = data
        images, labels = images.to(device), labels.to(device)
        
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        
        true_labels.extend(labels.cpu().numpy()) 
        predicted_labels.extend(predicted.cpu().numpy())

report = classification_report(true_labels, predicted_labels, target_names=class_names)

print(report)

Now, we can plot the confusion matrix to see our data distribution based on the predicted and actual output.

# Create lists to store true and predicted labels
true_labels = []
predicted_labels = []

net.eval()  # Set the model to evaluation mode
with torch.no_grad():
    for data in test_loader:
        images, labels = data
        images, labels = images.to(device), labels.to(device)
        
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        
        true_labels.extend(labels.cpu().numpy())  # Convert to numpy and add to list
        predicted_labels.extend(predicted.cpu().numpy())  # Convert to numpy and add to list

# Compute confusion matrix
cm = confusion_matrix(true_labels, predicted_labels)

# Plot confusion matrix using seaborn
plt.figure(figsize=(10, 7))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_names, yticklabels=class_names)
plt.xlabel('Predicted Labels')
plt.ylabel('True Labels')
plt.title('Confusion Matrix')
plt.show()

This block of code runs data evaluation but with softmax output for better reperesentation on the GUI.

def predict_with_probs(image_input, model, class_names):
    if image_input is None:
        return "No image provided. Please upload an image or provide a valid URL.", None

    if isinstance(image_input, str):
        if image_input.startswith("http"):
            response = requests.get(image_input)
            img = Image.open(BytesIO(response.content)).convert("RGB")
        else:
            img = Image.open(image_input).convert("RGB")
    elif isinstance(image_input, Image.Image):
        img = image_input.convert("RGB")
    else:
        raise ValueError("Unsupported input type. Please provide a valid image or URL.")

    # Apply transformations
    transform = transforms.Compose([
        transforms.Resize((128, 128)),
        transforms.ToTensor(),
        transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ])
    img = transform(img).unsqueeze(0)  # Add batch dimension

    # Move to device
    img = img.to(device)

    # Model inference
    model.eval()
    with torch.no_grad():
        logits = model(img)  # Get raw logits
        print("Logits: ", logits)
        probabilities = F.softmax(logits, dim=1)  # Apply softmax

    predicted_class_idx = torch.argmax(probabilities, dim=1).item()
    predicted_class = class_names[predicted_class_idx]
    probs = probabilities.cpu().numpy()[0]  # Convert to numpy array
    probs_text = {class_names[i]: probs[i].item() for i in range(len(class_names))}

    return predicted_class, probs_text

Finally, we run our GUI interface built on Gradio, a web-based interface mostly used for AI purposes.

def gradio_interface(image):
    predicted_class, prob_text = predict_with_probs(image, net, class_names)

    if prob_text is None:
        return "No image provided. Please upload an image or provide a valid URL.", None
    
    return predicted_class, prob_text

iface = gr.Interface(
    fn=gradio_interface,
    inputs=gr.Image(type="pil", sources=['upload','clipboard'],label="Upload Image or URL"),
    outputs=[
    gr.Textbox(label="Predicted Class"),
    gr.Label(num_top_classes=5,label="Probability Graph")
    ],
    live=True
)

iface.launch()

</aside>