|
import os |
|
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' |
|
import tensorflow as tf |
|
from utils.constants import MAX_LENGTH, IMAGE_SIZE, HIDDEN_UNITS |
|
import json |
|
import io |
|
|
|
|
|
class ImageCaptioner(): |
|
""" |
|
A custom class that builds the full model from the smaller sub models. It contains a cnn for feature extraction, a cnn_encoder to encode the features to a suitable dimension, |
|
an RNN decoder that contains an attention layer and RNN layer to generate text from the last predicted token + encoded image features. |
|
""" |
|
def __init__(self, cnn, cnn_encoder, rnn_decoder, **kwargs): |
|
""" |
|
Initializes the ImageCaptioner class with the given arguments. |
|
|
|
Args: |
|
cnn: A convolutional neural network that is used to extract features from images. |
|
cnn_encoder: A model that encodes the image features into a lower-dimensional space. |
|
rnn_decoder: A recurrent neural network that generates captions for the input images. |
|
max_length: The maximum length of the captions that the model generates. |
|
**kwargs: Additional keyword arguments that are not used in this implementation. |
|
""" |
|
self.cnn = cnn |
|
self.cnn_encoder = cnn_encoder |
|
self.rnn_decoder = rnn_decoder |
|
self.MAX_LENGTH = MAX_LENGTH |
|
self.START_TOKEN_INDEX = 1 |
|
self.END_TOKEN_INDEX = 2 |
|
self.HIDDEN_UNITS = HIDDEN_UNITS |
|
|
|
def __call__(self, inputs): |
|
""" |
|
Calls the MyCustomModel instance with the given inputs. |
|
|
|
Args: |
|
inputs: A list of input tensors containing the decoder input, encoded features, and hidden state. |
|
|
|
Returns: |
|
The output tensor of the RNN decoder. |
|
""" |
|
[decoder_input, encoded_features, hidden_state] = inputs |
|
return self.rnn_decoder(decoder_input, encoded_features, hidden_state, training=False) |
|
|
|
def predict(self, image): |
|
""" |
|
Generates a caption for the given image. |
|
|
|
Args: |
|
image: An input image tensor that the model generates a caption for. |
|
|
|
Returns: |
|
A tuple containing the indices of the predicted tokens and the attention weights sequence. |
|
""" |
|
image_features = self.cnn(image) |
|
reshaped_features = tf.reshape(image_features, (tf.shape(image_features)[0], -1, image_features.shape[3])) |
|
encoded_features = self.cnn_encoder(reshaped_features) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
n_captions = 2 |
|
results = tf.Variable(tf.zeros(shape=(n_captions, self.MAX_LENGTH),dtype='int32'), ) |
|
scores = tf.ones(shape=(n_captions,)) |
|
|
|
|
|
hiddens = tf.zeros((n_captions, self.HIDDEN_UNITS)) |
|
|
|
|
|
dec_inputs = tf.fill(dims=(n_captions,1), value=self.START_TOKEN_INDEX) |
|
batch_indices = list(range(n_captions)) |
|
for i in range(self.MAX_LENGTH): |
|
logits, hiddens, attention_weights = self.__call__([dec_inputs, encoded_features, hiddens]) |
|
predicted_ids = tf.random.categorical(logits, num_samples=1, dtype=tf.int32) |
|
predicted_ids = tf.squeeze(predicted_ids, axis=-1) |
|
|
|
|
|
element_indices = predicted_ids |
|
|
|
indices = tf.stack([batch_indices, element_indices], axis=1) |
|
scores *= tf.gather_nd(logits ,indices = indices) |
|
|
|
|
|
|
|
results[:,i].assign(predicted_ids) |
|
|
|
|
|
|
|
dec_inputs = tf.expand_dims(predicted_ids, 1) |
|
|
|
|
|
most_probable_sequence_id = int(tf.math.argmax(scores)) |
|
best_caption = list(results[most_probable_sequence_id].numpy()) |
|
print(best_caption) |
|
eos_loc = best_caption.index(self.END_TOKEN_INDEX) |
|
|
|
|
|
return best_caption[:eos_loc], None |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|