Spaces:
Sleeping
Sleeping
Upload 22 files
Browse files- .gitattributes +1 -0
- app.py +8 -0
- artifacts/caption_model.keras +3 -0
- artifacts/data_txt.npy +3 -0
- artifacts/vocabulary.npy +3 -0
- notebooks/Image_captioning.ipynb +972 -0
- requirements.txt +5 -0
- src/__init__.py +0 -0
- src/__pycache__/__init__.cpython-310.pyc +0 -0
- src/__pycache__/__init__.cpython-311.pyc +0 -0
- src/components/__init__.py +0 -0
- src/components/__pycache__/__init__.cpython-310.pyc +0 -0
- src/components/__pycache__/model.cpython-310.pyc +0 -0
- src/components/model.py +252 -0
- src/pipeline/__init__.py +0 -0
- src/pipeline/__pycache__/__init__.cpython-310.pyc +0 -0
- src/pipeline/__pycache__/__init__.cpython-311.pyc +0 -0
- src/pipeline/__pycache__/make_dataset.cpython-310.pyc +0 -0
- src/pipeline/__pycache__/predict.cpython-310.pyc +0 -0
- src/pipeline/__pycache__/predict.cpython-311.pyc +0 -0
- src/pipeline/make_dataset.py +117 -0
- src/pipeline/predict.py +81 -0
- src/pipeline/training.py +45 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
artifacts/caption_model.keras filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from src.pipeline.predict import generate_caption
|
3 |
+
|
4 |
+
demo = gr.Interface(fn=generate_caption,
|
5 |
+
inputs=gr.Image(),
|
6 |
+
outputs=[gr.Textbox(label="Generated Caption", lines=3)],
|
7 |
+
)
|
8 |
+
demo.launch()
|
artifacts/caption_model.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3015c7f04bee25a4c070cb043a9d7ed8edf5d3817d0299576ffed442cb1a750f
|
3 |
+
size 217502431
|
artifacts/data_txt.npy
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:349189a957c5c9d7ac2d46365981b556ce6d02b3facaf3a95c8249edc2d4be7a
|
3 |
+
size 34305968
|
artifacts/vocabulary.npy
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:25aee45770b60296f52c86aa049bf471cf284389972310dc6880bd9caf690e1f
|
3 |
+
size 784736
|
notebooks/Image_captioning.ipynb
ADDED
@@ -0,0 +1,972 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": null,
|
6 |
+
"metadata": {
|
7 |
+
"colab": {
|
8 |
+
"base_uri": "https://localhost:8080/",
|
9 |
+
"height": 1000
|
10 |
+
},
|
11 |
+
"id": "nUu3FjibHfQL",
|
12 |
+
"outputId": "8f9e98eb-f627-49f9-dcae-47dfdde9cb1c"
|
13 |
+
},
|
14 |
+
"outputs": [],
|
15 |
+
"source": [
|
16 |
+
"!pip install keras==2.15.0 tensorflow==2.15.0"
|
17 |
+
]
|
18 |
+
},
|
19 |
+
{
|
20 |
+
"cell_type": "code",
|
21 |
+
"execution_count": null,
|
22 |
+
"metadata": {
|
23 |
+
"id": "3dlzV23EMp8e"
|
24 |
+
},
|
25 |
+
"outputs": [],
|
26 |
+
"source": [
|
27 |
+
"import os\n",
|
28 |
+
"os.environ['KERAS_BACKEND'] = 'tensorflow'\n",
|
29 |
+
"import pathlib\n",
|
30 |
+
"import re"
|
31 |
+
]
|
32 |
+
},
|
33 |
+
{
|
34 |
+
"cell_type": "code",
|
35 |
+
"execution_count": null,
|
36 |
+
"metadata": {
|
37 |
+
"id": "vo6h7I0NNR2G"
|
38 |
+
},
|
39 |
+
"outputs": [],
|
40 |
+
"source": [
|
41 |
+
"import tensorflow as tf\n",
|
42 |
+
"import keras\n",
|
43 |
+
"import numpy as np\n",
|
44 |
+
"from keras import layers"
|
45 |
+
]
|
46 |
+
},
|
47 |
+
{
|
48 |
+
"cell_type": "code",
|
49 |
+
"execution_count": null,
|
50 |
+
"metadata": {
|
51 |
+
"colab": {
|
52 |
+
"base_uri": "https://localhost:8080/"
|
53 |
+
},
|
54 |
+
"id": "FXa1ANO0NdPB",
|
55 |
+
"outputId": "df1c87dd-c04f-469d-ec04-4b81e2c7917e"
|
56 |
+
},
|
57 |
+
"outputs": [
|
58 |
+
{
|
59 |
+
"name": "stdout",
|
60 |
+
"output_type": "stream",
|
61 |
+
"text": [
|
62 |
+
"2.15.0\n",
|
63 |
+
"2.15.0\n",
|
64 |
+
"tensorflow\n"
|
65 |
+
]
|
66 |
+
}
|
67 |
+
],
|
68 |
+
"source": [
|
69 |
+
"print(keras.__version__)\n",
|
70 |
+
"print(tf.__version__)\n",
|
71 |
+
"print(keras.backend.backend())"
|
72 |
+
]
|
73 |
+
},
|
74 |
+
{
|
75 |
+
"cell_type": "code",
|
76 |
+
"execution_count": null,
|
77 |
+
"metadata": {
|
78 |
+
"id": "iGRrFrjo-VQL"
|
79 |
+
},
|
80 |
+
"outputs": [],
|
81 |
+
"source": [
|
82 |
+
"# Path to the images\n",
|
83 |
+
"IMAGES_PATH = \"Flicker8k_Dataset\"\n",
|
84 |
+
"\n",
|
85 |
+
"# Desired image dimensions\n",
|
86 |
+
"IMAGE_SIZE = (299, 299)\n",
|
87 |
+
"\n",
|
88 |
+
"# Vocabulary size\n",
|
89 |
+
"VOCAB_SIZE = 10000\n",
|
90 |
+
"\n",
|
91 |
+
"# Fixed length allowed for any sequence\n",
|
92 |
+
"SEQ_LENGTH = 25\n",
|
93 |
+
"\n",
|
94 |
+
"# Dimension for the image embeddings and token embeddings\n",
|
95 |
+
"EMBED_DIM = 512\n",
|
96 |
+
"\n",
|
97 |
+
"# Per-layer units in the feed-forward network\n",
|
98 |
+
"FF_DIM = 512\n",
|
99 |
+
"\n",
|
100 |
+
"# Other training parameters\n",
|
101 |
+
"BATCH_SIZE = 64\n",
|
102 |
+
"EPOCHS = 30\n",
|
103 |
+
"AUTOTUNE = tf.data.AUTOTUNE"
|
104 |
+
]
|
105 |
+
},
|
106 |
+
{
|
107 |
+
"cell_type": "code",
|
108 |
+
"execution_count": null,
|
109 |
+
"metadata": {
|
110 |
+
"colab": {
|
111 |
+
"base_uri": "https://localhost:8080/",
|
112 |
+
"height": 36
|
113 |
+
},
|
114 |
+
"id": "Yiy02CsNO12W",
|
115 |
+
"outputId": "0f8b9a5e-c590-4b12-ec51-82741fadf4d9"
|
116 |
+
},
|
117 |
+
"outputs": [],
|
118 |
+
"source": [
|
119 |
+
"path = pathlib.Path(\".\")\n",
|
120 |
+
"keras.utils.get_file(\n",
|
121 |
+
" origin='https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_Dataset.zip',\n",
|
122 |
+
" cache_dir='.',\n",
|
123 |
+
" cache_subdir=path,\n",
|
124 |
+
" extract=True)\n",
|
125 |
+
"keras.utils.get_file(\n",
|
126 |
+
" origin='https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_text.zip',\n",
|
127 |
+
" cache_dir='.',\n",
|
128 |
+
" cache_subdir=path,\n",
|
129 |
+
" extract=True)"
|
130 |
+
]
|
131 |
+
},
|
132 |
+
{
|
133 |
+
"cell_type": "code",
|
134 |
+
"execution_count": null,
|
135 |
+
"metadata": {
|
136 |
+
"id": "8ChgFWRLUzhJ"
|
137 |
+
},
|
138 |
+
"outputs": [],
|
139 |
+
"source": [
|
140 |
+
"dataset = pathlib.Path(path, \"Flickr8k.token.txt\").read_text(encoding='utf-8').splitlines()"
|
141 |
+
]
|
142 |
+
},
|
143 |
+
{
|
144 |
+
"cell_type": "code",
|
145 |
+
"execution_count": null,
|
146 |
+
"metadata": {
|
147 |
+
"colab": {
|
148 |
+
"base_uri": "https://localhost:8080/"
|
149 |
+
},
|
150 |
+
"id": "Tp4TSNVZBlEt",
|
151 |
+
"outputId": "42113a83-cc68-4ed3-a630-8aba8a2b20d6"
|
152 |
+
},
|
153 |
+
"outputs": [],
|
154 |
+
"source": [
|
155 |
+
"dataset"
|
156 |
+
]
|
157 |
+
},
|
158 |
+
{
|
159 |
+
"cell_type": "code",
|
160 |
+
"execution_count": null,
|
161 |
+
"metadata": {
|
162 |
+
"id": "qYtr55VMWTTy"
|
163 |
+
},
|
164 |
+
"outputs": [],
|
165 |
+
"source": [
|
166 |
+
"dataset = [line.split('\\t') for line in dataset]"
|
167 |
+
]
|
168 |
+
},
|
169 |
+
{
|
170 |
+
"cell_type": "code",
|
171 |
+
"execution_count": null,
|
172 |
+
"metadata": {
|
173 |
+
"colab": {
|
174 |
+
"base_uri": "https://localhost:8080/"
|
175 |
+
},
|
176 |
+
"id": "9y18xIyfBovq",
|
177 |
+
"outputId": "7896d304-5864-46d8-8b63-945dfebd3151"
|
178 |
+
},
|
179 |
+
"outputs": [],
|
180 |
+
"source": [
|
181 |
+
"dataset"
|
182 |
+
]
|
183 |
+
},
|
184 |
+
{
|
185 |
+
"cell_type": "code",
|
186 |
+
"execution_count": null,
|
187 |
+
"metadata": {
|
188 |
+
"id": "aMQbS8ueZzii"
|
189 |
+
},
|
190 |
+
"outputs": [],
|
191 |
+
"source": [
|
192 |
+
"dataset = [[os.path.join(IMAGES_PATH,fname.split('#')[0].strip()), caption] for (fname, caption) in dataset]"
|
193 |
+
]
|
194 |
+
},
|
195 |
+
{
|
196 |
+
"cell_type": "code",
|
197 |
+
"execution_count": null,
|
198 |
+
"metadata": {
|
199 |
+
"colab": {
|
200 |
+
"base_uri": "https://localhost:8080/"
|
201 |
+
},
|
202 |
+
"id": "l7w7CxPuZtMG",
|
203 |
+
"outputId": "e3ca1665-277b-4c81-88d3-5c2c39ccd628"
|
204 |
+
},
|
205 |
+
"outputs": [],
|
206 |
+
"source": [
|
207 |
+
"dataset"
|
208 |
+
]
|
209 |
+
},
|
210 |
+
{
|
211 |
+
"cell_type": "code",
|
212 |
+
"execution_count": null,
|
213 |
+
"metadata": {
|
214 |
+
"colab": {
|
215 |
+
"base_uri": "https://localhost:8080/"
|
216 |
+
},
|
217 |
+
"id": "mkMvwXnZBFzD",
|
218 |
+
"outputId": "774cd7f3-0ffc-4273-862d-feb4366c3e20"
|
219 |
+
},
|
220 |
+
"outputs": [],
|
221 |
+
"source": [
|
222 |
+
"for i in dataset:\n",
|
223 |
+
" print(i)\n",
|
224 |
+
" break"
|
225 |
+
]
|
226 |
+
},
|
227 |
+
{
|
228 |
+
"cell_type": "code",
|
229 |
+
"execution_count": null,
|
230 |
+
"metadata": {
|
231 |
+
"id": "kqthDk6gZV3i"
|
232 |
+
},
|
233 |
+
"outputs": [],
|
234 |
+
"source": [
|
235 |
+
"caption_mapping = {}\n",
|
236 |
+
"text_data = []\n",
|
237 |
+
"X_en_data = []\n",
|
238 |
+
"X_de_data = []\n",
|
239 |
+
"Y_data = []"
|
240 |
+
]
|
241 |
+
},
|
242 |
+
{
|
243 |
+
"cell_type": "code",
|
244 |
+
"execution_count": null,
|
245 |
+
"metadata": {
|
246 |
+
"id": "yWbcI72w9Xv2"
|
247 |
+
},
|
248 |
+
"outputs": [],
|
249 |
+
"source": [
|
250 |
+
"for img_name, caption in dataset:\n",
|
251 |
+
" if img_name.endswith(\"jpg\"):\n",
|
252 |
+
" X_de_data.append(\"<start> \" + caption.strip().replace(\".\", \"\"))\n",
|
253 |
+
" Y_data.append(caption.strip().replace(\".\", \"\") + \" <end>\")\n",
|
254 |
+
" text_data.append(\"<start> \" + caption.strip().replace(\".\", \"\") + \" <end>\")\n",
|
255 |
+
" X_en_data.append(img_name)\n",
|
256 |
+
"\n",
|
257 |
+
"\n",
|
258 |
+
" if img_name in caption_mapping:\n",
|
259 |
+
" caption_mapping[img_name].append(caption)\n",
|
260 |
+
" else:\n",
|
261 |
+
" caption_mapping[img_name] = [caption]"
|
262 |
+
]
|
263 |
+
},
|
264 |
+
{
|
265 |
+
"cell_type": "code",
|
266 |
+
"execution_count": null,
|
267 |
+
"metadata": {
|
268 |
+
"id": "aqLKJwdVSydw"
|
269 |
+
},
|
270 |
+
"outputs": [],
|
271 |
+
"source": [
|
272 |
+
"for i in X_de_data:\n",
|
273 |
+
" if len(i) <= 2:\n",
|
274 |
+
" print(\"Y\")"
|
275 |
+
]
|
276 |
+
},
|
277 |
+
{
|
278 |
+
"cell_type": "code",
|
279 |
+
"execution_count": null,
|
280 |
+
"metadata": {
|
281 |
+
"colab": {
|
282 |
+
"base_uri": "https://localhost:8080/"
|
283 |
+
},
|
284 |
+
"id": "6RDJi5j4_C_z",
|
285 |
+
"outputId": "a6b9a4e5-94a3-40cc-98e6-8454e4e268ab"
|
286 |
+
},
|
287 |
+
"outputs": [],
|
288 |
+
"source": [
|
289 |
+
"print(X_en_data[0])\n",
|
290 |
+
"print(X_de_data[0])\n",
|
291 |
+
"print(Y_data[0])"
|
292 |
+
]
|
293 |
+
},
|
294 |
+
{
|
295 |
+
"cell_type": "code",
|
296 |
+
"execution_count": null,
|
297 |
+
"metadata": {
|
298 |
+
"id": "L_l0R04eJZnQ"
|
299 |
+
},
|
300 |
+
"outputs": [],
|
301 |
+
"source": [
|
302 |
+
"train_size=0.8\n",
|
303 |
+
"shuffle=True\n",
|
304 |
+
"np.random.seed(42)"
|
305 |
+
]
|
306 |
+
},
|
307 |
+
{
|
308 |
+
"cell_type": "code",
|
309 |
+
"execution_count": null,
|
310 |
+
"metadata": {
|
311 |
+
"colab": {
|
312 |
+
"base_uri": "https://localhost:8080/"
|
313 |
+
},
|
314 |
+
"id": "f-EnvEgh8sOB",
|
315 |
+
"outputId": "0cc36fe3-6cac-48ea-bcd4-9ace27dd5325"
|
316 |
+
},
|
317 |
+
"outputs": [],
|
318 |
+
"source": [
|
319 |
+
"zipped = list(zip(X_en_data, X_de_data, Y_data))\n",
|
320 |
+
"np.random.shuffle(zipped)\n",
|
321 |
+
"X_en_data, X_de_data, Y_data = zip(*zipped)\n",
|
322 |
+
"print(X_en_data[0])\n",
|
323 |
+
"print(X_de_data[0])\n",
|
324 |
+
"print(Y_data[0])"
|
325 |
+
]
|
326 |
+
},
|
327 |
+
{
|
328 |
+
"cell_type": "code",
|
329 |
+
"execution_count": null,
|
330 |
+
"metadata": {
|
331 |
+
"id": "Z7EFBHhdPeLs"
|
332 |
+
},
|
333 |
+
"outputs": [],
|
334 |
+
"source": [
|
335 |
+
"train_size = int(len(X_en_data)*train_size)\n",
|
336 |
+
"X_train_en = list(X_en_data[:train_size])\n",
|
337 |
+
"X_train_de = list(X_de_data[:train_size])\n",
|
338 |
+
"Y_train = list(Y_data[:train_size])\n",
|
339 |
+
"X_valid_en = list(X_en_data[train_size:])\n",
|
340 |
+
"X_valid_de = list(X_de_data[train_size:])\n",
|
341 |
+
"Y_valid = list(Y_data[train_size:])"
|
342 |
+
]
|
343 |
+
},
|
344 |
+
{
|
345 |
+
"cell_type": "code",
|
346 |
+
"execution_count": null,
|
347 |
+
"metadata": {
|
348 |
+
"colab": {
|
349 |
+
"base_uri": "https://localhost:8080/"
|
350 |
+
},
|
351 |
+
"id": "VEACJzQ0Tccm",
|
352 |
+
"outputId": "0c534618-1218-49df-ec73-54bdaf6c0452"
|
353 |
+
},
|
354 |
+
"outputs": [],
|
355 |
+
"source": [
|
356 |
+
"print(X_train_en[0])\n",
|
357 |
+
"print(X_train_de[0])\n",
|
358 |
+
"print(Y_train[0])\n",
|
359 |
+
"print(X_valid_en[0])\n",
|
360 |
+
"print(X_valid_de[0])\n",
|
361 |
+
"print(Y_valid[0])"
|
362 |
+
]
|
363 |
+
},
|
364 |
+
{
|
365 |
+
"cell_type": "code",
|
366 |
+
"execution_count": null,
|
367 |
+
"metadata": {
|
368 |
+
"id": "tZAf67OXAmxn"
|
369 |
+
},
|
370 |
+
"outputs": [],
|
371 |
+
"source": [
|
372 |
+
"strip_chars = \"!\\\"#$%&'()*+,-./:;=?@[\\]^_`{|}~\"\n",
|
373 |
+
"def custom_standardization(input_string):\n",
|
374 |
+
" lowercase = tf.strings.lower(input_string)\n",
|
375 |
+
" return tf.strings.regex_replace(lowercase, f'{re.escape(strip_chars)}', '')"
|
376 |
+
]
|
377 |
+
},
|
378 |
+
{
|
379 |
+
"cell_type": "code",
|
380 |
+
"execution_count": null,
|
381 |
+
"metadata": {
|
382 |
+
"id": "d6v0_3TuJZaG"
|
383 |
+
},
|
384 |
+
"outputs": [],
|
385 |
+
"source": [
|
386 |
+
"vectorization = keras.layers.TextVectorization(\n",
|
387 |
+
" max_tokens=VOCAB_SIZE,\n",
|
388 |
+
" output_mode=\"int\",\n",
|
389 |
+
" output_sequence_length=SEQ_LENGTH,\n",
|
390 |
+
" standardize=custom_standardization,\n",
|
391 |
+
" )\n",
|
392 |
+
"\n",
|
393 |
+
"vectorization.adapt(text_data)\n",
|
394 |
+
"vocab = np.array(vectorization.get_vocabulary())\n",
|
395 |
+
"np.save('./artifacts/vocabulary.npy', vocab)"
|
396 |
+
]
|
397 |
+
},
|
398 |
+
{
|
399 |
+
"cell_type": "code",
|
400 |
+
"execution_count": null,
|
401 |
+
"metadata": {
|
402 |
+
"id": "WcXsq2LzNpda"
|
403 |
+
},
|
404 |
+
"outputs": [],
|
405 |
+
"source": [
|
406 |
+
"def decode_and_resize(img_path):\n",
|
407 |
+
" img = tf.io.read_file(img_path)\n",
|
408 |
+
" img = tf.image.decode_jpeg(img, channels=3)\n",
|
409 |
+
" img = tf.image.resize(img, IMAGE_SIZE)\n",
|
410 |
+
" img = tf.image.convert_image_dtype(img, tf.float32)\n",
|
411 |
+
" return img\n",
|
412 |
+
"\n",
|
413 |
+
"\n",
|
414 |
+
"def process_input(img_cap, y_captions):\n",
|
415 |
+
" img_path, x_captions = img_cap\n",
|
416 |
+
" return ((decode_and_resize(img_path), vectorization(x_captions)), vectorization(y_captions))\n",
|
417 |
+
"\n",
|
418 |
+
"\n",
|
419 |
+
"def make_dataset(images, x_captions, y_captions):\n",
|
420 |
+
" dataset = tf.data.Dataset.from_tensor_slices(((images, x_captions), y_captions))\n",
|
421 |
+
" dataset = dataset.map(process_input, num_parallel_calls=AUTOTUNE)\n",
|
422 |
+
" dataset = dataset.batch(BATCH_SIZE).prefetch(AUTOTUNE)\n",
|
423 |
+
"\n",
|
424 |
+
" return dataset\n",
|
425 |
+
"\n",
|
426 |
+
"\n",
|
427 |
+
"\n",
|
428 |
+
"train_dataset = make_dataset(X_train_en, X_train_de, Y_train)\n",
|
429 |
+
"\n",
|
430 |
+
"valid_dataset = make_dataset(X_valid_en, X_valid_de, Y_valid)\n"
|
431 |
+
]
|
432 |
+
},
|
433 |
+
{
|
434 |
+
"cell_type": "code",
|
435 |
+
"execution_count": null,
|
436 |
+
"metadata": {
|
437 |
+
"id": "CC_icKqG5xGg"
|
438 |
+
},
|
439 |
+
"outputs": [],
|
440 |
+
"source": [
|
441 |
+
"image_augmentation = keras.Sequential(\n",
|
442 |
+
" [\n",
|
443 |
+
" keras.layers.RandomFlip(\"horizontal\"),\n",
|
444 |
+
" keras.layers.RandomRotation(0.2),\n",
|
445 |
+
" keras.layers.RandomContrast(0.3),\n",
|
446 |
+
" ]\n",
|
447 |
+
")\n",
|
448 |
+
"@keras.saving.register_keras_serializable()\n",
|
449 |
+
"def get_cnn_model():\n",
|
450 |
+
" base_model = keras.applications.efficientnet.EfficientNetB0(\n",
|
451 |
+
" input_shape=(*IMAGE_SIZE, 3),\n",
|
452 |
+
" include_top=False,\n",
|
453 |
+
" weights=\"imagenet\"\n",
|
454 |
+
" )\n",
|
455 |
+
" base_model.trainable = False\n",
|
456 |
+
" base_model_out = base_model.output\n",
|
457 |
+
" base_model_out = layers.Reshape((-1, base_model_out.shape[-1]))(base_model_out)\n",
|
458 |
+
" cnn_model = keras.models.Model(base_model.input, base_model_out)\n",
|
459 |
+
" return cnn_model\n",
|
460 |
+
"\n",
|
461 |
+
"@keras.saving.register_keras_serializable()\n",
|
462 |
+
"class TransformerEncoderBlock(layers.Layer):\n",
|
463 |
+
" def __init__(self, embed_dim, dense_dim, num_heads, **kwargs):\n",
|
464 |
+
" super().__init__(**kwargs)\n",
|
465 |
+
" self.embed_dim = embed_dim\n",
|
466 |
+
" self.dense_dim = dense_dim\n",
|
467 |
+
" self.num_heads = num_heads\n",
|
468 |
+
" self.attention_1 = layers.MultiHeadAttention(\n",
|
469 |
+
" num_heads=num_heads, key_dim=embed_dim, dropout=0.0\n",
|
470 |
+
" )\n",
|
471 |
+
" self.layernorm_1 = layers.LayerNormalization()\n",
|
472 |
+
" self.layernorm_2 = layers.LayerNormalization()\n",
|
473 |
+
" self.dense_1 = layers.Dense(embed_dim, activation=\"relu\")\n",
|
474 |
+
"\n",
|
475 |
+
" def get_config(self):\n",
|
476 |
+
" base_config = super().get_config()\n",
|
477 |
+
" config = {\n",
|
478 |
+
" \"embed_dim\": self.embed_dim,\n",
|
479 |
+
" \"dense_dim\": self.dense_dim,\n",
|
480 |
+
" \"num_heads\": self.num_heads,\n",
|
481 |
+
" }\n",
|
482 |
+
" return {**base_config, **config}\n",
|
483 |
+
"\n",
|
484 |
+
"\n",
|
485 |
+
" def call(self, inputs, training):\n",
|
486 |
+
" inputs = self.layernorm_1(inputs)\n",
|
487 |
+
" inputs = self.dense_1(inputs)\n",
|
488 |
+
"\n",
|
489 |
+
" attention_output_1 = self.attention_1(\n",
|
490 |
+
" query=inputs,\n",
|
491 |
+
" value=inputs,\n",
|
492 |
+
" key=inputs,\n",
|
493 |
+
" training=training,\n",
|
494 |
+
" )\n",
|
495 |
+
" out_1 = self.layernorm_2(inputs + attention_output_1)\n",
|
496 |
+
" return out_1\n",
|
497 |
+
"\n",
|
498 |
+
"@keras.saving.register_keras_serializable()\n",
|
499 |
+
"class PositionalEmbedding(layers.Layer):\n",
|
500 |
+
" def __init__(self, sequence_length, vocab_size, embed_dim, **kwargs):\n",
|
501 |
+
" super().__init__(**kwargs)\n",
|
502 |
+
" self.token_embeddings = layers.Embedding(\n",
|
503 |
+
" input_dim=vocab_size, output_dim=embed_dim, mask_zero=True\n",
|
504 |
+
" )\n",
|
505 |
+
" self.position_embeddings = layers.Embedding(\n",
|
506 |
+
" input_dim=sequence_length, output_dim=embed_dim\n",
|
507 |
+
" )\n",
|
508 |
+
" self.sequence_length = sequence_length\n",
|
509 |
+
" self.vocab_size = vocab_size\n",
|
510 |
+
" self.embed_dim = embed_dim\n",
|
511 |
+
"\n",
|
512 |
+
" self.add = layers.Add()\n",
|
513 |
+
"\n",
|
514 |
+
" def get_config(self):\n",
|
515 |
+
" base_config = super().get_config()\n",
|
516 |
+
" config = {\n",
|
517 |
+
" \"sequence_length\": self.sequence_length,\n",
|
518 |
+
" \"vocab_size\": self.vocab_size,\n",
|
519 |
+
" \"embed_dim\": self.embed_dim,\n",
|
520 |
+
" }\n",
|
521 |
+
" return {**base_config, **config}\n",
|
522 |
+
"\n",
|
523 |
+
" def call(self, seq):\n",
|
524 |
+
" seq = self.token_embeddings(seq)\n",
|
525 |
+
"\n",
|
526 |
+
" x = tf.range(tf.shape(seq)[1])\n",
|
527 |
+
" x = x[tf.newaxis, :]\n",
|
528 |
+
" x = self.position_embeddings(x)\n",
|
529 |
+
"\n",
|
530 |
+
" return self.add([seq,x])\n",
|
531 |
+
"\n",
|
532 |
+
"@keras.saving.register_keras_serializable()\n",
|
533 |
+
"class TransformerDecoderBlock(layers.Layer):\n",
|
534 |
+
" def __init__(self, embed_dim, ff_dim, num_heads, **kwargs):\n",
|
535 |
+
" super().__init__(**kwargs)\n",
|
536 |
+
" self.embed_dim = embed_dim\n",
|
537 |
+
" self.ff_dim = ff_dim\n",
|
538 |
+
" self.num_heads = num_heads\n",
|
539 |
+
" self.attention_1 = layers.MultiHeadAttention(\n",
|
540 |
+
" num_heads=num_heads, key_dim=embed_dim, dropout=0.1\n",
|
541 |
+
" )\n",
|
542 |
+
" self.attention_2 = layers.MultiHeadAttention(\n",
|
543 |
+
" num_heads=num_heads, key_dim=embed_dim, dropout=0.1\n",
|
544 |
+
" )\n",
|
545 |
+
" self.ffn_layer_1 = layers.Dense(ff_dim, activation=\"relu\")\n",
|
546 |
+
" self.ffn_layer_2 = layers.Dense(embed_dim)\n",
|
547 |
+
"\n",
|
548 |
+
" self.layernorm_1 = layers.LayerNormalization()\n",
|
549 |
+
" self.layernorm_2 = layers.LayerNormalization()\n",
|
550 |
+
" self.layernorm_3 = layers.LayerNormalization()\n",
|
551 |
+
"\n",
|
552 |
+
" self.embedding = PositionalEmbedding(\n",
|
553 |
+
" embed_dim=EMBED_DIM,\n",
|
554 |
+
" sequence_length=SEQ_LENGTH,\n",
|
555 |
+
" vocab_size=VOCAB_SIZE,\n",
|
556 |
+
" )\n",
|
557 |
+
" self.out = layers.Dense(VOCAB_SIZE, activation=\"softmax\")\n",
|
558 |
+
"\n",
|
559 |
+
" self.dropout_1 = layers.Dropout(0.3)\n",
|
560 |
+
" self.dropout_2 = layers.Dropout(0.5)\n",
|
561 |
+
" self.supports_masking = True\n",
|
562 |
+
"\n",
|
563 |
+
" def get_config(self):\n",
|
564 |
+
" base_config = super().get_config()\n",
|
565 |
+
" config = {\n",
|
566 |
+
" \"embed_dim\": self.embed_dim,\n",
|
567 |
+
" \"ff_dim\": self.ff_dim,\n",
|
568 |
+
" \"num_heads\": self.num_heads,\n",
|
569 |
+
"\n",
|
570 |
+
" }\n",
|
571 |
+
" return {**base_config, **config}\n",
|
572 |
+
"\n",
|
573 |
+
"\n",
|
574 |
+
"\n",
|
575 |
+
" def call(self, inputs, encoder_outputs, training, mask=None):\n",
|
576 |
+
" inputs = self.embedding(inputs)\n",
|
577 |
+
"\n",
|
578 |
+
" attention_output_1 = self.attention_1(\n",
|
579 |
+
" query=inputs,\n",
|
580 |
+
" value=inputs,\n",
|
581 |
+
" key=inputs,\n",
|
582 |
+
" training=training,\n",
|
583 |
+
" use_causal_mask=True\n",
|
584 |
+
" )\n",
|
585 |
+
" out_1 = self.layernorm_1(inputs + attention_output_1)\n",
|
586 |
+
"\n",
|
587 |
+
" attention_output_2 = self.attention_2(\n",
|
588 |
+
" query=out_1,\n",
|
589 |
+
" value=encoder_outputs,\n",
|
590 |
+
" key=encoder_outputs,\n",
|
591 |
+
" training=training,\n",
|
592 |
+
" )\n",
|
593 |
+
" out_2 = self.layernorm_2(out_1 + attention_output_2)\n",
|
594 |
+
"\n",
|
595 |
+
" ffn_out = self.ffn_layer_1(out_2)\n",
|
596 |
+
" ffn_out = self.dropout_1(ffn_out, training=training)\n",
|
597 |
+
" ffn_out = self.ffn_layer_2(ffn_out)\n",
|
598 |
+
"\n",
|
599 |
+
" ffn_out = self.layernorm_3(ffn_out + out_2, training=training)\n",
|
600 |
+
" ffn_out = self.dropout_2(ffn_out, training=training)\n",
|
601 |
+
" preds = self.out(ffn_out)\n",
|
602 |
+
" return preds\n",
|
603 |
+
"\n",
|
604 |
+
"\n",
|
605 |
+
"@keras.saving.register_keras_serializable()\n",
|
606 |
+
"class ImageCaptioningModel(keras.Model):\n",
|
607 |
+
" def __init__(\n",
|
608 |
+
" self,\n",
|
609 |
+
" cnn_model,\n",
|
610 |
+
" encoder,\n",
|
611 |
+
" decoder,\n",
|
612 |
+
" image_aug=None,\n",
|
613 |
+
" **kwargs\n",
|
614 |
+
" ):\n",
|
615 |
+
" super().__init__(**kwargs)\n",
|
616 |
+
" self.cnn_model = cnn_model\n",
|
617 |
+
" self.encoder = encoder\n",
|
618 |
+
" self.decoder = decoder\n",
|
619 |
+
" self.image_aug = image_aug\n",
|
620 |
+
"\n",
|
621 |
+
" def get_config(self):\n",
|
622 |
+
" base_config = super().get_config()\n",
|
623 |
+
" config = {\n",
|
624 |
+
" \"cnn_model\": self.cnn_model,\n",
|
625 |
+
" \"encoder\": self.encoder,\n",
|
626 |
+
" \"decoder\": self.decoder,\n",
|
627 |
+
" \"image_aug\": self.image_aug,\n",
|
628 |
+
" }\n",
|
629 |
+
" return {**base_config, **config}\n",
|
630 |
+
"\n",
|
631 |
+
" @classmethod\n",
|
632 |
+
" def from_config(cls, config):\n",
|
633 |
+
" # Note that you can also use [`keras.saving.deserialize_keras_object`](/api/models/model_saving_apis/serialization_utils#deserializekerasobject-function) here\n",
|
634 |
+
" config[\"cnn_model\"] = keras.saving.deserialize_keras_object(config[\"cnn_model\"])\n",
|
635 |
+
" config[\"encoder\"] = keras.saving.deserialize_keras_object(config[\"encoder\"])\n",
|
636 |
+
" config[\"decoder\"] = keras.saving.deserialize_keras_object(config[\"decoder\"])\n",
|
637 |
+
" config[\"image_aug\"] = keras.saving.deserialize_keras_object(config[\"image_aug\"])\n",
|
638 |
+
"\n",
|
639 |
+
" # Instantiate the ImageCaptioningModel with the remaining configuration\n",
|
640 |
+
" return cls(**config)\n",
|
641 |
+
"\n",
|
642 |
+
" def call(self, inputs, training):\n",
|
643 |
+
" img, caption = inputs\n",
|
644 |
+
" if self.image_aug:\n",
|
645 |
+
" img = self.image_aug(img)\n",
|
646 |
+
" img_embed = self.cnn_model(img)\n",
|
647 |
+
" encoder_out = self.encoder(img_embed, training=training)\n",
|
648 |
+
" pred = self.decoder(caption, encoder_out, training=training)\n",
|
649 |
+
" return pred\n",
|
650 |
+
"\n",
|
651 |
+
"\n"
|
652 |
+
]
|
653 |
+
},
|
654 |
+
{
|
655 |
+
"cell_type": "code",
|
656 |
+
"execution_count": null,
|
657 |
+
"metadata": {
|
658 |
+
"id": "MGCXWbEY6tTn"
|
659 |
+
},
|
660 |
+
"outputs": [],
|
661 |
+
"source": [
|
662 |
+
"cnn_model = get_cnn_model()\n",
|
663 |
+
"encoder = TransformerEncoderBlock(embed_dim=EMBED_DIM, dense_dim=FF_DIM, num_heads=1)\n",
|
664 |
+
"decoder = TransformerDecoderBlock(embed_dim=EMBED_DIM, ff_dim=FF_DIM, num_heads=2)\n",
|
665 |
+
"caption_model = ImageCaptioningModel(\n",
|
666 |
+
" cnn_model=cnn_model,\n",
|
667 |
+
" encoder=encoder,\n",
|
668 |
+
" decoder=decoder,\n",
|
669 |
+
" image_aug=image_augmentation,\n",
|
670 |
+
")"
|
671 |
+
]
|
672 |
+
},
|
673 |
+
{
|
674 |
+
"cell_type": "code",
|
675 |
+
"execution_count": null,
|
676 |
+
"metadata": {
|
677 |
+
"colab": {
|
678 |
+
"base_uri": "https://localhost:8080/",
|
679 |
+
"height": 391
|
680 |
+
},
|
681 |
+
"id": "LtUx3PjMB6aJ",
|
682 |
+
"outputId": "3cdc513a-321d-425b-a617-549e42fbf404"
|
683 |
+
},
|
684 |
+
"outputs": [],
|
685 |
+
"source": [
|
686 |
+
"\n",
|
687 |
+
"early_stopping = keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True)\n",
|
688 |
+
"\n",
|
689 |
+
"\n",
|
690 |
+
"@keras.saving.register_keras_serializable()\n",
|
691 |
+
"class LRSchedule(keras.optimizers.schedules.LearningRateSchedule):\n",
|
692 |
+
" def __init__(self, post_warmup_learning_rate, warmup_steps, **kwargs):\n",
|
693 |
+
" super().__init__(**kwargs)\n",
|
694 |
+
" self.post_warmup_learning_rate = post_warmup_learning_rate\n",
|
695 |
+
" self.warmup_steps = warmup_steps\n",
|
696 |
+
"\n",
|
697 |
+
" def get_config(self):\n",
|
698 |
+
" config = {\n",
|
699 |
+
" \"post_warmup_learning_rate\": self.post_warmup_learning_rate,\n",
|
700 |
+
" \"warmup_steps\": self.warmup_steps,\n",
|
701 |
+
" }\n",
|
702 |
+
" return config\n",
|
703 |
+
"\n",
|
704 |
+
" def __call__(self, step):\n",
|
705 |
+
" global_step = tf.cast(step, tf.float32)\n",
|
706 |
+
" warmup_steps = tf.cast(self.warmup_steps, tf.float32)\n",
|
707 |
+
" warmup_progress = global_step / warmup_steps\n",
|
708 |
+
" warmup_learning_rate = self.post_warmup_learning_rate * warmup_progress\n",
|
709 |
+
" return tf.cond(\n",
|
710 |
+
" global_step < warmup_steps,\n",
|
711 |
+
" lambda: warmup_learning_rate,\n",
|
712 |
+
" lambda: self.post_warmup_learning_rate,\n",
|
713 |
+
" )\n",
|
714 |
+
"\n",
|
715 |
+
"\n",
|
716 |
+
"num_train_steps = len(train_dataset) * EPOCHS\n",
|
717 |
+
"num_warmup_steps = num_train_steps // 15\n",
|
718 |
+
"lr_schedule = LRSchedule(post_warmup_learning_rate=1e-4, warmup_steps=num_warmup_steps)\n",
|
719 |
+
"\n",
|
720 |
+
"caption_model.compile(optimizer=keras.optimizers.Adam(lr_schedule), loss='sparse_categorical_crossentropy',\n",
|
721 |
+
" metrics=['accuracy'])\n",
|
722 |
+
"\n",
|
723 |
+
"caption_model.fit(\n",
|
724 |
+
" train_dataset,\n",
|
725 |
+
" epochs=EPOCHS,\n",
|
726 |
+
" validation_data=valid_dataset,\n",
|
727 |
+
" callbacks=[early_stopping],\n",
|
728 |
+
")"
|
729 |
+
]
|
730 |
+
},
|
731 |
+
{
|
732 |
+
"cell_type": "code",
|
733 |
+
"execution_count": null,
|
734 |
+
"metadata": {
|
735 |
+
"id": "M10k_8_gBKxz"
|
736 |
+
},
|
737 |
+
"outputs": [],
|
738 |
+
"source": [
|
739 |
+
"caption_model.save(\"caption_model.keras\")"
|
740 |
+
]
|
741 |
+
},
|
742 |
+
{
|
743 |
+
"cell_type": "code",
|
744 |
+
"execution_count": null,
|
745 |
+
"metadata": {
|
746 |
+
"id": "f1FD15MiBQSh"
|
747 |
+
},
|
748 |
+
"outputs": [],
|
749 |
+
"source": [
|
750 |
+
"loaded_model = keras.models.load_model(\"caption_model.keras\", compile=True)"
|
751 |
+
]
|
752 |
+
},
|
753 |
+
{
|
754 |
+
"cell_type": "code",
|
755 |
+
"execution_count": null,
|
756 |
+
"metadata": {
|
757 |
+
"colab": {
|
758 |
+
"base_uri": "https://localhost:8080/"
|
759 |
+
},
|
760 |
+
"id": "ULoizN2kfR2W",
|
761 |
+
"outputId": "fa3f0e8f-f1cc-4821-8f37-3977c6feb047"
|
762 |
+
},
|
763 |
+
"outputs": [],
|
764 |
+
"source": [
|
765 |
+
"caption_model.summary()"
|
766 |
+
]
|
767 |
+
},
|
768 |
+
{
|
769 |
+
"cell_type": "code",
|
770 |
+
"execution_count": null,
|
771 |
+
"metadata": {
|
772 |
+
"colab": {
|
773 |
+
"base_uri": "https://localhost:8080/"
|
774 |
+
},
|
775 |
+
"id": "MUTEhm28fVdN",
|
776 |
+
"outputId": "b020cfe6-b3e4-4c84-cf58-e59a233c6035"
|
777 |
+
},
|
778 |
+
"outputs": [],
|
779 |
+
"source": [
|
780 |
+
"loaded_model.summary()"
|
781 |
+
]
|
782 |
+
},
|
783 |
+
{
|
784 |
+
"cell_type": "code",
|
785 |
+
"execution_count": null,
|
786 |
+
"metadata": {
|
787 |
+
"colab": {
|
788 |
+
"base_uri": "https://localhost:8080/"
|
789 |
+
},
|
790 |
+
"id": "k4H_CsBUYBSi",
|
791 |
+
"outputId": "590ecbca-1980-4456-89f1-ce0b2643506f"
|
792 |
+
},
|
793 |
+
"outputs": [],
|
794 |
+
"source": [
|
795 |
+
"caption_model.evaluate(valid_dataset)"
|
796 |
+
]
|
797 |
+
},
|
798 |
+
{
|
799 |
+
"cell_type": "code",
|
800 |
+
"execution_count": null,
|
801 |
+
"metadata": {
|
802 |
+
"colab": {
|
803 |
+
"base_uri": "https://localhost:8080/"
|
804 |
+
},
|
805 |
+
"id": "xzYtGvSPYA5H",
|
806 |
+
"outputId": "5b103038-b02d-491a-d08c-c252682590fd"
|
807 |
+
},
|
808 |
+
"outputs": [],
|
809 |
+
"source": [
|
810 |
+
"loaded_model.evaluate(valid_dataset)"
|
811 |
+
]
|
812 |
+
},
|
813 |
+
{
|
814 |
+
"cell_type": "code",
|
815 |
+
"execution_count": null,
|
816 |
+
"metadata": {
|
817 |
+
"id": "UvRoJqZ-Xp7g"
|
818 |
+
},
|
819 |
+
"outputs": [],
|
820 |
+
"source": [
|
821 |
+
"import matplotlib.pyplot as plt"
|
822 |
+
]
|
823 |
+
},
|
824 |
+
{
|
825 |
+
"cell_type": "code",
|
826 |
+
"execution_count": null,
|
827 |
+
"metadata": {
|
828 |
+
"colab": {
|
829 |
+
"base_uri": "https://localhost:8080/",
|
830 |
+
"height": 452
|
831 |
+
},
|
832 |
+
"id": "5edj0qS3YCTZ",
|
833 |
+
"outputId": "fefb8277-944e-4a42-aa64-aef5df6ab92b"
|
834 |
+
},
|
835 |
+
"outputs": [],
|
836 |
+
"source": [
|
837 |
+
"\n",
|
838 |
+
"\n",
|
839 |
+
"vocab = vectorization.get_vocabulary()\n",
|
840 |
+
"index_lookup = dict(zip(range(len(vocab)), vocab))\n",
|
841 |
+
"max_decoded_sentence_length = SEQ_LENGTH - 1\n",
|
842 |
+
"valid_images = list(X_train_en)\n",
|
843 |
+
"\n",
|
844 |
+
"\n",
|
845 |
+
"def generate_caption():\n",
|
846 |
+
" # Select a random image from the validation dataset\n",
|
847 |
+
" sample_img = np.random.choice(valid_images)\n",
|
848 |
+
"\n",
|
849 |
+
" # Read the image from the disk\n",
|
850 |
+
" sample_img = decode_and_resize(sample_img)\n",
|
851 |
+
" img = sample_img.numpy().clip(0, 255).astype(np.uint8)\n",
|
852 |
+
" plt.imshow(img)\n",
|
853 |
+
" plt.show()\n",
|
854 |
+
"\n",
|
855 |
+
" # Pass the image to the CNN\n",
|
856 |
+
" img = tf.expand_dims(sample_img, 0)\n",
|
857 |
+
" img = caption_model.cnn_model(img)\n",
|
858 |
+
"\n",
|
859 |
+
" # Pass the image features to the Transformer encoder\n",
|
860 |
+
" encoded_img = caption_model.encoder(img, training=False)\n",
|
861 |
+
"\n",
|
862 |
+
" # Generate the caption using the Transformer decoder\n",
|
863 |
+
" decoded_caption = \"<start> \"\n",
|
864 |
+
" for i in range(max_decoded_sentence_length):\n",
|
865 |
+
" tokenized_caption = vectorization([decoded_caption])\n",
|
866 |
+
" mask = tf.math.not_equal(tokenized_caption, 0)\n",
|
867 |
+
" predictions = caption_model.decoder(\n",
|
868 |
+
" tokenized_caption, encoded_img, training=False, mask=mask\n",
|
869 |
+
" )\n",
|
870 |
+
" sampled_token_index = np.argmax(predictions[0, i, :])\n",
|
871 |
+
" sampled_token = index_lookup[sampled_token_index]\n",
|
872 |
+
" if sampled_token == \"<end>\":\n",
|
873 |
+
" break\n",
|
874 |
+
" decoded_caption += \" \" + sampled_token\n",
|
875 |
+
"\n",
|
876 |
+
" decoded_caption = decoded_caption.replace(\"<start> \", \"\")\n",
|
877 |
+
" decoded_caption = decoded_caption.replace(\" <end>\", \"\").strip()\n",
|
878 |
+
" print(\"Predicted Caption: \", decoded_caption)\n",
|
879 |
+
"\n",
|
880 |
+
"\n",
|
881 |
+
"# Check predictions for a few samples\n",
|
882 |
+
"generate_caption()\n"
|
883 |
+
]
|
884 |
+
},
|
885 |
+
{
|
886 |
+
"cell_type": "code",
|
887 |
+
"execution_count": null,
|
888 |
+
"metadata": {
|
889 |
+
"colab": {
|
890 |
+
"base_uri": "https://localhost:8080/",
|
891 |
+
"height": 715
|
892 |
+
},
|
893 |
+
"id": "3zRF5hAEbOdm",
|
894 |
+
"outputId": "85611bc9-70b9-4282-aac4-53d3af5c2c18"
|
895 |
+
},
|
896 |
+
"outputs": [],
|
897 |
+
"source": [
|
898 |
+
"\n",
|
899 |
+
"\n",
|
900 |
+
"vocab = vectorization.get_vocabulary()\n",
|
901 |
+
"index_lookup = dict(zip(range(len(vocab)), vocab))\n",
|
902 |
+
"max_decoded_sentence_length = SEQ_LENGTH - 1\n",
|
903 |
+
"valid_images = list(X_train_en)\n",
|
904 |
+
"\n",
|
905 |
+
"\n",
|
906 |
+
"def generate_caption():\n",
|
907 |
+
" # Select a random image from the validation dataset\n",
|
908 |
+
" sample_img = np.random.choice(valid_images)\n",
|
909 |
+
"\n",
|
910 |
+
" # Read the image from the disk\n",
|
911 |
+
" sample_img = decode_and_resize(sample_img)\n",
|
912 |
+
" img = sample_img.numpy().clip(0, 255).astype(np.uint8)\n",
|
913 |
+
" plt.imshow(img)\n",
|
914 |
+
" plt.show()\n",
|
915 |
+
"\n",
|
916 |
+
" # Pass the image to the CNN\n",
|
917 |
+
" img = tf.expand_dims(sample_img, 0)\n",
|
918 |
+
" img = loaded_model.cnn_model(img)\n",
|
919 |
+
"\n",
|
920 |
+
" # Pass the image features to the Transformer encoder\n",
|
921 |
+
" encoded_img = loaded_model.encoder(img, training=False)\n",
|
922 |
+
"\n",
|
923 |
+
" # Generate the caption using the Transformer decoder\n",
|
924 |
+
" decoded_caption = \"<start> \"\n",
|
925 |
+
" for i in range(max_decoded_sentence_length):\n",
|
926 |
+
" tokenized_caption = vectorization([decoded_caption])\n",
|
927 |
+
" mask = tf.math.not_equal(tokenized_caption, 0)\n",
|
928 |
+
" predictions = loaded_model.decoder(\n",
|
929 |
+
" tokenized_caption, encoded_img, training=False, mask=mask\n",
|
930 |
+
" )\n",
|
931 |
+
" sampled_token_index = np.argmax(predictions[0, i, :])\n",
|
932 |
+
" sampled_token = index_lookup[sampled_token_index]\n",
|
933 |
+
" if sampled_token == \"<end>\":\n",
|
934 |
+
" break\n",
|
935 |
+
" decoded_caption += \" \" + sampled_token\n",
|
936 |
+
"\n",
|
937 |
+
" decoded_caption = decoded_caption.replace(\"<start> \", \"\")\n",
|
938 |
+
" decoded_caption = decoded_caption.replace(\" <end>\", \"\").strip()\n",
|
939 |
+
" print(\"Predicted Caption: \", decoded_caption)\n",
|
940 |
+
"\n",
|
941 |
+
"\n",
|
942 |
+
"# Check predictions for a few samples\n",
|
943 |
+
"generate_caption()\n"
|
944 |
+
]
|
945 |
+
},
|
946 |
+
{
|
947 |
+
"cell_type": "code",
|
948 |
+
"execution_count": null,
|
949 |
+
"metadata": {
|
950 |
+
"id": "4n5iXcJwwB9-"
|
951 |
+
},
|
952 |
+
"outputs": [],
|
953 |
+
"source": []
|
954 |
+
}
|
955 |
+
],
|
956 |
+
"metadata": {
|
957 |
+
"accelerator": "GPU",
|
958 |
+
"colab": {
|
959 |
+
"gpuType": "T4",
|
960 |
+
"provenance": []
|
961 |
+
},
|
962 |
+
"kernelspec": {
|
963 |
+
"display_name": "Python 3",
|
964 |
+
"name": "python3"
|
965 |
+
},
|
966 |
+
"language_info": {
|
967 |
+
"name": "python"
|
968 |
+
}
|
969 |
+
},
|
970 |
+
"nbformat": 4,
|
971 |
+
"nbformat_minor": 0
|
972 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
keras==2.15.0
|
2 |
+
tensorflow==2.15.0
|
3 |
+
numpy
|
4 |
+
matplotlib
|
5 |
+
gradio
|
src/__init__.py
ADDED
File without changes
|
src/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (194 Bytes). View file
|
|
src/__pycache__/__init__.cpython-311.pyc
ADDED
Binary file (210 Bytes). View file
|
|
src/components/__init__.py
ADDED
File without changes
|
src/components/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (205 Bytes). View file
|
|
src/components/__pycache__/model.cpython-310.pyc
ADDED
Binary file (7.02 kB). View file
|
|
src/components/model.py
ADDED
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import keras
|
2 |
+
from keras import layers
|
3 |
+
import tensorflow as tf
|
4 |
+
|
5 |
+
IMAGE_SIZE = (299, 299)
|
6 |
+
VOCAB_SIZE = 10000
|
7 |
+
SEQ_LENGTH = 25
|
8 |
+
EMBED_DIM = 512
|
9 |
+
FF_DIM = 512
|
10 |
+
|
11 |
+
|
12 |
+
image_augmentation = keras.Sequential(
|
13 |
+
[
|
14 |
+
keras.layers.RandomFlip("horizontal"),
|
15 |
+
keras.layers.RandomRotation(0.2),
|
16 |
+
keras.layers.RandomContrast(0.3),
|
17 |
+
]
|
18 |
+
)
|
19 |
+
|
20 |
+
|
21 |
+
@keras.saving.register_keras_serializable()
|
22 |
+
def get_cnn_model():
|
23 |
+
base_model = keras.applications.efficientnet.EfficientNetB0(
|
24 |
+
input_shape=(*IMAGE_SIZE, 3),
|
25 |
+
include_top=False,
|
26 |
+
weights="imagenet"
|
27 |
+
)
|
28 |
+
base_model.trainable = False
|
29 |
+
base_model_out = base_model.output
|
30 |
+
base_model_out = layers.Reshape(
|
31 |
+
(-1, base_model_out.shape[-1]))(base_model_out)
|
32 |
+
cnn_model = keras.models.Model(base_model.input, base_model_out)
|
33 |
+
return cnn_model
|
34 |
+
|
35 |
+
|
36 |
+
@keras.saving.register_keras_serializable()
|
37 |
+
class TransformerEncoderBlock(layers.Layer):
|
38 |
+
def __init__(self, embed_dim, dense_dim, num_heads, **kwargs):
|
39 |
+
super().__init__(**kwargs)
|
40 |
+
self.embed_dim = embed_dim
|
41 |
+
self.dense_dim = dense_dim
|
42 |
+
self.num_heads = num_heads
|
43 |
+
self.attention_1 = layers.MultiHeadAttention(
|
44 |
+
num_heads=num_heads, key_dim=embed_dim, dropout=0.0
|
45 |
+
)
|
46 |
+
self.layernorm_1 = layers.LayerNormalization()
|
47 |
+
self.layernorm_2 = layers.LayerNormalization()
|
48 |
+
self.dense_1 = layers.Dense(embed_dim, activation="relu")
|
49 |
+
|
50 |
+
def get_config(self):
|
51 |
+
base_config = super().get_config()
|
52 |
+
config = {
|
53 |
+
"embed_dim": self.embed_dim,
|
54 |
+
"dense_dim": self.dense_dim,
|
55 |
+
"num_heads": self.num_heads,
|
56 |
+
}
|
57 |
+
return {**base_config, **config}
|
58 |
+
|
59 |
+
def call(self, inputs, training):
|
60 |
+
inputs = self.layernorm_1(inputs)
|
61 |
+
inputs = self.dense_1(inputs)
|
62 |
+
|
63 |
+
attention_output_1 = self.attention_1(
|
64 |
+
query=inputs,
|
65 |
+
value=inputs,
|
66 |
+
key=inputs,
|
67 |
+
training=training,
|
68 |
+
)
|
69 |
+
out_1 = self.layernorm_2(inputs + attention_output_1)
|
70 |
+
return out_1
|
71 |
+
|
72 |
+
|
73 |
+
@keras.saving.register_keras_serializable()
|
74 |
+
class PositionalEmbedding(layers.Layer):
|
75 |
+
def __init__(self, sequence_length, vocab_size, embed_dim, **kwargs):
|
76 |
+
super().__init__(**kwargs)
|
77 |
+
self.token_embeddings = layers.Embedding(
|
78 |
+
input_dim=vocab_size, output_dim=embed_dim, mask_zero=True
|
79 |
+
)
|
80 |
+
self.position_embeddings = layers.Embedding(
|
81 |
+
input_dim=sequence_length, output_dim=embed_dim
|
82 |
+
)
|
83 |
+
self.sequence_length = sequence_length
|
84 |
+
self.vocab_size = vocab_size
|
85 |
+
self.embed_dim = embed_dim
|
86 |
+
|
87 |
+
self.add = layers.Add()
|
88 |
+
|
89 |
+
def get_config(self):
|
90 |
+
base_config = super().get_config()
|
91 |
+
config = {
|
92 |
+
"sequence_length": self.sequence_length,
|
93 |
+
"vocab_size": self.vocab_size,
|
94 |
+
"embed_dim": self.embed_dim,
|
95 |
+
}
|
96 |
+
return {**base_config, **config}
|
97 |
+
|
98 |
+
def call(self, seq):
|
99 |
+
seq = self.token_embeddings(seq)
|
100 |
+
|
101 |
+
x = tf.range(tf.shape(seq)[1])
|
102 |
+
x = x[tf.newaxis, :]
|
103 |
+
x = self.position_embeddings(x)
|
104 |
+
|
105 |
+
return self.add([seq, x])
|
106 |
+
|
107 |
+
|
108 |
+
@keras.saving.register_keras_serializable()
|
109 |
+
class TransformerDecoderBlock(layers.Layer):
|
110 |
+
def __init__(self, embed_dim, ff_dim, num_heads, **kwargs):
|
111 |
+
super().__init__(**kwargs)
|
112 |
+
self.embed_dim = embed_dim
|
113 |
+
self.ff_dim = ff_dim
|
114 |
+
self.num_heads = num_heads
|
115 |
+
self.attention_1 = layers.MultiHeadAttention(
|
116 |
+
num_heads=num_heads, key_dim=embed_dim, dropout=0.1
|
117 |
+
)
|
118 |
+
self.attention_2 = layers.MultiHeadAttention(
|
119 |
+
num_heads=num_heads, key_dim=embed_dim, dropout=0.1
|
120 |
+
)
|
121 |
+
self.ffn_layer_1 = layers.Dense(ff_dim, activation="relu")
|
122 |
+
self.ffn_layer_2 = layers.Dense(embed_dim)
|
123 |
+
|
124 |
+
self.layernorm_1 = layers.LayerNormalization()
|
125 |
+
self.layernorm_2 = layers.LayerNormalization()
|
126 |
+
self.layernorm_3 = layers.LayerNormalization()
|
127 |
+
|
128 |
+
self.embedding = PositionalEmbedding(
|
129 |
+
embed_dim=EMBED_DIM,
|
130 |
+
sequence_length=SEQ_LENGTH,
|
131 |
+
vocab_size=VOCAB_SIZE,
|
132 |
+
)
|
133 |
+
self.out = layers.Dense(VOCAB_SIZE, activation="softmax")
|
134 |
+
|
135 |
+
self.dropout_1 = layers.Dropout(0.3)
|
136 |
+
self.dropout_2 = layers.Dropout(0.5)
|
137 |
+
self.supports_masking = True
|
138 |
+
|
139 |
+
def get_config(self):
|
140 |
+
base_config = super().get_config()
|
141 |
+
config = {
|
142 |
+
"embed_dim": self.embed_dim,
|
143 |
+
"ff_dim": self.ff_dim,
|
144 |
+
"num_heads": self.num_heads,
|
145 |
+
|
146 |
+
}
|
147 |
+
return {**base_config, **config}
|
148 |
+
|
149 |
+
def call(self, inputs, encoder_outputs, training, mask=None):
|
150 |
+
inputs = self.embedding(inputs)
|
151 |
+
|
152 |
+
attention_output_1 = self.attention_1(
|
153 |
+
query=inputs,
|
154 |
+
value=inputs,
|
155 |
+
key=inputs,
|
156 |
+
training=training,
|
157 |
+
use_causal_mask=True
|
158 |
+
)
|
159 |
+
out_1 = self.layernorm_1(inputs + attention_output_1)
|
160 |
+
|
161 |
+
attention_output_2 = self.attention_2(
|
162 |
+
query=out_1,
|
163 |
+
value=encoder_outputs,
|
164 |
+
key=encoder_outputs,
|
165 |
+
training=training,
|
166 |
+
)
|
167 |
+
out_2 = self.layernorm_2(out_1 + attention_output_2)
|
168 |
+
|
169 |
+
ffn_out = self.ffn_layer_1(out_2)
|
170 |
+
ffn_out = self.dropout_1(ffn_out, training=training)
|
171 |
+
ffn_out = self.ffn_layer_2(ffn_out)
|
172 |
+
|
173 |
+
ffn_out = self.layernorm_3(ffn_out + out_2, training=training)
|
174 |
+
ffn_out = self.dropout_2(ffn_out, training=training)
|
175 |
+
preds = self.out(ffn_out)
|
176 |
+
return preds
|
177 |
+
|
178 |
+
|
179 |
+
@keras.saving.register_keras_serializable()
|
180 |
+
class ImageCaptioningModel(keras.Model):
|
181 |
+
def __init__(
|
182 |
+
self,
|
183 |
+
cnn_model,
|
184 |
+
encoder,
|
185 |
+
decoder,
|
186 |
+
image_aug=None,
|
187 |
+
**kwargs
|
188 |
+
):
|
189 |
+
super().__init__(**kwargs)
|
190 |
+
self.cnn_model = cnn_model
|
191 |
+
self.encoder = encoder
|
192 |
+
self.decoder = decoder
|
193 |
+
self.image_aug = image_aug
|
194 |
+
|
195 |
+
def get_config(self):
|
196 |
+
base_config = super().get_config()
|
197 |
+
config = {
|
198 |
+
"cnn_model": self.cnn_model,
|
199 |
+
"encoder": self.encoder,
|
200 |
+
"decoder": self.decoder,
|
201 |
+
"image_aug": self.image_aug,
|
202 |
+
}
|
203 |
+
return {**base_config, **config}
|
204 |
+
|
205 |
+
@classmethod
|
206 |
+
def from_config(cls, config):
|
207 |
+
# Note that you can also use [`keras.saving.deserialize_keras_object`](/api/models/model_saving_apis/serialization_utils#deserializekerasobject-function) here
|
208 |
+
config["cnn_model"] = keras.saving.deserialize_keras_object(
|
209 |
+
config["cnn_model"])
|
210 |
+
config["encoder"] = keras.saving.deserialize_keras_object(
|
211 |
+
config["encoder"])
|
212 |
+
config["decoder"] = keras.saving.deserialize_keras_object(
|
213 |
+
config["decoder"])
|
214 |
+
config["image_aug"] = keras.saving.deserialize_keras_object(
|
215 |
+
config["image_aug"])
|
216 |
+
|
217 |
+
# Instantiate the ImageCaptioningModel with the remaining configuration
|
218 |
+
return cls(**config)
|
219 |
+
|
220 |
+
def call(self, inputs, training):
|
221 |
+
img, caption = inputs
|
222 |
+
if self.image_aug:
|
223 |
+
img = self.image_aug(img)
|
224 |
+
img_embed = self.cnn_model(img)
|
225 |
+
encoder_out = self.encoder(img_embed, training=training)
|
226 |
+
pred = self.decoder(caption, encoder_out, training=training)
|
227 |
+
return pred
|
228 |
+
|
229 |
+
@keras.saving.register_keras_serializable()
|
230 |
+
class LRSchedule(keras.optimizers.schedules.LearningRateSchedule):
|
231 |
+
def __init__(self, post_warmup_learning_rate, warmup_steps, **kwargs):
|
232 |
+
super().__init__(**kwargs)
|
233 |
+
self.post_warmup_learning_rate = post_warmup_learning_rate
|
234 |
+
self.warmup_steps = warmup_steps
|
235 |
+
|
236 |
+
def get_config(self):
|
237 |
+
config = {
|
238 |
+
"post_warmup_learning_rate": self.post_warmup_learning_rate,
|
239 |
+
"warmup_steps": self.warmup_steps,
|
240 |
+
}
|
241 |
+
return config
|
242 |
+
|
243 |
+
def __call__(self, step):
|
244 |
+
global_step = tf.cast(step, tf.float32)
|
245 |
+
warmup_steps = tf.cast(self.warmup_steps, tf.float32)
|
246 |
+
warmup_progress = global_step / warmup_steps
|
247 |
+
warmup_learning_rate = self.post_warmup_learning_rate * warmup_progress
|
248 |
+
return tf.cond(
|
249 |
+
global_step < warmup_steps,
|
250 |
+
lambda: warmup_learning_rate,
|
251 |
+
lambda: self.post_warmup_learning_rate,
|
252 |
+
)
|
src/pipeline/__init__.py
ADDED
File without changes
|
src/pipeline/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (203 Bytes). View file
|
|
src/pipeline/__pycache__/__init__.cpython-311.pyc
ADDED
Binary file (219 Bytes). View file
|
|
src/pipeline/__pycache__/make_dataset.cpython-310.pyc
ADDED
Binary file (3.29 kB). View file
|
|
src/pipeline/__pycache__/predict.cpython-310.pyc
ADDED
Binary file (2.49 kB). View file
|
|
src/pipeline/__pycache__/predict.cpython-311.pyc
ADDED
Binary file (4.57 kB). View file
|
|
src/pipeline/make_dataset.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pathlib
|
2 |
+
import keras
|
3 |
+
import tensorflow as tf
|
4 |
+
import os
|
5 |
+
import numpy as np
|
6 |
+
import re
|
7 |
+
|
8 |
+
|
9 |
+
IMAGES_PATH = "Flicker8k_Dataset"
|
10 |
+
IMAGE_SIZE = (299, 299)
|
11 |
+
VOCAB_SIZE = 10000
|
12 |
+
SEQ_LENGTH = 25
|
13 |
+
BATCH_SIZE = 64
|
14 |
+
AUTOTUNE = tf.data.AUTOTUNE
|
15 |
+
|
16 |
+
|
17 |
+
path = pathlib.Path(".")
|
18 |
+
keras.utils.get_file(
|
19 |
+
origin='https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_Dataset.zip',
|
20 |
+
cache_dir='.',
|
21 |
+
cache_subdir=path,
|
22 |
+
extract=True)
|
23 |
+
keras.utils.get_file(
|
24 |
+
origin='https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_text.zip',
|
25 |
+
cache_dir='.',
|
26 |
+
cache_subdir=path,
|
27 |
+
extract=True)
|
28 |
+
|
29 |
+
dataset = pathlib.Path(path, "Flickr8k.token.txt").read_text(
|
30 |
+
encoding='utf-8').splitlines()
|
31 |
+
|
32 |
+
dataset = [line.split('\t') for line in dataset]
|
33 |
+
|
34 |
+
dataset = [[os.path.join(IMAGES_PATH, fname.split(
|
35 |
+
'#')[0].strip()), caption] for (fname, caption) in dataset]
|
36 |
+
|
37 |
+
caption_mapping = {}
|
38 |
+
text_data = []
|
39 |
+
X_en_data = []
|
40 |
+
X_de_data = []
|
41 |
+
Y_data = []
|
42 |
+
|
43 |
+
for img_name, caption in dataset:
|
44 |
+
if img_name.endswith("jpg"):
|
45 |
+
X_de_data.append("<start> " + caption.strip().replace(".", ""))
|
46 |
+
Y_data.append(caption.strip().replace(".", "") + " <end>")
|
47 |
+
text_data.append(
|
48 |
+
"<start> " + caption.strip().replace(".", "") + " <end>")
|
49 |
+
X_en_data.append(img_name)
|
50 |
+
|
51 |
+
if img_name in caption_mapping:
|
52 |
+
caption_mapping[img_name].append(caption)
|
53 |
+
else:
|
54 |
+
caption_mapping[img_name] = [caption]
|
55 |
+
|
56 |
+
train_size = 0.8
|
57 |
+
shuffle = True
|
58 |
+
np.random.seed(42)
|
59 |
+
|
60 |
+
zipped = list(zip(X_en_data, X_de_data, Y_data))
|
61 |
+
np.random.shuffle(zipped)
|
62 |
+
X_en_data, X_de_data, Y_data = zip(*zipped)
|
63 |
+
|
64 |
+
train_size = int(len(X_en_data)*train_size)
|
65 |
+
X_train_en = list(X_en_data[:train_size])
|
66 |
+
X_train_de = list(X_de_data[:train_size])
|
67 |
+
Y_train = list(Y_data[:train_size])
|
68 |
+
X_valid_en = list(X_en_data[train_size:])
|
69 |
+
X_valid_de = list(X_de_data[train_size:])
|
70 |
+
Y_valid = list(Y_data[train_size:])
|
71 |
+
|
72 |
+
strip_chars = "!\"#$%&'()*+,-./:;=?@[\]^_`{|}~"
|
73 |
+
|
74 |
+
|
75 |
+
def custom_standardization(input_string):
|
76 |
+
lowercase = tf.strings.lower(input_string)
|
77 |
+
return tf.strings.regex_replace(lowercase, f'{re.escape(strip_chars)}', '')
|
78 |
+
|
79 |
+
|
80 |
+
vectorization = keras.layers.TextVectorization(
|
81 |
+
max_tokens=VOCAB_SIZE,
|
82 |
+
output_mode="int",
|
83 |
+
output_sequence_length=SEQ_LENGTH,
|
84 |
+
standardize=custom_standardization,
|
85 |
+
)
|
86 |
+
|
87 |
+
vectorization.adapt(text_data)
|
88 |
+
|
89 |
+
vocab = np.array(vectorization.get_vocabulary())
|
90 |
+
np.save('./artifacts/vocabulary.npy', vocab)
|
91 |
+
|
92 |
+
|
93 |
+
def decode_and_resize(img_path):
|
94 |
+
img = tf.io.read_file(img_path)
|
95 |
+
img = tf.image.decode_jpeg(img, channels=3)
|
96 |
+
img = tf.image.resize(img, IMAGE_SIZE)
|
97 |
+
img = tf.image.convert_image_dtype(img, tf.float32)
|
98 |
+
return img
|
99 |
+
|
100 |
+
|
101 |
+
def process_input(img_cap, y_captions):
|
102 |
+
img_path, x_captions = img_cap
|
103 |
+
return ((decode_and_resize(img_path), vectorization(x_captions)), vectorization(y_captions))
|
104 |
+
|
105 |
+
|
106 |
+
def make_dataset(images, x_captions, y_captions):
|
107 |
+
dataset = tf.data.Dataset.from_tensor_slices(
|
108 |
+
((images, x_captions), y_captions))
|
109 |
+
dataset = dataset.map(process_input, num_parallel_calls=AUTOTUNE)
|
110 |
+
dataset = dataset.batch(BATCH_SIZE).prefetch(AUTOTUNE)
|
111 |
+
|
112 |
+
return dataset
|
113 |
+
|
114 |
+
|
115 |
+
train_dataset = make_dataset(X_train_en, X_train_de, Y_train)
|
116 |
+
|
117 |
+
valid_dataset = make_dataset(X_valid_en, X_valid_de, Y_valid)
|
src/pipeline/predict.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import keras
|
2 |
+
import numpy as np
|
3 |
+
import tensorflow as tf
|
4 |
+
import re
|
5 |
+
from src.components.model import get_cnn_model, TransformerEncoderBlock, TransformerDecoderBlock, ImageCaptioningModel, image_augmentation, LRSchedule
|
6 |
+
|
7 |
+
SEQ_LENGTH = 25
|
8 |
+
VOCAB_SIZE = 10000
|
9 |
+
IMAGE_SIZE = (299, 299)
|
10 |
+
|
11 |
+
print("loading_model...")
|
12 |
+
loaded_model = keras.saving.load_model(
|
13 |
+
"./artifacts/caption_model.keras", compile=True)
|
14 |
+
print("model loaded...")
|
15 |
+
|
16 |
+
vocab = np.load("./artifacts/vocabulary.npy")
|
17 |
+
print("vocab loaded...")
|
18 |
+
data_txt = np.load("./artifacts/data_txt.npy").tolist()
|
19 |
+
print("vectorization data loaded...")
|
20 |
+
|
21 |
+
index_lookup = dict(zip(range(len(vocab)), vocab))
|
22 |
+
print("index lookup loaded...")
|
23 |
+
max_decoded_sentence_length = SEQ_LENGTH - 1
|
24 |
+
strip_chars = "!\"#$%&'()*+,-./:;=?@[\]^_`{|}~"
|
25 |
+
|
26 |
+
|
27 |
+
def custom_standardization(input_string):
|
28 |
+
lowercase = tf.strings.lower(input_string)
|
29 |
+
return tf.strings.regex_replace(lowercase, f'{re.escape(strip_chars)}', '')
|
30 |
+
|
31 |
+
|
32 |
+
vectorization = keras.layers.TextVectorization(
|
33 |
+
max_tokens=VOCAB_SIZE,
|
34 |
+
output_mode="int",
|
35 |
+
output_sequence_length=SEQ_LENGTH,
|
36 |
+
standardize=custom_standardization,
|
37 |
+
)
|
38 |
+
|
39 |
+
vectorization.adapt(data_txt)
|
40 |
+
print("vectorization adapted...")
|
41 |
+
|
42 |
+
|
43 |
+
def decode_and_resize(image):
|
44 |
+
if isinstance(image, str):
|
45 |
+
img = tf.io.read_file(image)
|
46 |
+
img = tf.image.decode_jpeg(img, channels=3)
|
47 |
+
elif isinstance(image, np.ndarray):
|
48 |
+
img = tf.constant(image)
|
49 |
+
img = tf.image.resize(img, IMAGE_SIZE)
|
50 |
+
img = tf.image.convert_image_dtype(img, tf.float32)
|
51 |
+
return img
|
52 |
+
|
53 |
+
|
54 |
+
def generate_caption(image):
|
55 |
+
|
56 |
+
sample_img = decode_and_resize(image)
|
57 |
+
|
58 |
+
# Pass the image to the CNN
|
59 |
+
img = tf.expand_dims(sample_img, 0)
|
60 |
+
img = loaded_model.cnn_model(img)
|
61 |
+
|
62 |
+
# Pass the image features to the Transformer encoder
|
63 |
+
encoded_img = loaded_model.encoder(img, training=False)
|
64 |
+
|
65 |
+
# Generate the caption using the Transformer decoder
|
66 |
+
decoded_caption = "<start> "
|
67 |
+
for i in range(max_decoded_sentence_length):
|
68 |
+
tokenized_caption = vectorization([decoded_caption])
|
69 |
+
mask = tf.math.not_equal(tokenized_caption, 0)
|
70 |
+
predictions = loaded_model.decoder(
|
71 |
+
tokenized_caption, encoded_img, training=False, mask=mask
|
72 |
+
)
|
73 |
+
sampled_token_index = np.argmax(predictions[0, i, :])
|
74 |
+
sampled_token = index_lookup[sampled_token_index]
|
75 |
+
if sampled_token == "<end>":
|
76 |
+
break
|
77 |
+
decoded_caption += " " + sampled_token
|
78 |
+
|
79 |
+
decoded_caption = decoded_caption.replace("<start> ", "")
|
80 |
+
decoded_caption = decoded_caption.replace(" <end>", "").strip()
|
81 |
+
return decoded_caption
|
src/pipeline/training.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import keras
|
2 |
+
import tensorflow as tf
|
3 |
+
from make_dataset import train_dataset, valid_dataset
|
4 |
+
from src.components.model import get_cnn_model, TransformerEncoderBlock, TransformerDecoderBlock, ImageCaptioningModel, image_augmentation, LRSchedule
|
5 |
+
|
6 |
+
|
7 |
+
EMBED_DIM = 512
|
8 |
+
FF_DIM = 512
|
9 |
+
EPOCHS = 30
|
10 |
+
|
11 |
+
cnn_model = get_cnn_model()
|
12 |
+
encoder = TransformerEncoderBlock(
|
13 |
+
embed_dim=EMBED_DIM, dense_dim=FF_DIM, num_heads=1)
|
14 |
+
decoder = TransformerDecoderBlock(
|
15 |
+
embed_dim=EMBED_DIM, ff_dim=FF_DIM, num_heads=2)
|
16 |
+
caption_model = ImageCaptioningModel(
|
17 |
+
cnn_model=cnn_model,
|
18 |
+
encoder=encoder,
|
19 |
+
decoder=decoder,
|
20 |
+
image_aug=image_augmentation,
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
early_stopping = keras.callbacks.EarlyStopping(
|
25 |
+
patience=3, restore_best_weights=True)
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
|
30 |
+
num_train_steps = len(train_dataset) * EPOCHS
|
31 |
+
num_warmup_steps = num_train_steps // 15
|
32 |
+
lr_schedule = LRSchedule(post_warmup_learning_rate=1e-4,
|
33 |
+
warmup_steps=num_warmup_steps)
|
34 |
+
|
35 |
+
caption_model.compile(optimizer=keras.optimizers.Adam(lr_schedule), loss='sparse_categorical_crossentropy',
|
36 |
+
metrics=['accuracy'])
|
37 |
+
|
38 |
+
caption_model.fit(
|
39 |
+
train_dataset,
|
40 |
+
epochs=EPOCHS,
|
41 |
+
validation_data=valid_dataset,
|
42 |
+
callbacks=[early_stopping],
|
43 |
+
)
|
44 |
+
|
45 |
+
caption_model.save("./artifacts/caption_model1.keras")
|