Building an Image Captioning Model with the Flickr8k Dataset: A Comprehensive Step-by-Step Guide
Table of Contents
- Introduction
- Prerequisites
- Environment Setup
- Downloading and Exploring the Flickr8k Dataset
- Data Preprocessing
- Building the Image Captioning Model
- Training the Model
- Evaluating the Model
- Testing the Model
- Converting the Model to TensorFlow Lite
- Deploying on Mobile
- Conclusion
Introduction
Image captioning is a task that involves generating descriptive captions for images using deep learning techniques. This guide will walk you through building an image captioning model using the Flickr8k dataset, covering the entire pipeline from data loading and preprocessing to model training, evaluation, and deployment on mobile devices using TensorFlow Lite.
Prerequisites
Before diving into the implementation, ensure you have a basic understanding of the following:
- Python Programming: Familiarity with Python is essential.
- Deep Learning Basics: Understanding of neural networks, especially CNNs and RNNs.
- TensorFlow and Keras: Basic knowledge of TensorFlow and Keras frameworks.
- Natural Language Processing (NLP): Understanding of text preprocessing and sequence modeling.
Environment Setup
1. Install Required Libraries
Ensure you have Python 3.7 or higher installed. Install the necessary libraries using pip:
pip install numpy pandas matplotlib tensorflow keras pillow nltk
2. Import Libraries
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import string
import re
import tensorflow as tf
from tensorflow.keras.applications import InceptionV3
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Input, Dense, LSTM, Embedding, Dropout, add
from PIL import Image
import nltk
nltk.download('punkt')
Downloading and Exploring the Flickr8k Dataset
1. Download the Dataset
The Flickr8k dataset consists of 8,000 images, each annotated with five captions. You can download the dataset from Kaggle.
Alternatively, use the following script to download and extract the dataset:
# Create directories
mkdir data
cd data
# Download images
wget https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_Dataset.zip
unzip Flickr8k_Dataset.zip
# Download captions
wget https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_text.zip
unzip Flickr8k_text.zip
2. Directory Structure
data/
│
├── Flickr8k_Dataset/
│ └── Flickr8k/
│ ├── 123.jpg
│ ├── 124.jpg
│ └── ...
│
└── Flickr8k_text/
├── Flickr8k.token.txt
├── Flickr_8k.trainImages.txt
├── Flickr_8k.devImages.txt
└── Flickr_8k.testImages.txt
Data Preprocessing
Data preprocessing is crucial for preparing the images and captions for model training.
Image Preprocessing
We'll use the InceptionV3 model to extract features from images. First, load and preprocess the images.
from tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input
# Path to images
image_folder = 'data/Flickr8k_Dataset/Flickr8k'
# Load InceptionV3 model for feature extraction
model_cnn = InceptionV3(weights='imagenet')
model_cnn = Model(model_cnn.input, model_cnn.layers[-2].output)
def extract_features(img_path, model):
img = image.load_img(img_path, target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
feature = model.predict(x, verbose=0)
return feature
# Example
# features = extract_features(os.path.join(image_folder, '123.jpg'), model_cnn)
Note: Feature extraction can be time-consuming. It's recommended to extract and save features once.
Extract and Save Features
import pickle
# Read all image names
def load_doc(filename):
with open(filename, 'r') as file:
text = file.read()
return text
# Extract features for all images
def extract_features_for_all_images(image_folder, model):
features = {}
for img_name in os.listdir(image_folder):
if img_name.endswith('.jpg'):
img_path = os.path.join(image_folder, img_name)
feature = extract_features(img_path, model)
features[img_name.split('.')[0]] = feature
return features
# Uncomment to extract features (this might take some time)
# features = extract_features_for_all_images(image_folder, model_cnn)
# Save to file
# with open('features.pkl', 'wb') as f:
# pickle.dump(features, f)
Text (Caption) Preprocessing
Process captions by tokenizing, creating vocabulary, and mapping words to integers.
1. Load Captions
def load_doc(filename):
with open(filename, 'r') as file:
text = file.read()
return text
# Load captions
doc = load_doc('data/Flickr8k_text/Flickr8k.token.txt')
2. Parse Captions
from collections import defaultdict
def load_descriptions(doc):
descriptions = defaultdict(list)
for line in doc.strip().split('\n'):
tokens = line.split('\t')
image_id, caption = tokens[0], tokens[1]
image_id = image_id.split('.')[0]
caption = 'startseq ' + caption.rstrip('.').lower()
descriptions[image_id].append(caption)
return descriptions
descriptions = load_descriptions(doc)
print(list(descriptions.items())[0])
3. Clean Captions
Remove punctuation and non-alphabetic characters.
def clean_caption(caption):
caption = caption.translate(str.maketrans('', '', string.punctuation))
caption = re.sub(r'\d+', '', caption)
caption = caption.encode('ascii', 'ignore').decode('utf-8')
caption = caption.split()
caption = [word for word in caption if len(word) > 1]
caption = ' '.join(caption)
return caption
def clean_descriptions(descriptions):
for key, captions in descriptions.items():
descriptions[key] = [clean_caption(c) for c in captions]
clean_descriptions(descriptions)
4. Save Cleaned Captions
Optionally, save the cleaned captions for future use.
def save_descriptions(descriptions, filename):
lines = []
for key, captions in descriptions.items():
for caption in captions:
lines.append(key + ' ' + caption)
data = '\n'.join(lines)
with open(filename, 'w') as file:
file.write(data)
save_descriptions(descriptions, 'descriptions.txt')
5. Load Train, Validation, and Test Splits
def load_set(filename):
doc = load_doc(filename)
dataset = set()
for line in doc.strip().split('\n'):
image_id = line.split('.')[0]
dataset.add(image_id)
return dataset
train = load_set('data/Flickr8k_text/Flickr_8k.trainImages.txt')
valid = load_set('data/Flickr8k_text/Flickr_8k.devImages.txt')
test = load_set('data/Flickr8k_text/Flickr_8k.testImages.txt')
print(f'Training Set: {len(train)}')
print(f'Validation Set: {len(valid)}')
print(f'Test Set: {len(test)}')
6. Create Training, Validation, and Test Descriptions
def load_clean_descriptions(filename, dataset):
doc = load_doc(filename)
descriptions = defaultdict(list)
for line in doc.strip().split('\n'):
tokens = line.split()
image_id, caption = tokens[0], ' '.join(tokens[1:])
if image_id in dataset:
descriptions[image_id].append(caption)
return descriptions
train_descriptions = load_clean_descriptions('descriptions.txt', train)
valid_descriptions = load_clean_descriptions('descriptions.txt', valid)
test_descriptions = load_clean_descriptions('descriptions.txt', test)
print(f'Transcriptions: train={len(train_descriptions)}, validation={len(valid_descriptions)}, test={len(test_descriptions)}')
7. Build Vocabulary
def build_vocabulary(descriptions, threshold=10):
word_counts = {}
for key in descriptions:
for caption in descriptions[key]:
for word in caption.split():
word_counts[word] = word_counts.get(word, 0) + 1
vocab = [word for word, count in word_counts.items() if count >= threshold]
return vocab
vocab = build_vocabulary(train_descriptions)
print(f'Vocabulary Size: {len(vocab)}')
8. Convert Words to Integers (Tokenizer)
tokenizer = Tokenizer()
lines = []
for key in train_descriptions:
for caption in train_descriptions[key]:
lines.append(caption)
tokenizer.fit_on_texts(lines)
vocab_size = len(tokenizer.word_index) + 1
print(f'Vocabulary Size (Tokenizer): {vocab_size}')
9. Determine Maximum Caption Length
def max_length(descriptions):
return max(len(caption.split()) for captions in descriptions.values() for caption in captions)
max_length = max_length(train_descriptions)
print(f'Max Caption Length: {max_length}')
Building the Image Captioning Model
The model consists of two main parts:
- Feature Extraction (CNN): Extract image features using a Convolutional Neural Network (InceptionV3).
- Sequence Modeling (RNN): Generate captions using a Recurrent Neural Network (LSTM).
1. Feature Extraction with CNN
As previously set up, we use InceptionV3 to extract features.
2. Sequence Modeling with RNN
Design the RNN to take image features and generate captions word by word.
3. Combining CNN and RNN
Build a model that integrates both CNN and RNN components.
# Define model parameters
embedding_dim = 256
units = 256
# Image feature input
image_input = Input(shape=(2048,))
image_dropout = Dropout(0.5)(image_input)
image_dense = Dense(embedding_dim, activation='relu')(image_dropout)
# Caption input
caption_input = Input(shape=(max_length,))
caption_embedding = Embedding(vocab_size, embedding_dim, mask_zero=True)(caption_input)
caption_dropout = Dropout(0.5)(caption_embedding)
caption_lstm = LSTM(units)(caption_dropout)
# Combine features
decoder1 = add([image_dense, caption_lstm])
decoder2 = Dense(units, activation='relu')(decoder1)
outputs = Dense(vocab_size, activation='softmax')(decoder2)
# Define the model
model = Model(inputs=[image_input, caption_input], outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.summary()
Training the Model
Training involves feeding image features and corresponding captions to the model. Since captions are sequences, we use the "teacher forcing" technique where the model is trained to predict the next word in the sequence given the previous words.
1. Prepare Training Data
Create generator functions to feed data to the model in batches, which is efficient for large datasets.
def create_sequences(tokenizer, max_length, descriptions, photos, vocab_size):
X1, X2, y = [], [], []
for key, captions in descriptions.items():
for caption in captions:
# Convert words to integer tokens
seq = tokenizer.texts_to_sequences([caption])[0]
for i in range(1, len(seq)):
in_seq, out_seq = seq[:i], seq[i]
in_seq = pad_sequences([in_seq], maxlen=max_length)[0]
out_seq = tf.keras.utils.to_categorical([out_seq], num_classes=vocab_size)[0]
X1.append(photos[key][0])
X2.append(in_seq)
y.append(out_seq)
return np.array(X1), np.array(X2), np.array(y)
# Load image features
with open('features.pkl', 'rb') as f:
features = pickle.load(f)
# Prepare training data
X1_train, X2_train, y_train = create_sequences(tokenizer, max_length, train_descriptions, features, vocab_size)
print(X1_train.shape, X2_train.shape, y_train.shape)
Note: Due to memory constraints, it's advisable to use data generators for large datasets. Here, for simplicity, we're loading all data into memory.
2. Train the Model
epochs = 20
batch_size = 64
model.fit([X1_train, X2_train], y_train, epochs=epochs, batch_size=batch_size, verbose=1)
Tips:
- Early Stopping: Monitor validation loss and stop training when it stops improving.
- Checkpointing: Save the best model based on validation loss.
3. Save the Model
model.save('image_caption_model.h5')
Evaluating the Model
Evaluation involves assessing how well the model generates captions. Common metrics include BLEU scores.
BLEU Score
The BLEU (Bilingual Evaluation Understudy) score evaluates the quality of machine-generated text compared to reference texts.
from nltk.translate.bleu_score import corpus_bleu
def evaluate_model(model, descriptions, photos, tokenizer, max_length):
actual, predicted = list(), list()
for key, captions in descriptions.items():
yhat = generate_caption(model, photos, tokenizer, key, max_length)
references = [caption.split() for caption in captions]
predicted = yhat.split()
actual.append(references)
predicted = predicted
yield actual, predicted
def generate_caption(model, photo, tokenizer, key, max_length):
in_text = 'startseq'
for _ in range(max_length):
sequence = tokenizer.texts_to_sequences([in_text])[0]
sequence = pad_sequences([sequence], maxlen=max_length)
yhat = model.predict([photo[key], sequence], verbose=0)
yhat = np.argmax(yhat)
word = tokenizer.index_word.get(yhat, None)
if word is None:
break
in_text += ' ' + word
if word == 'endseq':
break
return in_text
# Example evaluation
# Note: Implement evaluation on the validation set for BLEU score calculation
Implementing BLEU Score Calculation:
def calculate_bleu_score(model, descriptions, features, tokenizer, max_length):
actual, predicted = list(), list()
for key, caps in descriptions.items():
yhat = generate_caption(model, features, tokenizer, key, max_length)
yhat = yhat.split()
yhat = yhat[1:-1] # Remove startseq and endseq
references = [cap.split()[1:-1] for cap in caps]
actual.append(references)
predicted.append(yhat)
bleu_score = corpus_bleu(actual, predicted)
return bleu_score
bleu_score = calculate_bleu_score(model, valid_descriptions, features, tokenizer, max_length)
print(f'BLEU Score: {bleu_score}')
Note: BLEU scores range from 0 to 1, with higher scores indicating better performance.
Testing the Model
Generate captions for new images to test the model's performance.
def load_image_features(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
# Load features
features = load_image_features('features.pkl')
# Load the trained model
model = load_model('image_caption_model.h5')
# Generate a caption for a test image
def generate_caption_test(model, photo, tokenizer, max_length):
in_text = 'startseq'
for _ in range(max_length):
sequence = tokenizer.texts_to_sequences([in_text])[0]
sequence = pad_sequences([sequence], maxlen=max_length)
yhat = model.predict([photo, sequence], verbose=0)
yhat = np.argmax(yhat)
word = tokenizer.index_word.get(yhat, None)
if word is None:
break
in_text += ' ' + word
if word == 'endseq':
break
return in_text
# Select a random test image
import random
test_image_id = random.choice(list(test_descriptions.keys()))
test_image_feature = features[test_image_id]
# Generate caption
caption = generate_caption_test(model, {test_image_id: test_image_feature}, tokenizer, max_length)
print(f'Generated Caption: {caption}')
Converting the Model to TensorFlow Lite
To deploy the model on mobile devices, convert it to TensorFlow Lite format.
1. Freeze the Model
First, ensure that the model is saved in the TensorFlow SavedModel format.
# Convert Keras model to SavedModel
model.save('saved_model/image_captioning_model')
2. Convert to TensorFlow Lite
Use the TensorFlow Lite Converter to convert the model.
import tensorflow as tf
# Set the path to the SavedModel directory
saved_model_dir = 'saved_model/image_captioning_model'
# Initialize the TFLite converter
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
# (Optional) Optimize the model
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# Convert the model
tflite_model = converter.convert()
# Save the converted model
with open('image_captioning_model.tflite', 'wb') as f:
f.write(tflite_model)
Note: Optimize the model for size and performance if necessary. Post-training quantization can reduce the model size with minimal impact on accuracy.
Deploying on Mobile
Deploy the TensorFlow Lite model on Android or iOS devices.
1. Android Deployment
-
Add TensorFlow Lite Dependency: Add the TensorFlow Lite library to your build.gradle:
dependencies {
implementation 'org.tensorflow:tensorflow-lite:2.12.0'
}
-
Load the TFLite Model:
Interpreter tflite;
try {
tflite = new Interpreter(loadModelFile("image_captioning_model.tflite"));
} catch (Exception e) {
e.printStackTrace();
}
-
Perform Inference: Prepare the input (image features and caption sequence) and run inference to get the output.
2. iOS Deployment
-
Add TensorFlow Lite Framework: Integrate TensorFlow Lite using CocoaPods or manually.
-
Load the TFLite Model:
guard let modelPath = Bundle.main.path(forResource: "image_captioning_model", ofType: "tflite") else {
fatalError("Failed to load the model file.")
}
let interpreter = try Interpreter(modelPath: modelPath)
-
Perform Inference: Similar to Android, prepare inputs and execute the interpreter to get outputs.
Note: Detailed deployment steps vary based on specific app requirements and platforms. Refer to the TensorFlow Lite documentation for comprehensive guides.
Conclusion
This guide provided a detailed walkthrough for building an image captioning model using the Flickr8k dataset. We covered data loading, preprocessing, model building, training, evaluation, and conversion to TensorFlow Lite for mobile deployment. Image captioning combines computer vision and natural language processing, showcasing the power of deep learning in generating meaningful descriptions from visual data.
Next Steps:
- Enhance the Model: Experiment with more advanced architectures, such as attention mechanisms.
- Increase Dataset Size: Use larger datasets like Flickr30k or MS COCO for improved performance.
- Fine-Tune CNN: Fine-tune the CNN feature extractor for better image representations.
- Optimize for Deployment: Further optimize the model for real-time mobile applications.
References