Certainly! Below is a comprehensive Google Colab notebook code that utilizes a pre-trained Vision Transformer (ViT) to classify images into two classes: "BF" and "NR". The notebook includes all necessary dependencies, data visualization steps, and instructions to set up the data directories.
Overview of the Steps:
- Setup and Install Dependencies
- Import Libraries
- Mount Google Drive (if data is stored there)
- Data Visualization
- Prepare Data Loaders
- Load Pretrained ViT Model
- Define Training Parameters
- Train the Model
- Evaluate the Model
1. Setup and Install Dependencies
First, ensure that all necessary libraries are installed. We'll use torch, torchvision, timm (for Vision Transformer models), and other essential libraries.
# Install necessary libraries
!pip install torch torchvision torchaudio --quiet
!pip install timm --quiet
!pip install matplotlib --quiet
!pip install seaborn --quiet
2. Import Libraries
Import all the required libraries for data handling, visualization, and model training.
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import timm
from sklearn.metrics import confusion_matrix, classification_report
%matplotlib inline
3. Mount Google Drive (Optional)
If your dataset is stored in Google Drive, you can mount it. Otherwise, ensure your Train and Test folders are uploaded to the Colab environment.
from google.colab import drive
drive.mount('/content/drive')
Adjust the path to your data directories accordingly.
4. Define Data Directories
Set the paths to your training and testing data directories.
# Define the data directory
data_dir = '/content/data' # Update this path if your data is in a different location
train_dir = os.path.join(data_dir, 'Train')
test_dir = os.path.join(data_dir, 'Test')
5. Data Visualization
Visualize some sample images from each class to understand your dataset better.
import random
from torchvision.utils import make_grid
# Define image transformations for visualization (no normalization)
viz_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor()
])
# Load a small subset for visualization
viz_dataset = datasets.ImageFolder(root=train_dir, transform=viz_transform)
class_names = viz_dataset.classes
print("Classes:", class_names)
# Function to show images
def imshow(inp, title=None):
inp = inp.numpy().transpose((1, 2, 0))
plt.figure(figsize=(12, 6))
plt.imshow(inp)
if title:
plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated
# Get a batch of training data
inputs, classes_batch = next(iter(DataLoader(viz_dataset, batch_size=8, shuffle=True)))
# Make a grid from batch
out = make_grid(inputs)
imshow(out, title=[class_names[x] for x in classes_batch])
6. Prepare Data Loaders
Define the data transformations, including normalization, and create data loaders for training and testing.
# Define transformations for training and testing
train_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], # ImageNet means
std=[0.229, 0.224, 0.225]) # ImageNet stds
])
test_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
# Create datasets
train_dataset = datasets.ImageFolder(root=train_dir, transform=train_transform)
test_dataset = datasets.ImageFolder(root=test_dir, transform=test_transform)
# Define data loaders
batch_size = 32
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=2)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=2)
print(f"Number of training samples: {len(train_dataset)}")
print(f"Number of testing samples: {len(test_dataset)}")
7. Load Pretrained ViT Model
We'll use the timm library to load a pre-trained Vision Transformer model and modify the final layer for our binary classification task.
# Check if CUDA is available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Load a pretrained ViT model
model = timm.create_model('vit_base_patch16_224', pretrained=True)
# Modify the classification head
num_features = model.head.in_features
model.head = nn.Linear(num_features, 2) # Binary classification
model = model.to(device)
8. Define Training Parameters
Set up the loss function, optimizer, and learning rate scheduler.
# Define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=3e-4)
# Learning rate scheduler (optional)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)
9. Train the Model
Define the training loop and train the model for a specified number of epochs.
from tqdm import tqdm
def train_model(model, criterion, optimizer, scheduler, num_epochs=10):
train_losses = []
test_losses = []
best_acc = 0.0
for epoch in range(num_epochs):
print(f'Epoch {epoch+1}/{num_epochs}')
print('-' * 10)
# Training phase
model.train()
running_loss = 0.0
running_corrects = 0
loop = tqdm(train_loader, desc='Training', leave=False)
for inputs, labels in loop:
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
# Forward pass
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# Backward and optimize
loss.backward()
optimizer.step()
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
loop.set_postfix(loss=loss.item())
scheduler.step()
epoch_loss = running_loss / len(train_dataset)
epoch_acc = running_corrects.double() / len(train_dataset)
train_losses.append(epoch_loss)
print(f'Train Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
# Evaluation phase
model.eval()
running_loss = 0.0
running_corrects = 0
with torch.no_grad():
loop = tqdm(test_loader, desc='Evaluating', leave=False)
for inputs, labels in loop:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
loop.set_postfix(loss=loss.item())
epoch_loss = running_loss / len(test_dataset)
epoch_acc = running_corrects.double() / len(test_dataset)
test_losses.append(epoch_loss)
print(f'Test Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
# Deep copy the model
if epoch_acc > best_acc:
best_acc = epoch_acc
torch.save(model.state_dict(), 'best_vit_model.pth')
print(f'Best Test Acc: {best_acc:.4f}')
return train_losses, test_losses
# Train the model
num_epochs = 10
train_losses, test_losses = train_model(model, criterion, optimizer, scheduler, num_epochs=num_epochs)
10. Evaluate the Model
After training, evaluate the model on the test set and visualize the results using a confusion matrix and classification report.
# Load the best model
model.load_state_dict(torch.load('best_vit_model.pth'))
# Function to evaluate the model
def evaluate_model(model, dataloader, class_names):
model.eval()
all_preds = []
all_labels = []
with torch.no_grad():
loop = tqdm(dataloader, desc='Evaluating', leave=False)
for inputs, labels in loop:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
all_preds.extend(preds.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
# Confusion Matrix
cm = confusion_matrix(all_labels, all_preds)
plt.figure(figsize=(6,5))
sns.heatmap(cm, annot=True, fmt='d', xticklabels=class_names, yticklabels=class_names, cmap='Blues')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()
# Classification Report
print("Classification Report:")
print(classification_report(all_labels, all_preds, target_names=class_names))
# Evaluate the best model
evaluate_model(model, test_loader, class_names)
11. Visualize Training Progress
Plot the training and testing loss over epochs to monitor the model's learning progress.
# Plot training and testing loss
epochs = range(1, num_epochs + 1)
plt.figure(figsize=(10,5))
plt.plot(epochs, train_losses, 'b-', label='Training Loss')
plt.plot(epochs, test_losses, 'r-', label='Testing Loss')
plt.title('Training and Testing Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
Notes:
- Data Directory Structure: Ensure that your data directory (
/content/data) has the following structure:
data/
Train/
BF/
img1.jpg
img2.jpg
...
NR/
img1.jpg
img2.jpg
...
Test/
BF/
img1.jpg
img2.jpg
...
NR/
img1.jpg
img2.jpg
...
- GPU Acceleration: Make sure that GPU is enabled in your Google Colab notebook for faster training. You can enable it by going to
Runtime > Change runtime type > Hardware accelerator > GPU.
- Adjust Hyperparameters: Feel free to adjust hyperparameters such as
batch_size, learning rate, and num_epochs based on your dataset size and computational resources.
- Fine-tuning Strategies: The above code fine-tunes the entire ViT model. For faster training, you can freeze early layers and only train the classifier head by uncommenting the following lines before defining the optimizer:
for param in model.parameters():
param.requires_grad = False
# Only train the classifier head
for param in model.head.parameters():
param.requires_grad = True
- Saving and Loading Models: The best model based on test accuracy is saved as
best_vit_model.pth. You can load this model anytime for inference by using the torch.load method as shown in the evaluation section.
This comprehensive setup should help you leverage a pre-trained Vision Transformer for your binary classification task in Google Colab. Let me know if you have any questions or need further assistance!