Image Captioning Project Guide Using Flickr8k Dataset on Google Colab
This comprehensive guide will walk you through building an image captioning model using the Flickr8k dataset on Google Colab. The project includes data loading, preprocessing, model training, evaluation, predicting captions for custom images, and converting the trained model to TensorFlow Lite for deployment on mobile devices.
Table of Contents
- Project Overview
- Setup Environment
- Load and Explore the Flickr8k Dataset
- Data Preprocessing
- Build the Image Captioning Model
- Train the Model
- Evaluate the Model
- Predicting on Custom Images
- Convert the Model to TensorFlow Lite
- Deploying on Mobile
- Conclusion
Project Overview
Image captioning involves generating a textual description for a given image. This project utilizes the Flickr8k dataset, which contains 8,000 images, each paired with five different captions. We will build an end-to-end pipeline that:
- Loads and preprocesses the dataset.
- Builds and trains a neural network model to generate captions.
- Evaluates the model's performance.
- Generates captions for custom images.
- Converts the model to TensorFlow Lite for mobile deployment.
Setup Environment
First, ensure that you have access to Google Colab. This environment provides free GPU resources, which are beneficial for training deep learning models.
-
Open Google Colab:
-
Enable GPU:
- Go to
Runtime > Change runtime type.
- Under
Hardware accelerator, select GPU and save.
-
Install Necessary Libraries:
Run the following code snippets to install the required libraries.
!pip install tensorflow==2.9.1
!pip install numpy pandas matplotlib
!pip install Pillow
!pip install tensorflow-text # For text processing if needed
Load and Explore the Flickr8k Dataset
The Flickr8k dataset can be downloaded from Kaggle.
- Mount Google Drive:
It's efficient to store the dataset on Google Drive to avoid re-downloading.
from google.colab import drive
drive.mount('/content/drive')
- Download and Extract the Dataset:
Assuming you've uploaded the dataset to your Google Drive.
import os
import zipfile
# Define paths
drive_path = '/content/drive/MyDrive/Flickr8k' # Update with your path
images_zip = os.path.join(drive_path, 'Flickr8k_Dataset.zip')
captions_zip = os.path.join(drive_path, 'Flickr8k_text.zip')
# Extract images
with zipfile.ZipFile(images_zip, 'r') as zip_ref:
zip_ref.extractall(os.path.join(drive_path, 'Flickr8k_Dataset'))
# Extract captions
with zipfile.ZipFile(captions_zip, 'r') as zip_ref:
zip_ref.extractall(os.path.join(drive_path, 'Flickr8k_text'))
- Load Captions File:
The Flickr8k.token.txt file contains image filenames and their corresponding captions.
import pandas as pd
# Path to captions file
captions_file = os.path.join(drive_path, 'Flickr8k_text', 'Flickr8k.token.txt')
# Read captions
with open(captions_file, 'r') as file:
captions = file.read()
# Process captions into a dictionary
import string
def load_doc(filename):
file = open(filename, 'r')
text = file.read()
file.close()
return text
def preprocess_caption(caption):
caption = caption.lower()
caption = caption.translate(str.maketrans('', '', string.punctuation))
caption = caption.strip()
caption = '<start> ' + caption + ' <end>'
return caption
captions_dict = {}
for line in captions.split('\n'):
if len(line) < 1:
continue
tokens = line.split('\t')
image_id, caption = tokens[0].split('#')
image_id = image_id
if image_id not in captions_dict:
captions_dict[image_id] = []
captions_dict[image_id].append(preprocess_caption(caption))
# Display sample captions
for key, val in list(captions_dict.items())[:5]:
print(f"Image ID: {key}")
for cap in val:
print(f"Caption: {cap}")
print('\n')
Data Preprocessing
Proper data preprocessing is crucial for model performance. We'll preprocess both the images and the captions.
Image Preprocessing
- Load and Resize Images:
We'll use the InceptionV3 model for the encoder; hence, images need to be resized to 299x299 pixels.
import tensorflow as tf
from tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input
# Define image directory
image_dir = os.path.join(drive_path, 'Flickr8k_Dataset', 'Flicker8k_Dataset')
# Preprocess images using InceptionV3
def load_image(image_path):
img = tf.io.read_file(image_path)
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, (299, 299))
img = preprocess_input(img)
return img
# Sample image
sample_image_id = list(captions_dict.keys())[0]
sample_image_path = os.path.join(image_dir, sample_image_id)
sample_image = load_image(sample_image_path)
print(sample_image.shape)
- Feature Extraction:
Instead of training the encoder, we'll use a pre-trained InceptionV3 model to extract features.
# Load InceptionV3 model
image_model = InceptionV3(include_top=False, weights='imagenet')
new_input = image_model.input
hidden_layer = image_model.layers[-1].output # Last convolutional layer
image_features_extract_model = tf.keras.Model(new_input, hidden_layer)
# Extract features for all images
import pickle
features_path = os.path.join(drive_path, 'image_features.pkl')
if not os.path.exists(features_path):
def map_func(img_name):
img_path = os.path.join(image_dir, img_name.decode('utf-8'))
img = load_image(img_path)
img = tf.expand_dims(img, 0)
img_features = image_features_extract_model(img)
img_features = tf.reshape(img_features, (img_features.shape[0], -1, img_features.shape[3]))
return img_features.numpy()
# Create a list of all image filenames
image_filenames = list(captions_dict.keys())
# Extract features
import tqdm
image_features = {}
for img_name in tqdm.tqdm(image_filenames):
image_features[img_name] = map_func(img_name.encode('utf-8'))
# Save features
with open(features_path, 'wb') as f:
pickle.dump(image_features, f)
# Load features
with open(features_path, 'rb') as f:
image_features = pickle.load(f)
print("Number of images with extracted features:", len(image_features))
Text Preprocessing
- Tokenization:
Convert captions to sequences of integers.
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Compile all captions into a list
all_captions = []
for key in captions_dict:
for cap in captions_dict[key]:
all_captions.append(cap)
print("Total Captions: ", len(all_captions))
# Tokenize the captions
tokenizer = Tokenizer(num_words=5000, oov_token="<unk>", filters='!"#$%&()*+.,-/:;=?@[\]^_`{|}~ ')
tokenizer.fit_on_texts(all_captions)
# Create word to index mapping
tokenizer.word_index['<pad>'] = 0
tokenizer.index_word[0] = '<pad>'
# Save tokenizer
import json
tokenizer_json = tokenizer.to_json()
with open(os.path.join(drive_path, 'tokenizer.json'), 'w') as f:
f.write(tokenizer_json)
# Convert captions to sequences
train_seqs = tokenizer.texts_to_sequences(all_captions)
# Pad sequences
max_length = max(len(seq) for seq in train_seqs)
print("Maximum caption length:", max_length)
train_seqs = pad_sequences(train_seqs, maxlen=max_length, padding='post')
print("Sample padded sequence:", train_seqs[0])
- Create Vocabulary and Other Parameters:
Determine vocabulary size and sequence lengths.
vocab_size = len(tokenizer.word_index) + 1
print("Vocabulary Size:", vocab_size)
# Split data into training and validation (optional)
import numpy as np
# Create image, caption pairs
image_ids = []
captions_list = []
for key in captions_dict:
for cap in captions_dict[key]:
image_ids.append(key)
captions_list.append(cap)
# Convert to sequences
sequences = tokenizer.texts_to_sequences(captions_list)
sequences = pad_sequences(sequences, maxlen=max_length, padding='post')
# Convert to numpy arrays
image_ids = np.array(image_ids)
sequences = np.array(sequences)
# Shuffle the data
dataset_size = len(image_ids)
indices = np.arange(dataset_size)
np.random.shuffle(indices)
image_ids = image_ids[indices]
sequences = sequences[indices]
# Split into training and validation sets (90% train, 10% val)
split_index = int(0.9 * dataset_size)
train_image_ids = image_ids[:split_index]
train_sequences = sequences[:split_index]
val_image_ids = image_ids[split_index:]
val_sequences = sequences[split_index:]
print(f"Training Samples: {len(train_image_ids)}")
print(f"Validation Samples: {len(val_image_ids)}")
Build the Image Captioning Model
We'll adopt an Encoder-Decoder architecture, where:
- Encoder: Uses pre-extracted image features from InceptionV3.
- Decoder: A neural network (typically involving Embedding layers and LSTM) that generates captions.
Encoder
Since we've already extracted the image features, we'll feed them directly to the decoder.
# Image features shape: (batch_size, 64, 2048)
embedding_dim = 256
units = 512
Decoder
- Define the Decoder Model:
We'll use an Embedding layer followed by an LSTM and a Dense layer.
from tensorflow.keras import layers
class RNN_Decoder(tf.keras.Model):
def __init__(self, vocab_size, embedding_dim, units):
super(RNN_Decoder, self).__init__()
self.units = units
self.embedding = layers.Embedding(vocab_size, embedding_dim)
self.lstm = layers.LSTM(self.units,
return_sequences=True,
return_state=True,
recurrent_initializer='glorot_uniform')
self.fc = layers.Dense(vocab_size)
# Attention layers
self.attention = layers.AdditiveAttention()
def call(self, features, captions, hidden):
# features shape: (batch_size, 64, 2048)
# captions shape: (batch_size, max_length)
caption_embeddings = self.embedding(captions)
# caption_embeddings shape: (batch_size, max_length, embedding_dim)
# Apply attention
context_vector = self.attention([ caption_embeddings, features ])
# context_vector shape: (batch_size, max_length, units)
# Concatenate context and caption embeddings
combined_input = tf.concat([context_vector, caption_embeddings], axis=-1)
# Pass through LSTM
output, state_h, state_c = self.lstm(combined_input, initial_state=hidden)
# Pass through Dense layer
output = self.fc(output)
return output, state_h, state_c
def reset_state(self, batch_size):
return [tf.zeros((batch_size, self.units)),
tf.zeros((batch_size, self.units))]
# Instantiate the decoder
decoder = RNN_Decoder(vocab_size, embedding_dim, units)
- Define the Loss Function and Optimizer:
Use sparse_categorical_crossentropy as the loss and Adam optimizer.
# Loss function
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction='none')
def loss_function(real, pred):
mask = tf.math.logical_not(tf.math.equal(real, 0)) # Padding mask
loss_ = loss_object(real, pred)
mask = tf.cast(mask, dtype=loss_.dtype)
loss_ *= mask
return tf.reduce_mean(loss_)
- Define the Optimizer:
optimizer = tf.keras.optimizers.Adam()
- Define Metrics (Optional):
train_loss = tf.keras.metrics.Mean(name='train_loss')
Train the Model
Training involves feeding the image features and corresponding captions to the model and optimizing the weights.
- Create Data Batches:
Use tf.data for efficient data loading.
BATCH_SIZE = 64
BUFFER_SIZE = 1000
# Function to load image features
def map_func_train(img_id, seq):
img_tensor = image_features[img_id.decode('utf-8')][0]
return img_tensor, seq
# Create TensorFlow dataset
dataset = tf.data.Dataset.from_tensor_slices((train_image_ids, train_sequences))
dataset = dataset.map(lambda img, cap: tf.py_function(map_func_train, [img, cap], [tf.float32, tf.int32]),
num_parallel_calls=tf.data.AUTOTUNE)
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
dataset = dataset.prefetch(buffer_size=tf.data.AUTOTUNE)
# Validation dataset
def map_func_val(img_id, seq):
img_tensor = image_features[img_id.decode('utf-8')][0]
return img_tensor, seq
val_dataset = tf.data.Dataset.from_tensor_slices((val_image_ids, val_sequences))
val_dataset = val_dataset.map(lambda img, cap: tf.py_function(map_func_val, [img, cap], [tf.float32, tf.int32]),
num_parallel_calls=tf.data.AUTOTUNE)
val_dataset = val_dataset.batch(BATCH_SIZE)
val_dataset = val_dataset.prefetch(buffer_size=tf.data.AUTOTUNE)
- Define the Training Step:
Use @tf.function for performance optimization.
@tf.function
def train_step(img_tensor, target):
loss = 0
# Initialize hidden state
hidden = decoder.reset_state(batch_size=target.shape[0])
with tf.GradientTape() as tape:
# Pass image features and caption to the decoder
predictions, _, _ = decoder(img_tensor, target[:, :-1], hidden)
# Compute the loss
loss = loss_function(target[:, 1:], predictions)
# Compute gradients
trainable_variables = decoder.trainable_variables
gradients = tape.gradient(loss, trainable_variables)
# Update weights
optimizer.apply_gradients(zip(gradients, trainable_variables))
train_loss(loss)
- Training Loop:
EPOCHS = 20
for epoch in range(EPOCHS):
train_loss.reset_states()
for (batch, (img_tensor, target)) in enumerate(dataset):
train_step(img_tensor, target)
if batch % 100 == 0:
print(f"Epoch {epoch+1} Batch {batch} Loss {train_loss.result():.4f}")
# Validation loss computation (optional)
# Add validation steps if desired
print(f"Epoch {epoch+1} Loss {train_loss.result():.6f}")
- Save the Model:
After training, save the model weights.
decoder.save_weights(os.path.join(drive_path, 'decoder_weights.h5'))
Evaluate the Model
After training, evaluate the model's performance on the validation set using metrics like BLEU scores.
- Load the Model Weights:
decoder.load_weights(os.path.join(drive_path, 'decoder_weights.h5'))
- Prediction Function:
Define a function to generate captions for a given image.
def evaluate(image):
attention_plot = np.zeros((max_length, 64))
hidden = decoder.reset_state(batch_size=1)
temp_input = tf.expand_dims(load_image(image), 0)
img_tensor_val = image_features_extract_model(temp_input)
img_tensor_val = tf.reshape(img_tensor_val, (img_tensor_val.shape[0], -1, img_tensor_val.shape[3]))
features = img_tensor_val
dec_input = tf.expand_dims([tokenizer.word_index['<start>']], 0)
result = []
for i in range(max_length):
predictions, hidden_h, hidden_c = decoder(features, dec_input, hidden)
predicted_id = tf.argmax(predictions[:, -1, :], axis=-1).numpy()[0]
if tokenizer.index_word[predicted_id] == '<end>':
break
result.append(tokenizer.index_word[predicted_id])
dec_input = tf.expand_dims([predicted_id], 0)
return ' '.join(result)
- Compute BLEU Score (Optional):
Use BLEU scores to evaluate caption quality.
import nltk
from nltk.translate.bleu_score import sentence_bleu
def calculate_bleu(reference, candidate):
reference = [ref.split() for ref in reference]
candidate = candidate.split()
score = nltk.translate.bleu_score.sentence_bleu(reference, candidate)
return score
# Example evaluation
image_id = list(captions_dict.keys())[0]
image_path = os.path.join(image_dir, image_id)
generated_caption = evaluate(image_path)
print("Generated Caption:", generated_caption)
print("Reference Captions:", captions_dict[image_id])
Note: For comprehensive evaluation, iterate over the validation set and compute average BLEU scores.
Predicting on Custom Images
Once the model is trained, you can generate captions for new images.
- Upload Custom Image:
Use Colab's file upload functionality.
from google.colab import files
uploaded = files.upload()
import PIL.Image
for fn in uploaded.keys():
# Display the image
image = PIL.Image.open(fn)
display(image)
# Save to Google Drive or current directory
image_path = '/content/' + fn
image.save(image_path)
# Generate caption
caption = evaluate(image_path)
print("Caption:", caption)
- Example:
After running the above code, select an image file from your local machine. The model will display the image and print the generated caption.
Convert the Model to TensorFlow Lite
To deploy the model on a mobile device, convert it to TensorFlow Lite.
- Save the Decoder as a SavedModel:
decoder.save(os.path.join(drive_path, 'saved_decoder'))
- Convert to TensorFlow Lite:
import tensorflow as tf
# Convert the model
converter = tf.lite.TFLiteConverter.from_saved_model(os.path.join(drive_path, 'saved_decoder'))
tflite_model = converter.convert()
# Save the converted model
with open(os.path.join(drive_path, 'decoder.tflite'), 'wb') as f:
f.write(tflite_model)
- Verify the Converted Model:
(Optional) Test the TFLite model to ensure it's functioning correctly.
# Load TFLite model and allocate tensors
interpreter = tf.lite.Interpreter(model_path=os.path.join(drive_path, 'decoder.tflite'))
interpreter.allocate_tensors()
# Get input and output details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
Note: Due to the complexity of the model, especially with attention mechanisms, consider simplifying the model architecture for mobile compatibility.
Deploying on Mobile
Deploying the TensorFlow Lite model involves integrating it into a mobile application. Here's a high-level overview for Android:
-
Set Up Android Project:
- Use Android Studio to create a new project.
-
Add TensorFlow Lite Dependencies:
- Add the TensorFlow Lite dependency to your
build.gradle file.
dependencies {
implementation 'org.tensorflow:tensorflow-lite:2.9.1'
}
- Load the TFLite Model:
Place the decoder.tflite file in the assets directory and load it in your app.
import org.tensorflow.lite.Interpreter;
// Load model
Interpreter tflite = new Interpreter(loadModelFile("decoder.tflite"));
-
Preprocess Input Images:
- Resize and normalize images as done during training.
-
Run Inference:
- Pass the preprocessed image through the model to get the caption.
-
Post-process Output:
- Convert the output token IDs back to words using the tokenizer.
Note: Implementing the full caption generation logic on mobile requires replicating parts of the preprocessing and post-processing steps, including token mappings.
Conclusion
This guide provided a step-by-step approach to building an image captioning model using the Flickr8k dataset on Google Colab. You learned how to:
- Load and preprocess image and text data.
- Build and train an Encoder-Decoder model with attention.
- Evaluate the model's performance.
- Generate captions for custom images.
- Convert the trained model to TensorFlow Lite for mobile deployment.
For further improvements, consider exploring more advanced models like Transformers or exploring techniques to enhance caption quality and model efficiency for mobile applications.
Acknowledgements