Comprehensive Guide to Fine-Tuning an Image Captioning Model on Google Colab (CPU Runtime)
Image captioning is a critical task in computer vision and natural language processing, involving the generation of descriptive sentences for images. Fine-tuning a pre-trained image captioning model allows you to adapt it to specific datasets or improve its performance on particular tasks. This guide will walk you through the entire process of fine-tuning an image captioning model using Google Colab with a CPU runtime.
Note: While using a CPU is feasible, image captioning models are typically resource-intensive. Fine-tuning on a CPU may be slower compared to using GPUs. However, for smaller datasets or lightweight models, CPU runtime can suffice.
Table of Contents
- Prerequisites
- Step 1: Setting Up Google Colab Environment
- Step 2: Preparing the Dataset
- Step 3: Installing Necessary Libraries
- Step 4: Loading and Preprocessing Data
- Step 5: Selecting and Loading a Pre-trained Model
- Step 6: Fine-Tuning the Model
- Step 7: Evaluating the Fine-Tuned Model
- Step 8: Generating Captions
- Conclusion
Prerequisites
Before diving in, ensure you have:
- A Google account to access Google Colab.
- Basic knowledge of Python and familiarity with machine learning frameworks like TensorFlow or PyTorch.
- Understanding of image captioning concepts.
Step 1: Setting Up Google Colab Environment
-
Access Google Colab:
- Navigate to Google Colab and sign in with your Google account.
- Click on "New Notebook" to create a new Colab notebook.
-
Select CPU Runtime:
- By default, Colab may assign a GPU. To switch to CPU:
- Go to Runtime > Change runtime type.
- Under Hardware accelerator, select None.
- Click Save.
Step 2: Preparing the Dataset
For image captioning, popular datasets include:
- COCO (Common Objects in Context): Widely used with rich annotations.
- Flickr8k/Flickr30k: Smaller datasets suitable for quick experiments.
For this guide, we'll use the Flickr8k dataset due to its manageable size for CPU runtime.
-
Download Flickr8k Dataset:
- The dataset consists of 8,000 images, each with five captions.
- Download Link: Flickr8k Dataset
Note: You'll need to register to access the dataset. Alternatively, for demonstration, we can use a similar dataset or synthetic data.
-
For the purpose of this guide, we will use a subset of the Flickr8k dataset available via torchvision.
Step 3: Installing Necessary Libraries
We'll use PyTorch for this guide, leveraging the transformers library for the model.
# Install required libraries
!pip install torch torchvision
!pip install transformers
!pip install nltk
!pip install pillow
Explanation:
- torch & torchvision: Core libraries for deep learning tasks.
- transformers: Provides state-of-the-art models for various NLP and vision tasks.
- nltk: Useful for text preprocessing.
- pillow: For image processing.
Step 4: Loading and Preprocessing Data
4.1 Importing Libraries
import os
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
import nltk
from nltk.tokenize import word_tokenize
from transformers import BertTokenizer
import matplotlib.pyplot as plt
nltk.download('punkt')
4.2 Setting Up Paths
Assuming you've uploaded the Flickr8k dataset to your Google Drive, mount it.
from google.colab import drive
drive.mount('/content/drive')
Note: Replace the dataset path accordingly.
# Define dataset directories
IMAGE_DIR = '/content/drive/MyDrive/Flickr8k/images/' # Update this path
CAPTION_FILE = '/content/drive/MyDrive/Flickr8k/captions.txt' # Update this path
4.3 Building Vocabulary
We need to tokenize captions and build a vocabulary.
class Vocabulary:
def __init__(self, freq_threshold):
self.freq_threshold = freq_threshold
self.itos = {0: "<PAD>", 1: "<SOS>", 2: "<EOS>", 3: "<UNK>"}
self.stoi = {v: k for k, v in self.itos.items()}
def __len__(self):
return len(self.itos)
@staticmethod
def tokenize(text):
return word_tokenize(text.lower())
def build_vocabulary(self, sentence_list):
frequencies = {}
idx = 4
for sentence in sentence_list:
for word in self.tokenize(sentence):
frequencies[word] = frequencies.get(word, 0) + 1
if frequencies[word] == self.freq_threshold:
self.stoi[word] = idx
self.itos[idx] = word
idx += 1
def numericalize(self, text):
tokenized_text = self.tokenize(text)
return [
self.stoi.get(word, self.stoi["<UNK>"])
for word in tokenized_text
]
4.4 Creating the Dataset Class
class Flickr8kDataset(Dataset):
def __init__(self, root_dir, captions_file, transform=None, freq_threshold=5):
self.root_dir = root_dir
self.transform = transform
# Load captions
self.imgs = []
self.captions = {}
with open(captions_file, 'r') as f:
next(f) # skip header
for line in f:
img, caption = line.strip().split('\t')
img_id = img.split('#')[0]
if img_id in self.captions:
self.captions[img_id].append(caption)
else:
self.captions[img_id] = [caption]
self.imgs = list(self.captions.keys())
# Initialize vocabulary
self.vocab = Vocabulary(freq_threshold)
all_captions = [cap for caps in self.captions.values() for cap in caps]
self.vocab.build_vocabulary(all_captions)
def __len__(self):
return len(self.imgs)
def __getitem__(self, idx):
img_id = self.imgs[idx]
img_path = os.path.join(self.root_dir, img_id)
image = Image.open(img_path).convert("RGB")
if self.transform:
image = self.transform(image)
# For simplicity, pick the first caption
caption = self.captions[img_id][0]
numericalized_caption = [self.vocab.stoi["<SOS>"]]
numericalized_caption += self.vocab.numericalize(caption)
numericalized_caption.append(self.vocab.stoi["<EOS>"])
return image, torch.tensor(numericalized_caption)
4.5 Defining Transforms and Creating DataLoader
# Define image transformations
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
])
# Initialize dataset
dataset = Flickr8kDataset(
root_dir=IMAGE_DIR,
captions_file=CAPTION_FILE,
transform=transform,
freq_threshold=5,
)
# Split dataset into training and validation
train_size = int(0.8 * len(dataset))
val_size = len(dataset) - train_size
train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])
# Create DataLoaders
train_loader = DataLoader(
dataset=train_dataset,
batch_size=32,
shuffle=True,
num_workers=0
)
val_loader = DataLoader(
dataset=val_dataset,
batch_size=32,
shuffle=False,
num_workers=0
)
Notes:
- Batch Size: Adjust based on CPU capabilities. A smaller batch size might be necessary.
- num_workers=0: Ensures compatibility in Colab's environment.
Step 5: Selecting and Loading a Pre-trained Model
We'll use a pre-trained ResNet as the encoder and a simplified Transformer as the decoder for image captioning.
5.1 Defining the Encoder
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
self.resnet = models.resnet50(pretrained=True)
# Remove the last fully connected layer
self.resnet = nn.Sequential(*list(self.resnet.children())[:-1])
self.linear = nn.Linear(self.resnet[-1][-1].bn2.num_features, embed_size)
self.bn = nn.BatchNorm1d(embed_size, momentum=0.01)
def forward(self, images):
with torch.no_grad():
features = self.resnet(images)
features = features.reshape(features.size(0), -1)
features = self.bn(self.linear(features))
return features
5.2 Defining the Decoder
For simplicity, we'll use a basic LSTM-based decoder.
class DecoderRNN(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):
super(DecoderRNN, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)
self.linear = nn.Linear(hidden_size, vocab_size)
self.dropout = nn.Dropout(0.5)
def forward(self, features, captions):
embeddings = self.dropout(self.embed(captions))
embeddings = torch.cat((features.unsqueeze(1), embeddings), dim=1)
hiddens, _ = self.lstm(embeddings)
outputs = self.linear(hiddens)
return outputs
5.3 Combining Encoder and Decoder
class ImageCaptioningModel(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):
super(ImageCaptioningModel, self).__init__()
self.encoder = EncoderCNN(embed_size)
self.decoder = DecoderRNN(embed_size, hidden_size, vocab_size, num_layers)
def forward(self, images, captions):
features = self.encoder(images)
outputs = self.decoder(features, captions)
return outputs
Step 6: Fine-Tuning the Model
6.1 Setting Hyperparameters
# Hyperparameters
embed_size = 256
hidden_size = 512
num_layers = 1
learning_rate = 1e-3
num_epochs = 5
6.2 Initializing the Model, Loss Function, and Optimizer
vocab_size = len(dataset.vocab)
model = ImageCaptioningModel(embed_size, hidden_size, vocab_size, num_layers).to('cpu') # Ensures CPU usage
criterion = nn.CrossEntropyLoss(ignore_index=dataset.vocab.stoi["<PAD>"])
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
6.3 Training Loop
def train(model, dataloader, criterion, optimizer, epoch):
model.train()
total_loss = 0
for idx, (images, captions) in enumerate(dataloader):
images = images.to('cpu')
captions = captions.to('cpu')
# Forward pass
outputs = model(images, captions[:, :-1])
loss = criterion(outputs.reshape(-1, outputs.shape[2]), captions[:, 1:].reshape(-1))
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item()
if idx % 100 == 0:
print(f"Epoch [{epoch}/{num_epochs}], Step [{idx}/{len(dataloader)}], Loss: {loss.item():.4f}")
return total_loss / len(dataloader)
def validate(model, dataloader, criterion):
model.eval()
total_loss = 0
with torch.no_grad():
for images, captions in dataloader:
images = images.to('cpu')
captions = captions.to('cpu')
outputs = model(images, captions[:, :-1])
loss = criterion(outputs.reshape(-1, outputs.shape[2]), captions[:, 1:].reshape(-1))
total_loss += loss.item()
return total_loss / len(dataloader)
6.4 Running the Training Process
for epoch in range(1, num_epochs + 1):
train_loss = train(model, train_loader, criterion, optimizer, epoch)
val_loss = validate(model, val_loader, criterion)
print(f"Epoch [{epoch}], Train Loss: {train_loss:.4f}, Validation Loss: {val_loss:.4f}")
Notes:
- Monitoring: Loss decreases indicate learning. If loss doesn't decrease, consider tuning hyperparameters.
- Saving Checkpoints: For longer training, implement model checkpointing.
Step 7: Evaluating the Fine-Tuned Model
7.1 Generating Captions and Calculating Metrics
We'll use the BLEU score for evaluation. Install nltk if not already.
from nltk.translate.bleu_score import sentence_bleu
def generate_caption(model, image, vocab, max_length=20):
model.eval()
with torch.no_grad():
feature = model.encoder(image.unsqueeze(0).to('cpu'))
states = None
inputs = torch.tensor([vocab.stoi["<SOS>"]]).to('cpu')
caption = []
for _ in range(max_length):
outputs = model.decoder.embed(inputs).unsqueeze(0)
if states is None:
hiddens, states = model.decoder.lstm(torch.cat((feature.unsqueeze(1), outputs), dim=1))
else:
hiddens, states = model.decoder.lstm(outputs, states)
outputs = model.decoder.linear(hiddens.squeeze(1))
predicted = outputs.argmax(1)
caption.append(predicted.item())
if predicted.item() == vocab.stoi["<EOS>"]:
break
inputs = predicted
# Convert indices to words
caption_words = []
for idx in caption:
word = vocab.itos.get(idx, "<UNK>")
if word == "<EOS>":
break
caption_words.append(word)
return ' '.join(caption_words)
7.2 Calculating BLEU Score on Validation Set
def calculate_bleu(model, dataloader, vocab):
references = []
hypotheses = []
for images, captions in dataloader:
for i in range(images.size(0)):
image = images[i]
ground_truth = captions[i].tolist()
# Remove <SOS> and <EOS>
ground_truth = [vocab.itos[idx] for idx in ground_truth if idx not in {vocab.stoi["<SOS>"], vocab.stoi["<EOS>"], vocab.stoi["<PAD>"]}]
references.append([ground_truth])
# Generate caption
caption = generate_caption(model, image, vocab)
hypotheses.append(caption.split())
# Calculate BLEU scores
bleu1 = nltk.translate.bleu_score.corpus_bleu(references, hypotheses, weights=(1,0,0,0))
bleu2 = nltk.translate.bleu_score.corpus_bleu(references, hypotheses, weights=(0.5,0.5,0,0))
print(f"BLEU-1: {bleu1:.4f}, BLEU-2: {bleu2:.4f}")
Running Evaluation:
calculate_bleu(model, val_loader, dataset.vocab)
Notes:
- BLEU-1 and BLEU-2: Indicate unigram and bigram accuracy, respectively.
- Other Metrics: Consider METEOR, CIDEr for comprehensive evaluation.
Step 8: Generating Captions
Once satisfied with the model's performance, use it to generate captions for new images.
8.1 Loading an Example Image
from PIL import Image
# Replace with your image path
example_image_path = '/content/drive/MyDrive/Flickr8k/images/example.jpg'
image = Image.open(example_image_path).convert("RGB")
image_tensor = transform(image)
8.2 Generating and Displaying the Caption
caption = generate_caption(model, image_tensor, dataset.vocab)
print("Generated Caption:", caption)
# Displaying the image with the caption
plt.imshow(image)
plt.title(caption)
plt.axis('off')
plt.show()
Conclusion
Fine-tuning an image captioning model on Google Colab using a CPU runtime involves several steps, from setting up the environment and preparing data to training and evaluating the model. While CPU runtimes are slower, especially for larger models and datasets, optimizing data loaders and using lightweight architectures can make the process feasible.
For larger-scale projects or faster training times, consider upgrading to a GPU runtime in Colab or using more efficient models and training strategies. Additionally, exploring advanced models like Transformer-based architectures or leveraging multi-modal pre-trained models can further enhance performance.
Happy modeling!