i want to create a normal image captioning model on flickr8k dataset create a step by step comprehensive guide
i will run the model on colab with default runtime on cpu
so make the training and all smooth and fast
this is dataset path
IMAGE_DIR = '/content/drive/MyDrive/archive_extracted/Images'
CAPTION_FILE = '/content/drive/MyDrive/archive_extracted/captions.txt'
this is caption.txt format
image,caption
1000268201_693b08cb0e.jpg,A child in a pink dress is climbing up a set of stairs in an entry way .
1000268201_693b08cb0e.jpg,A girl going into a wooden building .
1000268201_693b08cb0e.jpg,A little girl climbing into a wooden playhouse .
1000268201_693b08cb0e.jpg,A little girl climbing the stairs to her playhouse .
1000268201_693b08cb0e.jpg,A little girl in a pink dress going into a wooden cabin .
1001773457_577c3a7d70.jpg,A black dog and a spotted dog are fighting
Assistant
Step-by-Step Guide to Image Captioning on Flickr8k Dataset in Google Colab (CPU)
This guide will help you create an image captioning model using the Flickr8k dataset. We'll run the model on Google Colab with the default runtime using CPU. The focus is on making training smooth and fast.
Prerequisites:
A Google account with access to Google Drive.
Basic knowledge of Python and TensorFlow/Keras.
Step 1: Set Up the Environment in Colab
First, we'll set up our Colab environment by importing necessary libraries and mounting Google Drive to access our dataset.
1.1. Import Libraries
python
import numpy as np
import pandas as pd
import os
import string
import glob
import time
from tqdm import tqdm
import matplotlib.pyplot as plt
%matplotlib inline
from keras.applications.vgg16 import VGG16, preprocess_input
from keras.preprocessing.image import load_img, img_to_array
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
from keras.utils import to_categorical
from keras.models import Model
from keras.layers import Input, Dense, LSTM, Embedding, Dropout
from keras.layers import add
import tensorflow as tf
print(tf.__version__)
1.2. Mount Google Drive
Mount your Google Drive to access the dataset located at the specified paths.
python
from google.colab import drive
drive.mount('/content/drive')
Step 2: Load and Preprocess Captions
We need to read the captions file and preprocess the text data.
We will use a pre-trained CNN (VGG16) to extract features from the images. This approach speeds up training because we don't need to train the CNN from scratch.
3.1. Load VGG16 Model Pre-Trained on ImageNet
python
model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
model = Model(inputs=model.inputs, outputs=model.layers[-1].output)
3.2. Extract Features from Images
We will extract features for all images and save them to disk to avoid reprocessing.
python
features = {}
images = glob.glob(IMAGE_DIR + '/*.jpg')
for img_path in tqdm(images):
# Load image
img = load_img(img_path, target_size=(224, 224))
# Convert image to array
img = img_to_array(img)
# Expand dimensions to match the model input
img = np.expand_dims(img, axis=0)
# Preprocess image
img = preprocess_input(img)
# Extract features
feature = model.predict(img, verbose=0)
# Get image ID
img_id = os.path.basename(img_path).split('.')[0]
features[img_id] = feature
# Save features to disk
np.save('image_features.npy', features)
Step 4: Prepare Data for Training
Prepare the inputs (image features and partial captions) and outputs (next words in the captions) for our model.
4.1. Load Features
python
# Load features
features = np.load('image_features.npy', allow_pickle=True).item()
# Convert captions to list
all_captions = list(captions['caption'].values)
# Initialize and fit the tokenizer
tokenizer = Tokenizer()
tokenizer.fit_on_texts(all_captions)
# Save the tokenizer for future use
import pickle
with open('tokenizer.pkl', 'wb') as f:
pickle.dump(tokenizer, f)
vocab_size = len(tokenizer.word_index) + 1
print('Vocabulary Size:', vocab_size)
4.4. Determine Maximum Caption Length
python
max_length = max(len(caption.split()) for caption in all_captions)
print('Maximum Caption Length:', max_length)
4.5. Create Sequences
We create sequences of input words and the next word in the caption.
python
def create_sequences(tokenizer, max_length, desc_list, photo):
X1, X2, y = [], [], []
for desc in desc_list:
seq = tokenizer.texts_to_sequences([desc])[0]
for i in range(1, len(seq)):
# Input sequence
in_seq = seq[:i]
# Output word
out_seq = seq[i]
# Pad input sequence
in_seq = pad_sequences([in_seq], maxlen=max_length)[0]
# Encode output word as one-hot vector
out_seq = to_categorical([out_seq], num_classes=vocab_size)[0]
# Store sequences
X1.append(photo)
X2.append(in_seq)
y.append(out_seq)
return np.array(X1), np.array(X2), np.array(y)
4.6. Prepare the Data
python
X1, X2, y = [], [], []
for img_id, group in captions.groupby('image_id'):
# Get photo features
photo = features[img_id][0]
desc_list = group['caption'].tolist()
in_img, in_seq, out_word = create_sequences(tokenizer, max_length, desc_list, photo)
X1.extend(in_img)
X2.extend(in_seq)
y.extend(out_word)
X1 = np.array(X1)
X2 = np.array(X2)
y = np.array(y)
print('Data Shapes:')
print('X1:', X1.shape)
print('X2:', X2.shape)
print('y:', y.shape)
Step 5: Define the Model
We will define a simple model architecture suitable for training on a CPU.
We will train the model with a small number of epochs to keep training time reasonable.
6.1. Set Up Checkpoints
python
from keras.callbacks import ModelCheckpoint
# Define checkpoint callback to save the model
filepath = 'model-ep{epoch:03d}-loss{loss:.3f}.h5'
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
6.2. Train the Model
python
# Define the number of epochs
epochs = 10 # Increase this number for better results but longer training time
# Define the batch size
batch_size = 32
model.fit([X1, X2], y, epochs=epochs, verbose=1, callbacks=[checkpoint], batch_size=batch_size)
Step 7: Evaluate the Model
We can evaluate the model using BLEU scores.
7.1. Define Caption Generation Function
python
def generate_caption(model, tokenizer, photo, max_length):
in_text = 'startseq'
for i in range(max_length):
# Convert input text to sequence
sequence = tokenizer.texts_to_sequences([in_text])[0]
# Pad the sequence
sequence = pad_sequences([sequence], maxlen=max_length)
# Predict the next word
yhat = model.predict([photo,sequence], verbose=0)
# Get the index with the highest probability
yhat = np.argmax(yhat)
# Convert index to word
word = tokenizer.index_word.get(yhat)
if word is None:
break
# Append word as input for generating the next word
in_text += ' ' + word
if word == 'endseq':
break
return in_text
7.2. Evaluate on a Sample Image
python
# Load an image and generate caption
def extract_features_single(img_path, model):
img = load_img(img_path, target_size=(224, 224))
img = img_to_array(img)
img = np.expand_dims(img, axis=0)
img = preprocess_input(img)
feature = model.predict(img, verbose=0)
return feature
# Use VGG16 model for feature extraction
model_temp = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# Load the trained model
from keras.models import load_model
trained_model = load_model('model-ep010-lossX.XXX.h5') # Replace with your model file
# Image path for testing
img_path = IMAGE_DIR + '/1002674143_1b742ab4b8.jpg' # Replace with your chosen image
# Extract features
photo = extract_features_single(img_path, model_temp)
# Generate caption
caption = generate_caption(trained_model, tokenizer, photo, max_length)
print('Generated Caption:', caption)
Step 8: Generate Captions for New Images
You can use the above generate_caption function to generate captions for any image.
# Image path for new image
new_img_path = 'path_to_new_image.jpg' # Provide the path to your image
# Extract features
new_photo = extract_features_single(new_img_path, model_temp)
# Generate caption
new_caption = generate_caption(trained_model, tokenizer, new_photo, max_length)
# Display the image and its caption
display_image_caption(new_img_path, new_caption)
Tips for Smooth and Fast Training on CPU
Use a Smaller Dataset: Limit the number of images and captions if necessary.
Reduce Vocabulary Size: Remove rare words to reduce the vocabulary size.
Simplify Model Architecture: Use fewer layers or smaller units in LSTM.
Lower Batch Size: Use a batch size that your CPU can handle efficiently.
Limit Number of Epochs: Start with a small number of epochs to see if the model is learning.
Save and Load Models: Save your model checkpoints so you can resume training without starting over.
Conclusion
You've now created an image captioning model using the Flickr8k dataset in Google Colab on CPU. Due to computational limitations, the performance may not be on par with models trained on GPUs, but this approach provides a foundation for understanding image captioning models.
For better results, consider running the training on a GPU-enabled Colab instance or reducing the dataset and model complexity further.