Spaces:
Sleeping
Sleeping
Update model.py
Browse files
model.py
CHANGED
|
@@ -2,16 +2,21 @@ import pickle
|
|
| 2 |
import tensorflow as tf
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
|
|
|
|
|
|
| 5 |
from keras.applications import efficientnet
|
| 6 |
-
|
| 7 |
-
|
| 8 |
# CONTANTS
|
| 9 |
-
MAX_LENGTH =
|
| 10 |
# VOCABULARY_SIZE = 10000
|
| 11 |
BATCH_SIZE = 32
|
| 12 |
BUFFER_SIZE = 1000
|
| 13 |
EMBEDDING_DIM = 512
|
| 14 |
UNITS = 512
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
# LOADING DATA
|
|
@@ -33,96 +38,108 @@ idx2word = tf.keras.layers.StringLookup(
|
|
| 33 |
|
| 34 |
# MODEL
|
| 35 |
def CNN_Encoder():
|
| 36 |
-
|
| 37 |
-
inception_v3 = efficientnet.EfficientNetB0(
|
| 38 |
input_shape=(*IMAGE_SIZE, 3),
|
| 39 |
include_top=False,
|
| 40 |
weights="imagenet",
|
| 41 |
)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
cnn_model = tf.keras.models.Model(inception_v3.input, output)
|
| 48 |
return cnn_model
|
| 49 |
-
|
| 50 |
|
| 51 |
|
|
|
|
| 52 |
class TransformerEncoderLayer(tf.keras.layers.Layer):
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
self.
|
| 57 |
-
self.
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
| 71 |
attention_mask=None,
|
| 72 |
-
training=training
|
| 73 |
)
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
return x
|
| 77 |
-
|
| 78 |
|
| 79 |
class Embeddings(tf.keras.layers.Layer):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
def
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def call(self, input_ids):
|
| 90 |
-
length = tf.shape(input_ids)[-1]
|
| 91 |
-
position_ids = tf.range(start=0, limit=length, delta=1)
|
| 92 |
-
position_ids = tf.expand_dims(position_ids, axis=0)
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
|
| 97 |
-
return token_embeddings + position_embeddings
|
| 98 |
|
| 99 |
|
| 100 |
class TransformerDecoderLayer(tf.keras.layers.Layer):
|
| 101 |
-
|
| 102 |
-
def __init__(self, embed_dim,
|
| 103 |
-
super().__init__()
|
| 104 |
-
self.
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
self
|
|
|
|
| 108 |
num_heads=num_heads, key_dim=embed_dim, dropout=0.1
|
| 109 |
)
|
| 110 |
-
self.attention_2 =
|
| 111 |
num_heads=num_heads, key_dim=embed_dim, dropout=0.1
|
| 112 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
self.
|
| 115 |
-
self.
|
| 116 |
-
self.
|
| 117 |
-
|
| 118 |
-
self.ffn_layer_1 = tf.keras.layers.Dense(units, activation="relu")
|
| 119 |
-
self.ffn_layer_2 = tf.keras.layers.Dense(embed_dim)
|
| 120 |
-
|
| 121 |
-
self.out = tf.keras.layers.Dense(tokenizer.vocabulary_size(), activation="softmax")
|
| 122 |
-
|
| 123 |
-
self.dropout_1 = tf.keras.layers.Dropout(0.3)
|
| 124 |
-
self.dropout_2 = tf.keras.layers.Dropout(0.5)
|
| 125 |
-
|
| 126 |
|
| 127 |
def call(self, input_ids, encoder_output, training, mask=None):
|
| 128 |
embeddings = self.embedding(input_ids)
|
|
@@ -165,6 +182,23 @@ class TransformerDecoderLayer(tf.keras.layers.Layer):
|
|
| 165 |
preds = self.out(ffn_out)
|
| 166 |
return preds
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
def get_causal_attention_mask(self, inputs):
|
| 170 |
input_shape = tf.shape(inputs)
|
|
@@ -178,7 +212,7 @@ class TransformerDecoderLayer(tf.keras.layers.Layer):
|
|
| 178 |
axis=0
|
| 179 |
)
|
| 180 |
return tf.tile(mask, mult)
|
| 181 |
-
|
| 182 |
|
| 183 |
class ImageCaptioningModel(tf.keras.Model):
|
| 184 |
|
|
@@ -303,8 +337,8 @@ def generate_caption(img, caption_model, add_noise=False):
|
|
| 303 |
|
| 304 |
|
| 305 |
def get_caption_model():
|
| 306 |
-
encoder = TransformerEncoderLayer(EMBEDDING_DIM, 1)
|
| 307 |
-
decoder = TransformerDecoderLayer(EMBEDDING_DIM,
|
| 308 |
|
| 309 |
cnn_model = CNN_Encoder()
|
| 310 |
|
|
@@ -316,7 +350,7 @@ def get_caption_model():
|
|
| 316 |
return batch
|
| 317 |
|
| 318 |
caption_model.call = call_fn
|
| 319 |
-
sample_x, sample_y = tf.random.normal((1, 299, 299, 3)), tf.zeros((1,
|
| 320 |
|
| 321 |
caption_model((sample_x, sample_y))
|
| 322 |
|
|
@@ -325,8 +359,8 @@ def get_caption_model():
|
|
| 325 |
caption_model.decoder(sample_y, sample_enc_out, training=False)
|
| 326 |
|
| 327 |
try:
|
| 328 |
-
caption_model.load_weights('saved_models/
|
| 329 |
except FileNotFoundError:
|
| 330 |
-
caption_model.load_weights('Image-Captioning/saved_models/
|
| 331 |
|
| 332 |
-
return caption_model
|
|
|
|
| 2 |
import tensorflow as tf
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
+
import keras
|
| 6 |
+
from keras import layers
|
| 7 |
from keras.applications import efficientnet
|
| 8 |
+
|
| 9 |
+
|
| 10 |
# CONTANTS
|
| 11 |
+
MAX_LENGTH = 80
|
| 12 |
# VOCABULARY_SIZE = 10000
|
| 13 |
BATCH_SIZE = 32
|
| 14 |
BUFFER_SIZE = 1000
|
| 15 |
EMBEDDING_DIM = 512
|
| 16 |
UNITS = 512
|
| 17 |
+
IMAGE_SIZE = (299, 299)
|
| 18 |
+
FF_DIM = 512
|
| 19 |
+
VOCAB_SIZE = 19774
|
| 20 |
|
| 21 |
|
| 22 |
# LOADING DATA
|
|
|
|
| 38 |
|
| 39 |
# MODEL
|
| 40 |
def CNN_Encoder():
|
| 41 |
+
base_model = efficientnet.EfficientNetB0(
|
|
|
|
| 42 |
input_shape=(*IMAGE_SIZE, 3),
|
| 43 |
include_top=False,
|
| 44 |
weights="imagenet",
|
| 45 |
)
|
| 46 |
+
# We freeze our feature extractor
|
| 47 |
+
base_model.trainable = False
|
| 48 |
+
base_model_out = base_model.output
|
| 49 |
+
base_model_out = layers.Reshape((-1, base_model_out.shape[-1]))(base_model_out)
|
| 50 |
+
cnn_model = keras.models.Model(base_model.input, base_model_out)
|
|
|
|
| 51 |
return cnn_model
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
+
#the extracted image features are passed to transformer based encoder that generates the new representation of inputs
|
| 55 |
class TransformerEncoderLayer(tf.keras.layers.Layer):
|
| 56 |
+
def __init__(self, embed_dim, dense_dim, num_heads, **kwargs):
|
| 57 |
+
super().__init__(**kwargs)
|
| 58 |
+
self.embed_dim = embed_dim
|
| 59 |
+
self.dense_dim = dense_dim
|
| 60 |
+
self.num_heads = num_heads
|
| 61 |
+
#captures dependencies between different parts of the input sequence.
|
| 62 |
+
self.attention_1 = layers.MultiHeadAttention(
|
| 63 |
+
num_heads=num_heads, key_dim=embed_dim, dropout=0.0
|
| 64 |
+
)
|
| 65 |
+
self.layernorm_1 = layers.LayerNormalization()
|
| 66 |
+
self.layernorm_2 = layers.LayerNormalization()
|
| 67 |
+
self.dense_1 = layers.Dense(embed_dim, activation="relu")
|
| 68 |
+
|
| 69 |
+
def call(self, inputs, training, mask=None):
|
| 70 |
+
inputs = self.layernorm_1(inputs)
|
| 71 |
+
inputs = self.dense_1(inputs)
|
| 72 |
+
|
| 73 |
+
attention_output_1 = self.attention_1(
|
| 74 |
+
query=inputs,
|
| 75 |
+
value=inputs,
|
| 76 |
+
key=inputs,
|
| 77 |
attention_mask=None,
|
| 78 |
+
training=training,
|
| 79 |
)
|
| 80 |
+
out_1 = self.layernorm_2(inputs + attention_output_1)
|
| 81 |
+
return out_1
|
|
|
|
|
|
|
| 82 |
|
| 83 |
class Embeddings(tf.keras.layers.Layer):
|
| 84 |
+
def __init__(self, sequence_length, vocab_size, embed_dim, **kwargs):
|
| 85 |
+
super().__init__(**kwargs)
|
| 86 |
+
self.token_embeddings = layers.Embedding(
|
| 87 |
+
input_dim=vocab_size, output_dim=embed_dim
|
| 88 |
+
)
|
| 89 |
+
self.position_embeddings = layers.Embedding(
|
| 90 |
+
input_dim=sequence_length, output_dim=embed_dim
|
| 91 |
+
)
|
| 92 |
+
self.sequence_length = sequence_length
|
| 93 |
+
self.vocab_size = vocab_size
|
| 94 |
+
self.embed_dim = embed_dim
|
| 95 |
+
self.embed_scale = tf.math.sqrt(tf.cast(embed_dim, tf.float32))#4== 2.0
|
| 96 |
|
| 97 |
+
def call(self, inputs):
|
| 98 |
+
length = tf.shape(inputs)[-1] #gets the length of input sequence or token
|
| 99 |
+
positions = tf.range(start=0, limit=length, delta=1)# Create a tensor of positions from 0 to length-1(if length is 5 then positions = [0,1,2,3,4])
|
| 100 |
+
embedded_tokens = self.token_embeddings(inputs)# Embed tokens using the token embedding layer(self.token_embeddings layer converts these discrete token indices into continuous, high-dimensional vectors (embeddings). Each token in the caption is represented by a dense vector that captures its semantic meaning.)
|
| 101 |
+
embedded_tokens = embedded_tokens * self.embed_scale # Scale the embedded tokens by the square root of the embedding dimension
|
| 102 |
+
embedded_positions = self.position_embeddings(positions) # Embed positions using the position embedding layer
|
| 103 |
+
return embedded_tokens + embedded_positions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
def compute_mask(self, inputs, mask=None):
|
| 106 |
+
return tf.math.not_equal(inputs, 0)
|
| 107 |
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
class TransformerDecoderLayer(tf.keras.layers.Layer):
|
| 111 |
+
|
| 112 |
+
def __init__(self, embed_dim, ff_dim, num_heads, **kwargs):
|
| 113 |
+
super().__init__(**kwargs)
|
| 114 |
+
self.embed_dim = embed_dim
|
| 115 |
+
self.ff_dim = ff_dim
|
| 116 |
+
self.num_heads = num_heads
|
| 117 |
+
#Defines two multi-head self-attention mechanisms (attention_1 and attention_2) with dropout.
|
| 118 |
+
self.attention_1 = layers.MultiHeadAttention(
|
| 119 |
num_heads=num_heads, key_dim=embed_dim, dropout=0.1
|
| 120 |
)
|
| 121 |
+
self.attention_2 = layers.MultiHeadAttention(
|
| 122 |
num_heads=num_heads, key_dim=embed_dim, dropout=0.1
|
| 123 |
)
|
| 124 |
+
#two feed-forward network layers with ReLU activation.
|
| 125 |
+
self.ffn_layer_1 = layers.Dense(ff_dim, activation="relu")
|
| 126 |
+
self.ffn_layer_2 = layers.Dense(embed_dim)
|
| 127 |
+
#normalization to the outputs of attention mechanisms
|
| 128 |
+
self.layernorm_1 = layers.LayerNormalization()
|
| 129 |
+
self.layernorm_2 = layers.LayerNormalization()
|
| 130 |
+
self.layernorm_3 = layers.LayerNormalization()
|
| 131 |
+
#Utilizes a PositionalEmbedding layer to incorporate positional information into the inputs.
|
| 132 |
+
self.embedding = Embeddings(
|
| 133 |
+
embed_dim=EMBEDDING_DIM,
|
| 134 |
+
sequence_length=MAX_LENGTH,
|
| 135 |
+
vocab_size=VOCAB_SIZE,
|
| 136 |
+
)
|
| 137 |
+
#softmax activation for generating predictions.
|
| 138 |
+
self.out = layers.Dense(VOCAB_SIZE, activation="softmax")
|
| 139 |
|
| 140 |
+
self.dropout_1 = layers.Dropout(0.3)
|
| 141 |
+
self.dropout_2 = layers.Dropout(0.5)
|
| 142 |
+
self.supports_masking = True # can be useful for handling variable-length sequences.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
def call(self, input_ids, encoder_output, training, mask=None):
|
| 145 |
embeddings = self.embedding(input_ids)
|
|
|
|
| 182 |
preds = self.out(ffn_out)
|
| 183 |
return preds
|
| 184 |
|
| 185 |
+
def get_causal_attention_mask(self, inputs):
|
| 186 |
+
input_shape = tf.shape(inputs)
|
| 187 |
+
batch_size, sequence_length = input_shape[0], input_shape[1]
|
| 188 |
+
i = tf.range(sequence_length)[:, tf.newaxis]
|
| 189 |
+
j = tf.range(sequence_length)
|
| 190 |
+
mask = tf.cast(i >= j, dtype="int32")
|
| 191 |
+
mask = tf.reshape(mask, (1, input_shape[1], input_shape[1]))
|
| 192 |
+
mult = tf.concat(
|
| 193 |
+
[
|
| 194 |
+
tf.expand_dims(batch_size, -1),
|
| 195 |
+
tf.constant([1, 1], dtype=tf.int32),
|
| 196 |
+
],
|
| 197 |
+
axis=0,
|
| 198 |
+
)
|
| 199 |
+
return tf.tile(mask, mult)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
|
| 203 |
def get_causal_attention_mask(self, inputs):
|
| 204 |
input_shape = tf.shape(inputs)
|
|
|
|
| 212 |
axis=0
|
| 213 |
)
|
| 214 |
return tf.tile(mask, mult)
|
| 215 |
+
|
| 216 |
|
| 217 |
class ImageCaptioningModel(tf.keras.Model):
|
| 218 |
|
|
|
|
| 337 |
|
| 338 |
|
| 339 |
def get_caption_model():
|
| 340 |
+
encoder = TransformerEncoderLayer(embed_dim=EMBEDDING_DIM, dense_dim=FF_DIM, num_heads=1)
|
| 341 |
+
decoder = TransformerDecoderLayer(embed_dim=EMBEDDING_DIM, ff_dim=FF_DIM, num_heads=2)
|
| 342 |
|
| 343 |
cnn_model = CNN_Encoder()
|
| 344 |
|
|
|
|
| 350 |
return batch
|
| 351 |
|
| 352 |
caption_model.call = call_fn
|
| 353 |
+
sample_x, sample_y = tf.random.normal((1, 299, 299, 3)), tf.zeros((1, 80))
|
| 354 |
|
| 355 |
caption_model((sample_x, sample_y))
|
| 356 |
|
|
|
|
| 359 |
caption_model.decoder(sample_y, sample_enc_out, training=False)
|
| 360 |
|
| 361 |
try:
|
| 362 |
+
caption_model.load_weights('saved_models/my_checkpoint.ckpt')
|
| 363 |
except FileNotFoundError:
|
| 364 |
+
caption_model.load_weights('Image-Captioning/saved_models/my_checkpoint.ckpt')
|
| 365 |
|
| 366 |
+
return caption_model
|