"
361 | ]
362 | },
363 | "metadata": {
364 | "tags": [],
365 | "needs_background": "light"
366 | }
367 | }
368 | ]
369 | }
370 | ]
371 | }
--------------------------------------------------------------------------------
/PAIGCP_Translation.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "PAIGCP_Translation.ipynb",
7 | "provenance": [],
8 | "collapsed_sections": [],
9 | "authorship_tag": "ABX9TyOon4bJkMZBRt5LS/ijtFKA",
10 | "include_colab_link": true
11 | },
12 | "kernelspec": {
13 | "name": "python3",
14 | "display_name": "Python 3"
15 | },
16 | "accelerator": "GPU"
17 | },
18 | "cells": [
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {
22 | "id": "view-in-github",
23 | "colab_type": "text"
24 | },
25 | "source": [
26 | "
"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "metadata": {
32 | "id": "rhUrDc_zOA-H",
33 | "colab_type": "code",
34 | "colab": {}
35 | },
36 | "source": [
37 | "import tensorflow as tf\n",
38 | "\n",
39 | "import numpy as np\n",
40 | "import os\n",
41 | "import time\n"
42 | ],
43 | "execution_count": null,
44 | "outputs": []
45 | },
46 | {
47 | "cell_type": "code",
48 | "metadata": {
49 | "id": "oG0JNbJsRfwT",
50 | "colab_type": "code",
51 | "colab": {
52 | "base_uri": "https://localhost:8080/",
53 | "height": 67
54 | },
55 | "outputId": "090686f1-6f70-4c1f-d1df-c7848cdc2557"
56 | },
57 | "source": [
58 | "path_to_zip = tf.keras.utils.get_file(\n",
59 | " 'spa-eng.zip', origin='http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip',\n",
60 | " extract=True)\n",
61 | "\n",
62 | "path_to_file = os.path.dirname(path_to_zip)+\"/spa-eng/spa.txt\"\n",
63 | "path_to_file"
64 | ],
65 | "execution_count": null,
66 | "outputs": [
67 | {
68 | "output_type": "stream",
69 | "text": [
70 | "Downloading data from http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip\n",
71 | "2646016/2638744 [==============================] - 0s 0us/step\n"
72 | ],
73 | "name": "stdout"
74 | },
75 | {
76 | "output_type": "execute_result",
77 | "data": {
78 | "text/plain": [
79 | "'/root/.keras/datasets/spa-eng/spa.txt'"
80 | ]
81 | },
82 | "metadata": {
83 | "tags": []
84 | },
85 | "execution_count": 2
86 | }
87 | ]
88 | },
89 | {
90 | "cell_type": "code",
91 | "metadata": {
92 | "id": "EswXJREBNYY-",
93 | "colab_type": "code",
94 | "colab": {
95 | "base_uri": "https://localhost:8080/",
96 | "height": 185
97 | },
98 | "outputId": "bdd86aaf-37de-4fee-a859-321609de9e7c"
99 | },
100 | "source": [
101 | "# Vectorize the data.\n",
102 | "input_texts = []\n",
103 | "target_texts = []\n",
104 | "input_characters = set()\n",
105 | "target_characters = set()\n",
106 | "with open(path_to_file, 'r', encoding='utf-8') as f:\n",
107 | " lines = f.read().split('\\n')\n",
108 | "\n",
109 | "lines[:10]"
110 | ],
111 | "execution_count": null,
112 | "outputs": [
113 | {
114 | "output_type": "execute_result",
115 | "data": {
116 | "text/plain": [
117 | "['Go.\\tVe.',\n",
118 | " 'Go.\\tVete.',\n",
119 | " 'Go.\\tVaya.',\n",
120 | " 'Go.\\tVáyase.',\n",
121 | " 'Hi.\\tHola.',\n",
122 | " 'Run!\\t¡Corre!',\n",
123 | " 'Run.\\tCorred.',\n",
124 | " 'Who?\\t¿Quién?',\n",
125 | " 'Fire!\\t¡Fuego!',\n",
126 | " 'Fire!\\t¡Incendio!']"
127 | ]
128 | },
129 | "metadata": {
130 | "tags": []
131 | },
132 | "execution_count": 3
133 | }
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "metadata": {
139 | "id": "vFmWesFKR6pr",
140 | "colab_type": "code",
141 | "colab": {}
142 | },
143 | "source": [
144 | "num_samples = 1000\n",
145 | "for line in lines[: min(num_samples, len(lines) - 1)]:\n",
146 | " input_text, target_text = line.split('\\t')\n",
147 | " # We use \"tab\" as the \"start sequence\" character\n",
148 | " # for the targets, and \"\\n\" as \"end sequence\" character.\n",
149 | " target_text = '\\t' + target_text + '\\n'\n",
150 | " input_texts.append(input_text)\n",
151 | " target_texts.append(target_text)\n",
152 | " for char in input_text:\n",
153 | " if char not in input_characters:\n",
154 | " input_characters.add(char)\n",
155 | " for char in target_text:\n",
156 | " if char not in target_characters:\n",
157 | " target_characters.add(char)"
158 | ],
159 | "execution_count": null,
160 | "outputs": []
161 | },
162 | {
163 | "cell_type": "code",
164 | "metadata": {
165 | "id": "FeeqI8GCSO8e",
166 | "colab_type": "code",
167 | "colab": {
168 | "base_uri": "https://localhost:8080/",
169 | "height": 50
170 | },
171 | "outputId": "51f9dcb8-8f6d-41e7-81cc-0d5feca621fe"
172 | },
173 | "source": [
174 | "input_characters = sorted(list(input_characters))\n",
175 | "num_encoder_tokens = len(input_characters)\n",
176 | "num_encoder_tokens, \",\".join(input_characters)"
177 | ],
178 | "execution_count": null,
179 | "outputs": [
180 | {
181 | "output_type": "execute_result",
182 | "data": {
183 | "text/plain": [
184 | "(61,\n",
185 | " \" ,!,',,,.,0,1,3,8,9,:,?,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,R,S,T,U,V,W,Y,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z\")"
186 | ]
187 | },
188 | "metadata": {
189 | "tags": []
190 | },
191 | "execution_count": 5
192 | }
193 | ]
194 | },
195 | {
196 | "cell_type": "code",
197 | "metadata": {
198 | "id": "JKsMQLeaSajS",
199 | "colab_type": "code",
200 | "colab": {
201 | "base_uri": "https://localhost:8080/",
202 | "height": 50
203 | },
204 | "outputId": "11922cd1-a0ca-452c-9ac7-7e40ed604d42"
205 | },
206 | "source": [
207 | "target_characters = sorted(list(target_characters))\n",
208 | "num_decoder_tokens = len(target_characters)\n",
209 | "num_decoder_tokens, \",\".join(target_characters)"
210 | ],
211 | "execution_count": null,
212 | "outputs": [
213 | {
214 | "output_type": "execute_result",
215 | "data": {
216 | "text/plain": [
217 | "(70,\n",
218 | " '\\t,\\n, ,!,,,.,0,3,8,:,?,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,Y,a,b,c,d,e,f,g,h,i,j,l,m,n,o,p,q,r,s,t,u,v,x,y,z,¡,¿,Á,É,Ó,Ú,á,é,í,ñ,ó,ú,ü')"
219 | ]
220 | },
221 | "metadata": {
222 | "tags": []
223 | },
224 | "execution_count": 6
225 | }
226 | ]
227 | },
228 | {
229 | "cell_type": "code",
230 | "metadata": {
231 | "id": "zXfuLaoVUD2b",
232 | "colab_type": "code",
233 | "colab": {
234 | "base_uri": "https://localhost:8080/",
235 | "height": 34
236 | },
237 | "outputId": "746f953a-c606-4ff2-82a0-e6369fe23a40"
238 | },
239 | "source": [
240 | "max_encoder_seq_length = max([len(txt) for txt in input_texts])\n",
241 | "print('Max sequence length for inputs:', max_encoder_seq_length)"
242 | ],
243 | "execution_count": null,
244 | "outputs": [
245 | {
246 | "output_type": "stream",
247 | "text": [
248 | "Max sequence length for inputs: 11\n"
249 | ],
250 | "name": "stdout"
251 | }
252 | ]
253 | },
254 | {
255 | "cell_type": "code",
256 | "metadata": {
257 | "id": "GwdHoAo41sx1",
258 | "colab_type": "code",
259 | "colab": {
260 | "base_uri": "https://localhost:8080/",
261 | "height": 34
262 | },
263 | "outputId": "49084ed2-5d75-456f-c39b-1085398217a2"
264 | },
265 | "source": [
266 | "max_decoder_seq_length = max([len(txt) for txt in target_texts])\n",
267 | "print('Max sequence length for outputs:', max_decoder_seq_length)"
268 | ],
269 | "execution_count": null,
270 | "outputs": [
271 | {
272 | "output_type": "stream",
273 | "text": [
274 | "Max sequence length for outputs: 31\n"
275 | ],
276 | "name": "stdout"
277 | }
278 | ]
279 | },
280 | {
281 | "cell_type": "code",
282 | "metadata": {
283 | "id": "AHc1qMwjVCQR",
284 | "colab_type": "code",
285 | "colab": {}
286 | },
287 | "source": [
288 | "input_token_index = dict(\n",
289 | " [(char, i) for i, char in enumerate(input_characters)])\n",
290 | "target_token_index = dict(\n",
291 | " [(char, i) for i, char in enumerate(target_characters)])\n",
292 | "\n",
293 | "encoder_input_data = np.zeros(\n",
294 | " (len(input_texts), max_encoder_seq_length, num_encoder_tokens),\n",
295 | " dtype='float32')\n",
296 | "decoder_input_data = np.zeros(\n",
297 | " (len(input_texts), max_decoder_seq_length, num_decoder_tokens),\n",
298 | " dtype='float32')\n",
299 | "decoder_target_data = np.zeros(\n",
300 | " (len(input_texts), max_decoder_seq_length, num_decoder_tokens),\n",
301 | " dtype='float32')"
302 | ],
303 | "execution_count": null,
304 | "outputs": []
305 | },
306 | {
307 | "cell_type": "code",
308 | "metadata": {
309 | "id": "4UgjBMmhVZU6",
310 | "colab_type": "code",
311 | "colab": {}
312 | },
313 | "source": [
314 | "for i, (input_text, target_text) in enumerate(zip(input_texts, target_texts)):\n",
315 | " for t, char in enumerate(input_text):\n",
316 | " encoder_input_data[i, t, input_token_index[char]] = 1.\n",
317 | " encoder_input_data[i, t + 1:, input_token_index[' ']] = 1.\n",
318 | " for t, char in enumerate(target_text):\n",
319 | " # decoder_target_data is ahead of decoder_input_data by one timestep\n",
320 | " decoder_input_data[i, t, target_token_index[char]] = 1.\n",
321 | " if t > 0:\n",
322 | " # decoder_target_data will be ahead by one timestep\n",
323 | " # and will not include the start character.\n",
324 | " decoder_target_data[i, t - 1, target_token_index[char]] = 1.\n",
325 | " decoder_input_data[i, t + 1:, target_token_index[' ']] = 1.\n",
326 | " decoder_target_data[i, t:, target_token_index[' ']] = 1."
327 | ],
328 | "execution_count": null,
329 | "outputs": []
330 | },
331 | {
332 | "cell_type": "code",
333 | "metadata": {
334 | "id": "vNJTVSHO3NQF",
335 | "colab_type": "code",
336 | "colab": {}
337 | },
338 | "source": [
339 | "from tensorflow.keras.models import Model\n",
340 | "from tensorflow.keras.layers import Input, LSTM, Dense, Embedding, Reshape\n",
341 | "\n",
342 | "batch_size = 64 # Batch size for training.\n",
343 | "epochs = 100 # Number of epochs to train for.\n",
344 | "latent_dim = 64 # Latent dimensionality of the encoding space.\n",
345 | "\n",
346 | "# Define an input sequence and process it.\n",
347 | "encoder_inputs = Input(shape=(None, num_encoder_tokens))\n",
348 | "#encoder_embedded = Embedding(input_dim=num_encoder_tokens, output_dim=64)(encoder_inputs)\n",
349 | "#encoder_reshape = Reshape((-1, 64))(encoder_embedded)\n",
350 | "encoder = LSTM(latent_dim, return_state=True)\n",
351 | "encoder_outputs, state_h, state_c = encoder(encoder_inputs)\n",
352 | "# We discard `encoder_outputs` and only keep the states.\n",
353 | "encoder_states = [state_h, state_c]"
354 | ],
355 | "execution_count": null,
356 | "outputs": []
357 | },
358 | {
359 | "cell_type": "code",
360 | "metadata": {
361 | "id": "Za7_kDtc4Gax",
362 | "colab_type": "code",
363 | "colab": {}
364 | },
365 | "source": [
366 | "# Set up the decoder, using `encoder_states` as initial state.\n",
367 | "decoder_inputs = Input(shape=(None, num_decoder_tokens))\n",
368 | "# We set up our decoder to return full output sequences,\n",
369 | "# and to return internal states as well. We don't use the\n",
370 | "# return states in the training model, but we will use them in inference.\n",
371 | "decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)\n",
372 | "decoder_outputs, _, _ = decoder_lstm(decoder_inputs,\n",
373 | " initial_state=encoder_states)\n",
374 | "decoder_dense = Dense(num_decoder_tokens, activation='softmax')\n",
375 | "decoder_outputs = decoder_dense(decoder_outputs)"
376 | ],
377 | "execution_count": null,
378 | "outputs": []
379 | },
380 | {
381 | "cell_type": "code",
382 | "metadata": {
383 | "id": "BkuLHwekRO2h",
384 | "colab_type": "code",
385 | "colab": {
386 | "base_uri": "https://localhost:8080/",
387 | "height": 34
388 | },
389 | "outputId": "e4ceab26-609c-4286-c015-e6d03733e8fa"
390 | },
391 | "source": [
392 | "batch_size = 64\n",
393 | "epochs = 100\n",
394 | "encoder_input_data.shape,decoder_input_data.shape"
395 | ],
396 | "execution_count": null,
397 | "outputs": [
398 | {
399 | "output_type": "execute_result",
400 | "data": {
401 | "text/plain": [
402 | "((1000, 11, 61), (1000, 31, 70))"
403 | ]
404 | },
405 | "metadata": {
406 | "tags": []
407 | },
408 | "execution_count": 76
409 | }
410 | ]
411 | },
412 | {
413 | "cell_type": "code",
414 | "metadata": {
415 | "id": "u-iU3cxY4qiQ",
416 | "colab_type": "code",
417 | "colab": {
418 | "base_uri": "https://localhost:8080/",
419 | "height": 1000
420 | },
421 | "outputId": "2e7dabe1-b899-4951-eba5-3b402f8f54f9"
422 | },
423 | "source": [
424 | "# Define the model that will turn\n",
425 | "# `encoder_input_data` & `decoder_input_data` into `decoder_target_data`\n",
426 | "model = Model([encoder_inputs, decoder_inputs], decoder_outputs)\n",
427 | "\n",
428 | "# Run training\n",
429 | "model.compile(optimizer='rmsprop', loss='categorical_crossentropy',\n",
430 | " metrics=['accuracy'])\n",
431 | "model.fit([encoder_input_data, decoder_input_data], decoder_target_data,\n",
432 | " batch_size=batch_size,\n",
433 | " epochs=epochs,\n",
434 | " validation_split=0.2)\n",
435 | "# Save model\n",
436 | "model.save('s2s.h5')"
437 | ],
438 | "execution_count": null,
439 | "outputs": [
440 | {
441 | "output_type": "stream",
442 | "text": [
443 | "Epoch 1/100\n",
444 | "13/13 [==============================] - 1s 76ms/step - loss: 3.3758 - accuracy: 0.5017 - val_loss: 2.1734 - val_accuracy: 0.5777\n",
445 | "Epoch 2/100\n",
446 | "13/13 [==============================] - 0s 19ms/step - loss: 1.7953 - accuracy: 0.6275 - val_loss: 1.9087 - val_accuracy: 0.5744\n",
447 | "Epoch 3/100\n",
448 | "13/13 [==============================] - 0s 19ms/step - loss: 1.6027 - accuracy: 0.6265 - val_loss: 1.7623 - val_accuracy: 0.5731\n",
449 | "Epoch 4/100\n",
450 | "13/13 [==============================] - 0s 20ms/step - loss: 1.5276 - accuracy: 0.6279 - val_loss: 1.7184 - val_accuracy: 0.5808\n",
451 | "Epoch 5/100\n",
452 | "13/13 [==============================] - 0s 19ms/step - loss: 1.4907 - accuracy: 0.6279 - val_loss: 1.6831 - val_accuracy: 0.5787\n",
453 | "Epoch 6/100\n",
454 | "13/13 [==============================] - 0s 19ms/step - loss: 1.4550 - accuracy: 0.6304 - val_loss: 1.7033 - val_accuracy: 0.5885\n",
455 | "Epoch 7/100\n",
456 | "13/13 [==============================] - 0s 19ms/step - loss: 1.4257 - accuracy: 0.6348 - val_loss: 1.6383 - val_accuracy: 0.5852\n",
457 | "Epoch 8/100\n",
458 | "13/13 [==============================] - 0s 20ms/step - loss: 1.4009 - accuracy: 0.6354 - val_loss: 1.6056 - val_accuracy: 0.5852\n",
459 | "Epoch 9/100\n",
460 | "13/13 [==============================] - 0s 19ms/step - loss: 1.3657 - accuracy: 0.6364 - val_loss: 1.5636 - val_accuracy: 0.5818\n",
461 | "Epoch 10/100\n",
462 | "13/13 [==============================] - 0s 19ms/step - loss: 1.3541 - accuracy: 0.6381 - val_loss: 1.5429 - val_accuracy: 0.5874\n",
463 | "Epoch 11/100\n",
464 | "13/13 [==============================] - 0s 20ms/step - loss: 1.3300 - accuracy: 0.6407 - val_loss: 1.5173 - val_accuracy: 0.5894\n",
465 | "Epoch 12/100\n",
466 | "13/13 [==============================] - 0s 20ms/step - loss: 1.3094 - accuracy: 0.6447 - val_loss: 1.5152 - val_accuracy: 0.5902\n",
467 | "Epoch 13/100\n",
468 | "13/13 [==============================] - 0s 22ms/step - loss: 1.2850 - accuracy: 0.6465 - val_loss: 1.5090 - val_accuracy: 0.5900\n",
469 | "Epoch 14/100\n",
470 | "13/13 [==============================] - 0s 19ms/step - loss: 1.2668 - accuracy: 0.6517 - val_loss: 1.4856 - val_accuracy: 0.5927\n",
471 | "Epoch 15/100\n",
472 | "13/13 [==============================] - 0s 19ms/step - loss: 1.2545 - accuracy: 0.6569 - val_loss: 1.4439 - val_accuracy: 0.5956\n",
473 | "Epoch 16/100\n",
474 | "13/13 [==============================] - 0s 19ms/step - loss: 1.2277 - accuracy: 0.6612 - val_loss: 1.4186 - val_accuracy: 0.6074\n",
475 | "Epoch 17/100\n",
476 | "13/13 [==============================] - 0s 20ms/step - loss: 1.2127 - accuracy: 0.6692 - val_loss: 1.4098 - val_accuracy: 0.6161\n",
477 | "Epoch 18/100\n",
478 | "13/13 [==============================] - 0s 19ms/step - loss: 1.2023 - accuracy: 0.6785 - val_loss: 1.3878 - val_accuracy: 0.6355\n",
479 | "Epoch 19/100\n",
480 | "13/13 [==============================] - 0s 20ms/step - loss: 1.1801 - accuracy: 0.6871 - val_loss: 1.3800 - val_accuracy: 0.6265\n",
481 | "Epoch 20/100\n",
482 | "13/13 [==============================] - 0s 19ms/step - loss: 1.1642 - accuracy: 0.6931 - val_loss: 1.4433 - val_accuracy: 0.6026\n",
483 | "Epoch 21/100\n",
484 | "13/13 [==============================] - 0s 19ms/step - loss: 1.1519 - accuracy: 0.6966 - val_loss: 1.3476 - val_accuracy: 0.6387\n",
485 | "Epoch 22/100\n",
486 | "13/13 [==============================] - 0s 20ms/step - loss: 1.1384 - accuracy: 0.7000 - val_loss: 1.3278 - val_accuracy: 0.6463\n",
487 | "Epoch 23/100\n",
488 | "13/13 [==============================] - 0s 19ms/step - loss: 1.1191 - accuracy: 0.7078 - val_loss: 1.3109 - val_accuracy: 0.6473\n",
489 | "Epoch 24/100\n",
490 | "13/13 [==============================] - 0s 20ms/step - loss: 1.1111 - accuracy: 0.7101 - val_loss: 1.3061 - val_accuracy: 0.6489\n",
491 | "Epoch 25/100\n",
492 | "13/13 [==============================] - 0s 19ms/step - loss: 1.0920 - accuracy: 0.7144 - val_loss: 1.3037 - val_accuracy: 0.6453\n",
493 | "Epoch 26/100\n",
494 | "13/13 [==============================] - 0s 19ms/step - loss: 1.0803 - accuracy: 0.7178 - val_loss: 1.2765 - val_accuracy: 0.6565\n",
495 | "Epoch 27/100\n",
496 | "13/13 [==============================] - 0s 20ms/step - loss: 1.0676 - accuracy: 0.7210 - val_loss: 1.2781 - val_accuracy: 0.6492\n",
497 | "Epoch 28/100\n",
498 | "13/13 [==============================] - 0s 20ms/step - loss: 1.0515 - accuracy: 0.7256 - val_loss: 1.2460 - val_accuracy: 0.6752\n",
499 | "Epoch 29/100\n",
500 | "13/13 [==============================] - 0s 19ms/step - loss: 1.0453 - accuracy: 0.7257 - val_loss: 1.2347 - val_accuracy: 0.6669\n",
501 | "Epoch 30/100\n",
502 | "13/13 [==============================] - 0s 20ms/step - loss: 1.0265 - accuracy: 0.7293 - val_loss: 1.2283 - val_accuracy: 0.6694\n",
503 | "Epoch 31/100\n",
504 | "13/13 [==============================] - 0s 19ms/step - loss: 1.0154 - accuracy: 0.7310 - val_loss: 1.2207 - val_accuracy: 0.6703\n",
505 | "Epoch 32/100\n",
506 | "13/13 [==============================] - 0s 19ms/step - loss: 1.0018 - accuracy: 0.7335 - val_loss: 1.2072 - val_accuracy: 0.6668\n",
507 | "Epoch 33/100\n",
508 | "13/13 [==============================] - 0s 19ms/step - loss: 0.9917 - accuracy: 0.7342 - val_loss: 1.1838 - val_accuracy: 0.6798\n",
509 | "Epoch 34/100\n",
510 | "13/13 [==============================] - 0s 19ms/step - loss: 0.9774 - accuracy: 0.7361 - val_loss: 1.1854 - val_accuracy: 0.6868\n",
511 | "Epoch 35/100\n",
512 | "13/13 [==============================] - 0s 19ms/step - loss: 0.9643 - accuracy: 0.7400 - val_loss: 1.1625 - val_accuracy: 0.6831\n",
513 | "Epoch 36/100\n",
514 | "13/13 [==============================] - 0s 19ms/step - loss: 0.9541 - accuracy: 0.7401 - val_loss: 1.1549 - val_accuracy: 0.6840\n",
515 | "Epoch 37/100\n",
516 | "13/13 [==============================] - 0s 19ms/step - loss: 0.9413 - accuracy: 0.7429 - val_loss: 1.1386 - val_accuracy: 0.6834\n",
517 | "Epoch 38/100\n",
518 | "13/13 [==============================] - 0s 19ms/step - loss: 0.9296 - accuracy: 0.7438 - val_loss: 1.1314 - val_accuracy: 0.6853\n",
519 | "Epoch 39/100\n",
520 | "13/13 [==============================] - 0s 20ms/step - loss: 0.9170 - accuracy: 0.7471 - val_loss: 1.1208 - val_accuracy: 0.6916\n",
521 | "Epoch 40/100\n",
522 | "13/13 [==============================] - 0s 20ms/step - loss: 0.9081 - accuracy: 0.7498 - val_loss: 1.1234 - val_accuracy: 0.6781\n",
523 | "Epoch 41/100\n",
524 | "13/13 [==============================] - 0s 20ms/step - loss: 0.8963 - accuracy: 0.7528 - val_loss: 1.1042 - val_accuracy: 0.6890\n",
525 | "Epoch 42/100\n",
526 | "13/13 [==============================] - 0s 19ms/step - loss: 0.8853 - accuracy: 0.7545 - val_loss: 1.0868 - val_accuracy: 0.6902\n",
527 | "Epoch 43/100\n",
528 | "13/13 [==============================] - 0s 19ms/step - loss: 0.8759 - accuracy: 0.7552 - val_loss: 1.0849 - val_accuracy: 0.6877\n",
529 | "Epoch 44/100\n",
530 | "13/13 [==============================] - 0s 19ms/step - loss: 0.8669 - accuracy: 0.7563 - val_loss: 1.0749 - val_accuracy: 0.6848\n",
531 | "Epoch 45/100\n",
532 | "13/13 [==============================] - 0s 20ms/step - loss: 0.8584 - accuracy: 0.7600 - val_loss: 1.0624 - val_accuracy: 0.6918\n",
533 | "Epoch 46/100\n",
534 | "13/13 [==============================] - 0s 20ms/step - loss: 0.8450 - accuracy: 0.7616 - val_loss: 1.0523 - val_accuracy: 0.6911\n",
535 | "Epoch 47/100\n",
536 | "13/13 [==============================] - 0s 19ms/step - loss: 0.8404 - accuracy: 0.7620 - val_loss: 1.0539 - val_accuracy: 0.6927\n",
537 | "Epoch 48/100\n",
538 | "13/13 [==============================] - 0s 20ms/step - loss: 0.8294 - accuracy: 0.7647 - val_loss: 1.0419 - val_accuracy: 0.6927\n",
539 | "Epoch 49/100\n",
540 | "13/13 [==============================] - 0s 20ms/step - loss: 0.8254 - accuracy: 0.7623 - val_loss: 1.0392 - val_accuracy: 0.6990\n",
541 | "Epoch 50/100\n",
542 | "13/13 [==============================] - 0s 20ms/step - loss: 0.8145 - accuracy: 0.7666 - val_loss: 1.0302 - val_accuracy: 0.6989\n",
543 | "Epoch 51/100\n",
544 | "13/13 [==============================] - 0s 20ms/step - loss: 0.8102 - accuracy: 0.7665 - val_loss: 1.0235 - val_accuracy: 0.6977\n",
545 | "Epoch 52/100\n",
546 | "13/13 [==============================] - 0s 19ms/step - loss: 0.8019 - accuracy: 0.7703 - val_loss: 1.0170 - val_accuracy: 0.7010\n",
547 | "Epoch 53/100\n",
548 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7937 - accuracy: 0.7730 - val_loss: 1.0248 - val_accuracy: 0.6944\n",
549 | "Epoch 54/100\n",
550 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7881 - accuracy: 0.7750 - val_loss: 1.0192 - val_accuracy: 0.6953\n",
551 | "Epoch 55/100\n",
552 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7839 - accuracy: 0.7730 - val_loss: 0.9980 - val_accuracy: 0.7066\n",
553 | "Epoch 56/100\n",
554 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7752 - accuracy: 0.7784 - val_loss: 1.0022 - val_accuracy: 0.7092\n",
555 | "Epoch 57/100\n",
556 | "13/13 [==============================] - 0s 21ms/step - loss: 0.7712 - accuracy: 0.7788 - val_loss: 0.9954 - val_accuracy: 0.7037\n",
557 | "Epoch 58/100\n",
558 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7624 - accuracy: 0.7803 - val_loss: 0.9922 - val_accuracy: 0.7098\n",
559 | "Epoch 59/100\n",
560 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7579 - accuracy: 0.7817 - val_loss: 1.0125 - val_accuracy: 0.6976\n",
561 | "Epoch 60/100\n",
562 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7543 - accuracy: 0.7820 - val_loss: 0.9926 - val_accuracy: 0.7069\n",
563 | "Epoch 61/100\n",
564 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7481 - accuracy: 0.7839 - val_loss: 0.9898 - val_accuracy: 0.7121\n",
565 | "Epoch 62/100\n",
566 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7456 - accuracy: 0.7844 - val_loss: 0.9801 - val_accuracy: 0.7089\n",
567 | "Epoch 63/100\n",
568 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7366 - accuracy: 0.7869 - val_loss: 0.9874 - val_accuracy: 0.7119\n",
569 | "Epoch 64/100\n",
570 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7323 - accuracy: 0.7882 - val_loss: 0.9717 - val_accuracy: 0.7110\n",
571 | "Epoch 65/100\n",
572 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7276 - accuracy: 0.7895 - val_loss: 0.9655 - val_accuracy: 0.7148\n",
573 | "Epoch 66/100\n",
574 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7220 - accuracy: 0.7906 - val_loss: 0.9847 - val_accuracy: 0.7079\n",
575 | "Epoch 67/100\n",
576 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7175 - accuracy: 0.7924 - val_loss: 0.9762 - val_accuracy: 0.7134\n",
577 | "Epoch 68/100\n",
578 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7146 - accuracy: 0.7911 - val_loss: 0.9653 - val_accuracy: 0.7134\n",
579 | "Epoch 69/100\n",
580 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7086 - accuracy: 0.7933 - val_loss: 0.9729 - val_accuracy: 0.7118\n",
581 | "Epoch 70/100\n",
582 | "13/13 [==============================] - 0s 19ms/step - loss: 0.7077 - accuracy: 0.7929 - val_loss: 0.9548 - val_accuracy: 0.7165\n",
583 | "Epoch 71/100\n",
584 | "13/13 [==============================] - 0s 20ms/step - loss: 0.7013 - accuracy: 0.7953 - val_loss: 0.9525 - val_accuracy: 0.7192\n",
585 | "Epoch 72/100\n",
586 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6964 - accuracy: 0.7962 - val_loss: 0.9481 - val_accuracy: 0.7206\n",
587 | "Epoch 73/100\n",
588 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6940 - accuracy: 0.7962 - val_loss: 0.9493 - val_accuracy: 0.7158\n",
589 | "Epoch 74/100\n",
590 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6893 - accuracy: 0.7981 - val_loss: 0.9526 - val_accuracy: 0.7131\n",
591 | "Epoch 75/100\n",
592 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6846 - accuracy: 0.7977 - val_loss: 0.9522 - val_accuracy: 0.7169\n",
593 | "Epoch 76/100\n",
594 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6810 - accuracy: 0.7996 - val_loss: 0.9414 - val_accuracy: 0.7261\n",
595 | "Epoch 77/100\n",
596 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6782 - accuracy: 0.8002 - val_loss: 0.9425 - val_accuracy: 0.7198\n",
597 | "Epoch 78/100\n",
598 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6724 - accuracy: 0.8013 - val_loss: 0.9387 - val_accuracy: 0.7218\n",
599 | "Epoch 79/100\n",
600 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6714 - accuracy: 0.8014 - val_loss: 0.9341 - val_accuracy: 0.7219\n",
601 | "Epoch 80/100\n",
602 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6648 - accuracy: 0.8038 - val_loss: 0.9447 - val_accuracy: 0.7189\n",
603 | "Epoch 81/100\n",
604 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6637 - accuracy: 0.8056 - val_loss: 0.9519 - val_accuracy: 0.7156\n",
605 | "Epoch 82/100\n",
606 | "13/13 [==============================] - 0s 21ms/step - loss: 0.6585 - accuracy: 0.8044 - val_loss: 0.9419 - val_accuracy: 0.7194\n",
607 | "Epoch 83/100\n",
608 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6546 - accuracy: 0.8057 - val_loss: 0.9433 - val_accuracy: 0.7173\n",
609 | "Epoch 84/100\n",
610 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6522 - accuracy: 0.8080 - val_loss: 0.9382 - val_accuracy: 0.7203\n",
611 | "Epoch 85/100\n",
612 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6474 - accuracy: 0.8094 - val_loss: 0.9362 - val_accuracy: 0.7219\n",
613 | "Epoch 86/100\n",
614 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6433 - accuracy: 0.8104 - val_loss: 0.9290 - val_accuracy: 0.7260\n",
615 | "Epoch 87/100\n",
616 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6397 - accuracy: 0.8106 - val_loss: 0.9324 - val_accuracy: 0.7268\n",
617 | "Epoch 88/100\n",
618 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6378 - accuracy: 0.8114 - val_loss: 0.9267 - val_accuracy: 0.7256\n",
619 | "Epoch 89/100\n",
620 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6336 - accuracy: 0.8124 - val_loss: 0.9598 - val_accuracy: 0.7163\n",
621 | "Epoch 90/100\n",
622 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6322 - accuracy: 0.8130 - val_loss: 0.9288 - val_accuracy: 0.7266\n",
623 | "Epoch 91/100\n",
624 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6272 - accuracy: 0.8146 - val_loss: 0.9322 - val_accuracy: 0.7206\n",
625 | "Epoch 92/100\n",
626 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6214 - accuracy: 0.8170 - val_loss: 0.9392 - val_accuracy: 0.7247\n",
627 | "Epoch 93/100\n",
628 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6214 - accuracy: 0.8163 - val_loss: 0.9352 - val_accuracy: 0.7250\n",
629 | "Epoch 94/100\n",
630 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6184 - accuracy: 0.8172 - val_loss: 0.9275 - val_accuracy: 0.7321\n",
631 | "Epoch 95/100\n",
632 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6141 - accuracy: 0.8190 - val_loss: 0.9285 - val_accuracy: 0.7313\n",
633 | "Epoch 96/100\n",
634 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6100 - accuracy: 0.8195 - val_loss: 0.9233 - val_accuracy: 0.7303\n",
635 | "Epoch 97/100\n",
636 | "13/13 [==============================] - 0s 20ms/step - loss: 0.6084 - accuracy: 0.8209 - val_loss: 0.9337 - val_accuracy: 0.7289\n",
637 | "Epoch 98/100\n",
638 | "13/13 [==============================] - 0s 19ms/step - loss: 0.6041 - accuracy: 0.8223 - val_loss: 0.9185 - val_accuracy: 0.7300\n",
639 | "Epoch 99/100\n",
640 | "13/13 [==============================] - 0s 19ms/step - loss: 0.5998 - accuracy: 0.8225 - val_loss: 0.9341 - val_accuracy: 0.7229\n",
641 | "Epoch 100/100\n",
642 | "13/13 [==============================] - 0s 20ms/step - loss: 0.5978 - accuracy: 0.8235 - val_loss: 0.9374 - val_accuracy: 0.7284\n"
643 | ],
644 | "name": "stdout"
645 | }
646 | ]
647 | },
648 | {
649 | "cell_type": "code",
650 | "metadata": {
651 | "id": "iCzu6qk70FlV",
652 | "colab_type": "code",
653 | "colab": {}
654 | },
655 | "source": [
656 | "encoder_model = Model(encoder_inputs, encoder_states)\n",
657 | "\n",
658 | "decoder_state_input_h = Input(shape=(latent_dim,))\n",
659 | "decoder_state_input_c = Input(shape=(latent_dim,))\n",
660 | "decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]\n",
661 | "decoder_outputs, state_h, state_c = decoder_lstm(\n",
662 | " decoder_inputs, initial_state=decoder_states_inputs)\n",
663 | "decoder_states = [state_h, state_c]\n",
664 | "decoder_outputs = decoder_dense(decoder_outputs)\n",
665 | "decoder_model = Model(\n",
666 | " [decoder_inputs] + decoder_states_inputs,\n",
667 | " [decoder_outputs] + decoder_states)\n",
668 | "\n",
669 | "# Reverse-lookup token index to decode sequences back to\n",
670 | "# something readable.\n",
671 | "reverse_input_char_index = dict(\n",
672 | " (i, char) for char, i in input_token_index.items())\n",
673 | "reverse_target_char_index = dict(\n",
674 | " (i, char) for char, i in target_token_index.items())"
675 | ],
676 | "execution_count": null,
677 | "outputs": []
678 | },
679 | {
680 | "cell_type": "code",
681 | "metadata": {
682 | "id": "ppivXYwF0PC-",
683 | "colab_type": "code",
684 | "colab": {}
685 | },
686 | "source": [
687 | "def decode_sequence(input_seq):\n",
688 | " # Encode the input as state vectors.\n",
689 | " states_value = encoder_model.predict(input_seq)\n",
690 | "\n",
691 | " # Generate empty target sequence of length 1.\n",
692 | " target_seq = np.zeros((1, 1, num_decoder_tokens))\n",
693 | " # Populate the first character of target sequence with the start character.\n",
694 | " target_seq[0, 0, target_token_index['\\t']] = 1.\n",
695 | "\n",
696 | " # Sampling loop for a batch of sequences\n",
697 | " # (to simplify, here we assume a batch of size 1).\n",
698 | " stop_condition = False\n",
699 | " decoded_sentence = ''\n",
700 | " while not stop_condition:\n",
701 | " output_tokens, h, c = decoder_model.predict(\n",
702 | " [target_seq] + states_value)\n",
703 | "\n",
704 | " # Sample a token\n",
705 | " sampled_token_index = np.argmax(output_tokens[0, -1, :])\n",
706 | " sampled_char = reverse_target_char_index[sampled_token_index]\n",
707 | " decoded_sentence += sampled_char\n",
708 | "\n",
709 | " # Exit condition: either hit max length\n",
710 | " # or find stop character.\n",
711 | " if (sampled_char == '\\n' or\n",
712 | " len(decoded_sentence) > max_decoder_seq_length):\n",
713 | " stop_condition = True\n",
714 | "\n",
715 | " # Update the target sequence (of length 1).\n",
716 | " target_seq = np.zeros((1, 1, num_decoder_tokens))\n",
717 | " target_seq[0, 0, sampled_token_index] = 1.\n",
718 | "\n",
719 | " # Update states\n",
720 | " states_value = [h, c]\n",
721 | "\n",
722 | " return decoded_sentence"
723 | ],
724 | "execution_count": null,
725 | "outputs": []
726 | },
727 | {
728 | "cell_type": "code",
729 | "metadata": {
730 | "id": "SFJRvGN80X3d",
731 | "colab_type": "code",
732 | "colab": {
733 | "base_uri": "https://localhost:8080/",
734 | "height": 1000
735 | },
736 | "outputId": "a29869d6-eb73-4df2-fa34-2fbd1b34c49a"
737 | },
738 | "source": [
739 | "for seq_index in range(100):\n",
740 | " # Take one sequence (part of the training set)\n",
741 | " # for trying out decoding.\n",
742 | " input_seq = encoder_input_data[seq_index: seq_index + 1]\n",
743 | " decoded_sentence = decode_sequence(input_seq)\n",
744 | " print('-')\n",
745 | " print('Input sentence:', input_texts[seq_index])\n",
746 | " print('Decoded sentence:', decoded_sentence)"
747 | ],
748 | "execution_count": null,
749 | "outputs": [
750 | {
751 | "output_type": "stream",
752 | "text": [
753 | "-\n",
754 | "Input sentence: Go.\n",
755 | "Decoded sentence: Vete.\n",
756 | "\n",
757 | "-\n",
758 | "Input sentence: Go.\n",
759 | "Decoded sentence: Vete.\n",
760 | "\n",
761 | "-\n",
762 | "Input sentence: Go.\n",
763 | "Decoded sentence: Vete.\n",
764 | "\n",
765 | "-\n",
766 | "Input sentence: Go.\n",
767 | "Decoded sentence: Vete.\n",
768 | "\n",
769 | "-\n",
770 | "Input sentence: Hi.\n",
771 | "Decoded sentence: Vente.\n",
772 | "\n",
773 | "-\n",
774 | "Input sentence: Run!\n",
775 | "Decoded sentence: ¡Ve elo!\n",
776 | "\n",
777 | "-\n",
778 | "Input sentence: Run.\n",
779 | "Decoded sentence: Vete.\n",
780 | "\n",
781 | "-\n",
782 | "Input sentence: Who?\n",
783 | "Decoded sentence: ¿Quién anor?\n",
784 | "\n",
785 | "-\n",
786 | "Input sentence: Fire!\n",
787 | "Decoded sentence: ¡Despara!\n",
788 | "\n",
789 | "-\n",
790 | "Input sentence: Fire!\n",
791 | "Decoded sentence: ¡Despara!\n",
792 | "\n",
793 | "-\n",
794 | "Input sentence: Fire!\n",
795 | "Decoded sentence: ¡Despara!\n",
796 | "\n",
797 | "-\n",
798 | "Input sentence: Help!\n",
799 | "Decoded sentence: ¡Vete!\n",
800 | "\n",
801 | "-\n",
802 | "Input sentence: Help!\n",
803 | "Decoded sentence: ¡Vete!\n",
804 | "\n",
805 | "-\n",
806 | "Input sentence: Help!\n",
807 | "Decoded sentence: ¡Vete!\n",
808 | "\n",
809 | "-\n",
810 | "Input sentence: Jump!\n",
811 | "Decoded sentence: ¡Dete alo!\n",
812 | "\n",
813 | "-\n",
814 | "Input sentence: Jump.\n",
815 | "Decoded sentence: Satente.\n",
816 | "\n",
817 | "-\n",
818 | "Input sentence: Stop!\n",
819 | "Decoded sentence: ¡Vete a!\n",
820 | "\n",
821 | "-\n",
822 | "Input sentence: Stop!\n",
823 | "Decoded sentence: ¡Vete a!\n",
824 | "\n",
825 | "-\n",
826 | "Input sentence: Stop!\n",
827 | "Decoded sentence: ¡Vete a!\n",
828 | "\n",
829 | "-\n",
830 | "Input sentence: Wait!\n",
831 | "Decoded sentence: ¡Desesta!\n",
832 | "\n",
833 | "-\n",
834 | "Input sentence: Wait.\n",
835 | "Decoded sentence: Allante alo.\n",
836 | "\n",
837 | "-\n",
838 | "Input sentence: Go on.\n",
839 | "Decoded sentence: Vente.\n",
840 | "\n",
841 | "-\n",
842 | "Input sentence: Go on.\n",
843 | "Decoded sentence: Vente.\n",
844 | "\n",
845 | "-\n",
846 | "Input sentence: Hello!\n",
847 | "Decoded sentence: ¡Lorado!\n",
848 | "\n",
849 | "-\n",
850 | "Input sentence: I ran.\n",
851 | "Decoded sentence: Corrí.\n",
852 | "\n",
853 | "-\n",
854 | "Input sentence: I ran.\n",
855 | "Decoded sentence: Corrí.\n",
856 | "\n",
857 | "-\n",
858 | "Input sentence: I try.\n",
859 | "Decoded sentence: Es trerda.\n",
860 | "\n",
861 | "-\n",
862 | "Input sentence: I won!\n",
863 | "Decoded sentence: ¡Prado!\n",
864 | "\n",
865 | "-\n",
866 | "Input sentence: Oh no!\n",
867 | "Decoded sentence: ¡Para!\n",
868 | "\n",
869 | "-\n",
870 | "Input sentence: Relax.\n",
871 | "Decoded sentence: Abrala a Tom.\n",
872 | "\n",
873 | "-\n",
874 | "Input sentence: Smile.\n",
875 | "Decoded sentence: Menten ararra.\n",
876 | "\n",
877 | "-\n",
878 | "Input sentence: Attack!\n",
879 | "Decoded sentence: ¡De pira!\n",
880 | "\n",
881 | "-\n",
882 | "Input sentence: Attack!\n",
883 | "Decoded sentence: ¡De pira!\n",
884 | "\n",
885 | "-\n",
886 | "Input sentence: Get up.\n",
887 | "Decoded sentence: Ayada.\n",
888 | "\n",
889 | "-\n",
890 | "Input sentence: Go now.\n",
891 | "Decoded sentence: Antrade.\n",
892 | "\n",
893 | "-\n",
894 | "Input sentence: Got it!\n",
895 | "Decoded sentence: ¡Lo te alo!\n",
896 | "\n",
897 | "-\n",
898 | "Input sentence: Got it?\n",
899 | "Decoded sentence: ¿Qué porro?\n",
900 | "\n",
901 | "-\n",
902 | "Input sentence: Got it?\n",
903 | "Decoded sentence: ¿Qué porro?\n",
904 | "\n",
905 | "-\n",
906 | "Input sentence: He ran.\n",
907 | "Decoded sentence: Mente ciente.\n",
908 | "\n",
909 | "-\n",
910 | "Input sentence: Hop in.\n",
911 | "Decoded sentence: Menten astrada.\n",
912 | "\n",
913 | "-\n",
914 | "Input sentence: Hug me.\n",
915 | "Decoded sentence: Ayrada esto.\n",
916 | "\n",
917 | "-\n",
918 | "Input sentence: I fell.\n",
919 | "Decoded sentence: Me cuerda.\n",
920 | "\n",
921 | "-\n",
922 | "Input sentence: I know.\n",
923 | "Decoded sentence: Me carrió.\n",
924 | "\n",
925 | "-\n",
926 | "Input sentence: I left.\n",
927 | "Decoded sentence: Lo vira.\n",
928 | "\n",
929 | "-\n",
930 | "Input sentence: I lied.\n",
931 | "Decoded sentence: Mentente.\n",
932 | "\n",
933 | "-\n",
934 | "Input sentence: I lost.\n",
935 | "Decoded sentence: Ve arí.\n",
936 | "\n",
937 | "-\n",
938 | "Input sentence: I quit.\n",
939 | "Decoded sentence: Mentre.\n",
940 | "\n",
941 | "-\n",
942 | "Input sentence: I quit.\n",
943 | "Decoded sentence: Mentre.\n",
944 | "\n",
945 | "-\n",
946 | "Input sentence: I work.\n",
947 | "Decoded sentence: Estrada.\n",
948 | "\n",
949 | "-\n",
950 | "Input sentence: I'm 19.\n",
951 | "Decoded sentence: Estoy alo.\n",
952 | "\n",
953 | "-\n",
954 | "Input sentence: I'm up.\n",
955 | "Decoded sentence: Estoy lorada.\n",
956 | "\n",
957 | "-\n",
958 | "Input sentence: Listen.\n",
959 | "Decoded sentence: Mintente en arira.\n",
960 | "\n",
961 | "-\n",
962 | "Input sentence: Listen.\n",
963 | "Decoded sentence: Mintente en arira.\n",
964 | "\n",
965 | "-\n",
966 | "Input sentence: Listen.\n",
967 | "Decoded sentence: Mintente en arira.\n",
968 | "\n",
969 | "-\n",
970 | "Input sentence: No way!\n",
971 | "Decoded sentence: ¡De pirra!\n",
972 | "\n",
973 | "-\n",
974 | "Input sentence: No way!\n",
975 | "Decoded sentence: ¡De pirra!\n",
976 | "\n",
977 | "-\n",
978 | "Input sentence: No way!\n",
979 | "Decoded sentence: ¡De pirra!\n",
980 | "\n",
981 | "-\n",
982 | "Input sentence: No way!\n",
983 | "Decoded sentence: ¡De pirra!\n",
984 | "\n",
985 | "-\n",
986 | "Input sentence: No way!\n",
987 | "Decoded sentence: ¡De pirra!\n",
988 | "\n",
989 | "-\n",
990 | "Input sentence: No way!\n",
991 | "Decoded sentence: ¡De pirra!\n",
992 | "\n",
993 | "-\n",
994 | "Input sentence: No way!\n",
995 | "Decoded sentence: ¡De pirra!\n",
996 | "\n",
997 | "-\n",
998 | "Input sentence: No way!\n",
999 | "Decoded sentence: ¡De pirra!\n",
1000 | "\n",
1001 | "-\n",
1002 | "Input sentence: No way!\n",
1003 | "Decoded sentence: ¡De pirra!\n",
1004 | "\n",
1005 | "-\n",
1006 | "Input sentence: No way!\n",
1007 | "Decoded sentence: ¡De pirra!\n",
1008 | "\n",
1009 | "-\n",
1010 | "Input sentence: Really?\n",
1011 | "Decoded sentence: ¿Pien iro?\n",
1012 | "\n",
1013 | "-\n",
1014 | "Input sentence: Really?\n",
1015 | "Decoded sentence: ¿Pien iro?\n",
1016 | "\n",
1017 | "-\n",
1018 | "Input sentence: Thanks.\n",
1019 | "Decoded sentence: Alala asto.\n",
1020 | "\n",
1021 | "-\n",
1022 | "Input sentence: Thanks.\n",
1023 | "Decoded sentence: Alala asto.\n",
1024 | "\n",
1025 | "-\n",
1026 | "Input sentence: Try it.\n",
1027 | "Decoded sentence: Pruente alo.\n",
1028 | "\n",
1029 | "-\n",
1030 | "Input sentence: We try.\n",
1031 | "Decoded sentence: Pruén astora.\n",
1032 | "\n",
1033 | "-\n",
1034 | "Input sentence: We won.\n",
1035 | "Decoded sentence: Minte alo.\n",
1036 | "\n",
1037 | "-\n",
1038 | "Input sentence: Why me?\n",
1039 | "Decoded sentence: ¿Quién an carado?\n",
1040 | "\n",
1041 | "-\n",
1042 | "Input sentence: Ask Tom.\n",
1043 | "Decoded sentence: Ayude a Tom.\n",
1044 | "\n",
1045 | "-\n",
1046 | "Input sentence: Awesome!\n",
1047 | "Decoded sentence: ¡Desperra!\n",
1048 | "\n",
1049 | "-\n",
1050 | "Input sentence: Be calm.\n",
1051 | "Decoded sentence: Séntate carra.\n",
1052 | "\n",
1053 | "-\n",
1054 | "Input sentence: Be cool.\n",
1055 | "Decoded sentence: Sénta carri.\n",
1056 | "\n",
1057 | "-\n",
1058 | "Input sentence: Be fair.\n",
1059 | "Decoded sentence: Sé antrente.\n",
1060 | "\n",
1061 | "-\n",
1062 | "Input sentence: Be kind.\n",
1063 | "Decoded sentence: Sén antre.\n",
1064 | "\n",
1065 | "-\n",
1066 | "Input sentence: Be nice.\n",
1067 | "Decoded sentence: Sénta cire.\n",
1068 | "\n",
1069 | "-\n",
1070 | "Input sentence: Beat it.\n",
1071 | "Decoded sentence: Séla asto.\n",
1072 | "\n",
1073 | "-\n",
1074 | "Input sentence: Call me.\n",
1075 | "Decoded sentence: Allama a Tom.\n",
1076 | "\n",
1077 | "-\n",
1078 | "Input sentence: Call me.\n",
1079 | "Decoded sentence: Allama a Tom.\n",
1080 | "\n",
1081 | "-\n",
1082 | "Input sentence: Call me.\n",
1083 | "Decoded sentence: Allama a Tom.\n",
1084 | "\n",
1085 | "-\n",
1086 | "Input sentence: Call us.\n",
1087 | "Decoded sentence: ¡Llamame a Tomásto.\n",
1088 | "\n",
1089 | "-\n",
1090 | "Input sentence: Come in.\n",
1091 | "Decoded sentence: Vente a Tom.\n",
1092 | "\n",
1093 | "-\n",
1094 | "Input sentence: Come in.\n",
1095 | "Decoded sentence: Vente a Tom.\n",
1096 | "\n",
1097 | "-\n",
1098 | "Input sentence: Come in.\n",
1099 | "Decoded sentence: Vente a Tom.\n",
1100 | "\n",
1101 | "-\n",
1102 | "Input sentence: Come on!\n",
1103 | "Decoded sentence: ¡Vete alo!\n",
1104 | "\n",
1105 | "-\n",
1106 | "Input sentence: Come on.\n",
1107 | "Decoded sentence: Vente aquí.\n",
1108 | "\n",
1109 | "-\n",
1110 | "Input sentence: Come on.\n",
1111 | "Decoded sentence: Vente aquí.\n",
1112 | "\n",
1113 | "-\n",
1114 | "Input sentence: Drop it!\n",
1115 | "Decoded sentence: ¡De prirdo!\n",
1116 | "\n",
1117 | "-\n",
1118 | "Input sentence: Get Tom.\n",
1119 | "Decoded sentence: Ayada a Tomás.\n",
1120 | "\n",
1121 | "-\n",
1122 | "Input sentence: Get out!\n",
1123 | "Decoded sentence: ¡La te alo!\n",
1124 | "\n",
1125 | "-\n",
1126 | "Input sentence: Get out.\n",
1127 | "Decoded sentence: Alata alo.\n",
1128 | "\n",
1129 | "-\n",
1130 | "Input sentence: Get out.\n",
1131 | "Decoded sentence: Alata alo.\n",
1132 | "\n",
1133 | "-\n",
1134 | "Input sentence: Get out.\n",
1135 | "Decoded sentence: Alata alo.\n",
1136 | "\n",
1137 | "-\n",
1138 | "Input sentence: Get out.\n",
1139 | "Decoded sentence: Alata alo.\n",
1140 | "\n",
1141 | "-\n",
1142 | "Input sentence: Get out.\n",
1143 | "Decoded sentence: Alata alo.\n",
1144 | "\n",
1145 | "-\n",
1146 | "Input sentence: Go away!\n",
1147 | "Decoded sentence: ¡La te a aquí!\n",
1148 | "\n",
1149 | "-\n",
1150 | "Input sentence: Go away!\n",
1151 | "Decoded sentence: ¡La te a aquí!\n",
1152 | "\n"
1153 | ],
1154 | "name": "stdout"
1155 | }
1156 | ]
1157 | }
1158 | ]
1159 | }
--------------------------------------------------------------------------------
/PAIGCP_image_captioning.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "accelerator": "GPU",
6 | "colab": {
7 | "name": "PAIGCP_image_captioning.ipynb",
8 | "provenance": [],
9 | "private_outputs": true,
10 | "collapsed_sections": [],
11 | "include_colab_link": true
12 | },
13 | "kernelspec": {
14 | "display_name": "Python 3",
15 | "name": "python3"
16 | }
17 | },
18 | "cells": [
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {
22 | "id": "view-in-github",
23 | "colab_type": "text"
24 | },
25 | "source": [
26 | "
"
27 | ]
28 | },
29 | {
30 | "cell_type": "markdown",
31 | "metadata": {
32 | "colab_type": "text",
33 | "id": "K2s1A9eLRPEj"
34 | },
35 | "source": [
36 | "##### Copyright 2018 The TensorFlow Authors.\n"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "metadata": {
42 | "cellView": "form",
43 | "colab_type": "code",
44 | "id": "VRLVEKiTEn04",
45 | "colab": {}
46 | },
47 | "source": [
48 | "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
49 | "# you may not use this file except in compliance with the License.\n",
50 | "# You may obtain a copy of the License at\n",
51 | "#\n",
52 | "# https://www.apache.org/licenses/LICENSE-2.0\n",
53 | "#\n",
54 | "# Unless required by applicable law or agreed to in writing, software\n",
55 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
56 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
57 | "# See the License for the specific language governing permissions and\n",
58 | "# limitations under the License."
59 | ],
60 | "execution_count": null,
61 | "outputs": []
62 | },
63 | {
64 | "cell_type": "markdown",
65 | "metadata": {
66 | "colab_type": "text",
67 | "id": "Cffg2i257iMS"
68 | },
69 | "source": [
70 | "# Image captioning with visual attention\n",
71 | "\n",
72 | ""
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {
97 | "colab_type": "text",
98 | "id": "QASbY_HGo4Lq"
99 | },
100 | "source": [
101 | "Given an image like the example below, our goal is to generate a caption such as \"a surfer riding on a wave\".\n",
102 | "\n",
103 | "\n",
104 | "\n",
105 | "*[Image Source](https://commons.wikimedia.org/wiki/Surfing#/media/File:Surfing_in_Hawaii.jpg); License: Public Domain*\n",
106 | "\n",
107 | "To accomplish this, you'll use an attention-based model, which enables us to see what parts of the image the model focuses on as it generates a caption.\n",
108 | "\n",
109 | "\n",
110 | "\n",
111 | "The model architecture is similar to [Show, Attend and Tell: Neural Image Caption Generation with Visual Attention](https://arxiv.org/abs/1502.03044).\n",
112 | "\n",
113 | "This notebook is an end-to-end example. When you run the notebook, it downloads the [MS-COCO](http://cocodataset.org/#home) dataset, preprocesses and caches a subset of images using Inception V3, trains an encoder-decoder model, and generates captions on new images using the trained model.\n",
114 | "\n",
115 | "In this example, you will train a model on a relatively small amount of data—the first 30,000 captions for about 20,000 images (because there are multiple captions per image in the dataset)."
116 | ]
117 | },
118 | {
119 | "cell_type": "code",
120 | "metadata": {
121 | "colab_type": "code",
122 | "id": "U8l4RJ0XRPEm",
123 | "colab": {}
124 | },
125 | "source": [
126 | "import tensorflow as tf\n",
127 | "\n",
128 | "# You'll generate plots of attention in order to see which parts of an image\n",
129 | "# our model focuses on during captioning\n",
130 | "import matplotlib.pyplot as plt\n",
131 | "\n",
132 | "# Scikit-learn includes many helpful utilities\n",
133 | "from sklearn.model_selection import train_test_split\n",
134 | "from sklearn.utils import shuffle\n",
135 | "\n",
136 | "import re\n",
137 | "import numpy as np\n",
138 | "import os\n",
139 | "import time\n",
140 | "import json\n",
141 | "from glob import glob\n",
142 | "from PIL import Image\n",
143 | "import pickle"
144 | ],
145 | "execution_count": null,
146 | "outputs": []
147 | },
148 | {
149 | "cell_type": "markdown",
150 | "metadata": {
151 | "colab_type": "text",
152 | "id": "b6qbGw8MRPE5"
153 | },
154 | "source": [
155 | "## Download and prepare the MS-COCO dataset\n",
156 | "\n",
157 | "You will use the [MS-COCO dataset](http://cocodataset.org/#home) to train our model. The dataset contains over 82,000 images, each of which has at least 5 different caption annotations. The code below downloads and extracts the dataset automatically.\n",
158 | "\n",
159 | "**Caution: large download ahead**. You'll use the training set, which is a 13GB file."
160 | ]
161 | },
162 | {
163 | "cell_type": "code",
164 | "metadata": {
165 | "colab_type": "code",
166 | "id": "krQuPYTtRPE7",
167 | "colab": {}
168 | },
169 | "source": [
170 | "# Download caption annotation files\n",
171 | "annotation_folder = '/annotations/'\n",
172 | "if not os.path.exists(os.path.abspath('.') + annotation_folder):\n",
173 | " annotation_zip = tf.keras.utils.get_file('captions.zip',\n",
174 | " cache_subdir=os.path.abspath('.'),\n",
175 | " origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip',\n",
176 | " extract = True)\n",
177 | " annotation_file = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json'\n",
178 | " os.remove(annotation_zip)\n",
179 | "\n",
180 | "# Download image files\n",
181 | "image_folder = '/train2014/'\n",
182 | "if not os.path.exists(os.path.abspath('.') + image_folder):\n",
183 | " image_zip = tf.keras.utils.get_file('train2014.zip',\n",
184 | " cache_subdir=os.path.abspath('.'),\n",
185 | " origin = 'http://images.cocodataset.org/zips/train2014.zip',\n",
186 | " extract = True)\n",
187 | " PATH = os.path.dirname(image_zip) + image_folder\n",
188 | " os.remove(image_zip)\n",
189 | "else:\n",
190 | " PATH = os.path.abspath('.') + image_folder"
191 | ],
192 | "execution_count": null,
193 | "outputs": []
194 | },
195 | {
196 | "cell_type": "markdown",
197 | "metadata": {
198 | "colab_type": "text",
199 | "id": "aANEzb5WwSzg"
200 | },
201 | "source": [
202 | "## Optional: limit the size of the training set \n",
203 | "To speed up training for this tutorial, you'll use a subset of 30,000 captions and their corresponding images to train our model. Choosing to use more data would result in improved captioning quality."
204 | ]
205 | },
206 | {
207 | "cell_type": "code",
208 | "metadata": {
209 | "colab_type": "code",
210 | "id": "4G3b8x8_RPFD",
211 | "colab": {}
212 | },
213 | "source": [
214 | "# Read the json file\n",
215 | "with open(annotation_file, 'r') as f:\n",
216 | " annotations = json.load(f)\n",
217 | "\n",
218 | "# Store captions and image names in vectors\n",
219 | "all_captions = []\n",
220 | "all_img_name_vector = []\n",
221 | "\n",
222 | "for annot in annotations['annotations']:\n",
223 | " caption = ' ' + annot['caption'] + ' '\n",
224 | " image_id = annot['image_id']\n",
225 | " full_coco_image_path = PATH + 'COCO_train2014_' + '%012d.jpg' % (image_id)\n",
226 | "\n",
227 | " all_img_name_vector.append(full_coco_image_path)\n",
228 | " all_captions.append(caption)\n",
229 | "\n",
230 | "# Shuffle captions and image_names together\n",
231 | "# Set a random state\n",
232 | "train_captions, img_name_vector = shuffle(all_captions,\n",
233 | " all_img_name_vector,\n",
234 | " random_state=1)\n",
235 | "\n",
236 | "# Select the first 30000 captions from the shuffled set\n",
237 | "num_examples = 30000\n",
238 | "train_captions = train_captions[:num_examples]\n",
239 | "img_name_vector = img_name_vector[:num_examples]"
240 | ],
241 | "execution_count": null,
242 | "outputs": []
243 | },
244 | {
245 | "cell_type": "code",
246 | "metadata": {
247 | "colab_type": "code",
248 | "id": "mPBMgK34RPFL",
249 | "colab": {}
250 | },
251 | "source": [
252 | "len(train_captions), len(all_captions)"
253 | ],
254 | "execution_count": null,
255 | "outputs": []
256 | },
257 | {
258 | "cell_type": "markdown",
259 | "metadata": {
260 | "colab_type": "text",
261 | "id": "8cSW4u-ORPFQ"
262 | },
263 | "source": [
264 | "## Preprocess the images using InceptionV3\n",
265 | "Next, you will use InceptionV3 (which is pretrained on Imagenet) to classify each image. You will extract features from the last convolutional layer.\n",
266 | "\n",
267 | "First, you will convert the images into InceptionV3's expected format by:\n",
268 | "* Resizing the image to 299px by 299px\n",
269 | "* [Preprocess the images](https://cloud.google.com/tpu/docs/inception-v3-advanced#preprocessing_stage) using the [preprocess_input](https://www.tensorflow.org/api_docs/python/tf/keras/applications/inception_v3/preprocess_input) method to normalize the image so that it contains pixels in the range of -1 to 1, which matches the format of the images used to train InceptionV3."
270 | ]
271 | },
272 | {
273 | "cell_type": "code",
274 | "metadata": {
275 | "colab_type": "code",
276 | "id": "zXR0217aRPFR",
277 | "colab": {}
278 | },
279 | "source": [
280 | "def load_image(image_path):\n",
281 | " img = tf.io.read_file(image_path)\n",
282 | " img = tf.image.decode_jpeg(img, channels=3)\n",
283 | " img = tf.image.resize(img, (299, 299))\n",
284 | " img = tf.keras.applications.inception_v3.preprocess_input(img)\n",
285 | " return img, image_path"
286 | ],
287 | "execution_count": null,
288 | "outputs": []
289 | },
290 | {
291 | "cell_type": "markdown",
292 | "metadata": {
293 | "colab_type": "text",
294 | "id": "MDvIu4sXRPFV"
295 | },
296 | "source": [
297 | "## Initialize InceptionV3 and load the pretrained Imagenet weights\n",
298 | "\n",
299 | "Now you'll create a tf.keras model where the output layer is the last convolutional layer in the InceptionV3 architecture. The shape of the output of this layer is ```8x8x2048```. You use the last convolutional layer because you are using attention in this example. You don't perform this initialization during training because it could become a bottleneck.\n",
300 | "\n",
301 | "* You forward each image through the network and store the resulting vector in a dictionary (image_name --> feature_vector).\n",
302 | "* After all the images are passed through the network, you pickle the dictionary and save it to disk.\n"
303 | ]
304 | },
305 | {
306 | "cell_type": "code",
307 | "metadata": {
308 | "colab_type": "code",
309 | "id": "RD3vW4SsRPFW",
310 | "colab": {}
311 | },
312 | "source": [
313 | "image_model = tf.keras.applications.InceptionV3(include_top=False,\n",
314 | " weights='imagenet')\n",
315 | "new_input = image_model.input\n",
316 | "hidden_layer = image_model.layers[-1].output\n",
317 | "\n",
318 | "image_features_extract_model = tf.keras.Model(new_input, hidden_layer)"
319 | ],
320 | "execution_count": null,
321 | "outputs": []
322 | },
323 | {
324 | "cell_type": "markdown",
325 | "metadata": {
326 | "colab_type": "text",
327 | "id": "rERqlR3WRPGO"
328 | },
329 | "source": [
330 | "## Caching the features extracted from InceptionV3\n",
331 | "\n",
332 | "You will pre-process each image with InceptionV3 and cache the output to disk. Caching the output in RAM would be faster but also memory intensive, requiring 8 \\* 8 \\* 2048 floats per image. At the time of writing, this exceeds the memory limitations of Colab (currently 12GB of memory).\n",
333 | "\n",
334 | "Performance could be improved with a more sophisticated caching strategy (for example, by sharding the images to reduce random access disk I/O), but that would require more code.\n",
335 | "\n",
336 | "The caching will take about 10 minutes to run in Colab with a GPU. If you'd like to see a progress bar, you can: \n",
337 | "\n",
338 | "1. install [tqdm](https://github.com/tqdm/tqdm):\n",
339 | "\n",
340 | " `!pip install tqdm`\n",
341 | "\n",
342 | "2. Import tqdm:\n",
343 | "\n",
344 | " `from tqdm import tqdm`\n",
345 | "\n",
346 | "3. Change the following line:\n",
347 | "\n",
348 | " `for img, path in image_dataset:`\n",
349 | "\n",
350 | " to:\n",
351 | "\n",
352 | " `for img, path in tqdm(image_dataset):`\n"
353 | ]
354 | },
355 | {
356 | "cell_type": "code",
357 | "metadata": {
358 | "colab_type": "code",
359 | "id": "Dx_fvbVgRPGQ",
360 | "colab": {}
361 | },
362 | "source": [
363 | "# Get unique images\n",
364 | "encode_train = sorted(set(img_name_vector))\n",
365 | "\n",
366 | "# Feel free to change batch_size according to your system configuration\n",
367 | "image_dataset = tf.data.Dataset.from_tensor_slices(encode_train)\n",
368 | "image_dataset = image_dataset.map(\n",
369 | " load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE).batch(16)\n",
370 | "\n",
371 | "for img, path in image_dataset:\n",
372 | " batch_features = image_features_extract_model(img)\n",
373 | " batch_features = tf.reshape(batch_features,\n",
374 | " (batch_features.shape[0], -1, batch_features.shape[3]))\n",
375 | "\n",
376 | " for bf, p in zip(batch_features, path):\n",
377 | " path_of_feature = p.numpy().decode(\"utf-8\")\n",
378 | " np.save(path_of_feature, bf.numpy())"
379 | ],
380 | "execution_count": null,
381 | "outputs": []
382 | },
383 | {
384 | "cell_type": "markdown",
385 | "metadata": {
386 | "colab_type": "text",
387 | "id": "nyqH3zFwRPFi"
388 | },
389 | "source": [
390 | "## Preprocess and tokenize the captions\n",
391 | "\n",
392 | "* First, you'll tokenize the captions (for example, by splitting on spaces). This gives us a vocabulary of all of the unique words in the data (for example, \"surfing\", \"football\", and so on).\n",
393 | "* Next, you'll limit the vocabulary size to the top 5,000 words (to save memory). You'll replace all other words with the token \"UNK\" (unknown).\n",
394 | "* You then create word-to-index and index-to-word mappings.\n",
395 | "* Finally, you pad all sequences to be the same length as the longest one."
396 | ]
397 | },
398 | {
399 | "cell_type": "code",
400 | "metadata": {
401 | "colab_type": "code",
402 | "id": "HZfK8RhQRPFj",
403 | "colab": {}
404 | },
405 | "source": [
406 | "# Find the maximum length of any caption in our dataset\n",
407 | "def calc_max_length(tensor):\n",
408 | " return max(len(t) for t in tensor)"
409 | ],
410 | "execution_count": null,
411 | "outputs": []
412 | },
413 | {
414 | "cell_type": "code",
415 | "metadata": {
416 | "colab_type": "code",
417 | "id": "oJGE34aiRPFo",
418 | "colab": {}
419 | },
420 | "source": [
421 | "# Choose the top 5000 words from the vocabulary\n",
422 | "top_k = 5000\n",
423 | "tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k,\n",
424 | " oov_token=\"\",\n",
425 | " filters='!\"#$%&()*+.,-/:;=?@[\\]^_`{|}~ ')\n",
426 | "tokenizer.fit_on_texts(train_captions)\n",
427 | "train_seqs = tokenizer.texts_to_sequences(train_captions)"
428 | ],
429 | "execution_count": null,
430 | "outputs": []
431 | },
432 | {
433 | "cell_type": "code",
434 | "metadata": {
435 | "colab_type": "code",
436 | "id": "8Q44tNQVRPFt",
437 | "colab": {}
438 | },
439 | "source": [
440 | "tokenizer.word_index[''] = 0\n",
441 | "tokenizer.index_word[0] = ''"
442 | ],
443 | "execution_count": null,
444 | "outputs": []
445 | },
446 | {
447 | "cell_type": "code",
448 | "metadata": {
449 | "colab_type": "code",
450 | "id": "0fpJb5ojRPFv",
451 | "colab": {}
452 | },
453 | "source": [
454 | "# Create the tokenized vectors\n",
455 | "train_seqs = tokenizer.texts_to_sequences(train_captions)"
456 | ],
457 | "execution_count": null,
458 | "outputs": []
459 | },
460 | {
461 | "cell_type": "code",
462 | "metadata": {
463 | "colab_type": "code",
464 | "id": "AidglIZVRPF4",
465 | "colab": {}
466 | },
467 | "source": [
468 | "# Pad each vector to the max_length of the captions\n",
469 | "# If you do not provide a max_length value, pad_sequences calculates it automatically\n",
470 | "cap_vector = tf.keras.preprocessing.sequence.pad_sequences(train_seqs, padding='post')"
471 | ],
472 | "execution_count": null,
473 | "outputs": []
474 | },
475 | {
476 | "cell_type": "code",
477 | "metadata": {
478 | "colab_type": "code",
479 | "id": "gL0wkttkRPGA",
480 | "colab": {}
481 | },
482 | "source": [
483 | "# Calculates the max_length, which is used to store the attention weights\n",
484 | "max_length = calc_max_length(train_seqs)"
485 | ],
486 | "execution_count": null,
487 | "outputs": []
488 | },
489 | {
490 | "cell_type": "markdown",
491 | "metadata": {
492 | "colab_type": "text",
493 | "id": "M3CD75nDpvTI"
494 | },
495 | "source": [
496 | "## Split the data into training and testing"
497 | ]
498 | },
499 | {
500 | "cell_type": "code",
501 | "metadata": {
502 | "colab_type": "code",
503 | "id": "iS7DDMszRPGF",
504 | "colab": {}
505 | },
506 | "source": [
507 | "# Create training and validation sets using an 80-20 split\n",
508 | "img_name_train, img_name_val, cap_train, cap_val = train_test_split(img_name_vector,\n",
509 | " cap_vector,\n",
510 | " test_size=0.2,\n",
511 | " random_state=0)"
512 | ],
513 | "execution_count": null,
514 | "outputs": []
515 | },
516 | {
517 | "cell_type": "code",
518 | "metadata": {
519 | "colab_type": "code",
520 | "id": "XmViPkRFRPGH",
521 | "colab": {}
522 | },
523 | "source": [
524 | "len(img_name_train), len(cap_train), len(img_name_val), len(cap_val)"
525 | ],
526 | "execution_count": null,
527 | "outputs": []
528 | },
529 | {
530 | "cell_type": "markdown",
531 | "metadata": {
532 | "colab_type": "text",
533 | "id": "uEWM9xrYcg45"
534 | },
535 | "source": [
536 | "## Create a tf.data dataset for training\n"
537 | ]
538 | },
539 | {
540 | "cell_type": "markdown",
541 | "metadata": {
542 | "colab_type": "text",
543 | "id": "horagNvhhZiy"
544 | },
545 | "source": [
546 | " Our images and captions are ready! Next, let's create a tf.data dataset to use for training our model."
547 | ]
548 | },
549 | {
550 | "cell_type": "code",
551 | "metadata": {
552 | "colab_type": "code",
553 | "id": "Q3TnZ1ToRPGV",
554 | "colab": {}
555 | },
556 | "source": [
557 | "# Feel free to change these parameters according to your system's configuration\n",
558 | "\n",
559 | "BATCH_SIZE = 64\n",
560 | "BUFFER_SIZE = 1000\n",
561 | "embedding_dim = 256\n",
562 | "units = 512\n",
563 | "vocab_size = top_k + 1\n",
564 | "num_steps = len(img_name_train) // BATCH_SIZE\n",
565 | "# Shape of the vector extracted from InceptionV3 is (64, 2048)\n",
566 | "# These two variables represent that vector shape\n",
567 | "features_shape = 2048\n",
568 | "attention_features_shape = 64"
569 | ],
570 | "execution_count": null,
571 | "outputs": []
572 | },
573 | {
574 | "cell_type": "code",
575 | "metadata": {
576 | "colab_type": "code",
577 | "id": "SmZS2N0bXG3T",
578 | "colab": {}
579 | },
580 | "source": [
581 | "# Load the numpy files\n",
582 | "def map_func(img_name, cap):\n",
583 | " img_tensor = np.load(img_name.decode('utf-8')+'.npy')\n",
584 | " return img_tensor, cap"
585 | ],
586 | "execution_count": null,
587 | "outputs": []
588 | },
589 | {
590 | "cell_type": "code",
591 | "metadata": {
592 | "colab_type": "code",
593 | "id": "FDF_Nm3tRPGZ",
594 | "colab": {}
595 | },
596 | "source": [
597 | "dataset = tf.data.Dataset.from_tensor_slices((img_name_train, cap_train))\n",
598 | "\n",
599 | "# Use map to load the numpy files in parallel\n",
600 | "dataset = dataset.map(lambda item1, item2: tf.numpy_function(\n",
601 | " map_func, [item1, item2], [tf.float32, tf.int32]),\n",
602 | " num_parallel_calls=tf.data.experimental.AUTOTUNE)\n",
603 | "\n",
604 | "# Shuffle and batch\n",
605 | "dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)\n",
606 | "dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)"
607 | ],
608 | "execution_count": null,
609 | "outputs": []
610 | },
611 | {
612 | "cell_type": "markdown",
613 | "metadata": {
614 | "colab_type": "text",
615 | "id": "nrvoDphgRPGd"
616 | },
617 | "source": [
618 | "## Model\n",
619 | "\n",
620 | "Fun fact: the decoder below is identical to the one in the example for [Neural Machine Translation with Attention](../sequences/nmt_with_attention.ipynb).\n",
621 | "\n",
622 | "The model architecture is inspired by the [Show, Attend and Tell](https://arxiv.org/pdf/1502.03044.pdf) paper.\n",
623 | "\n",
624 | "* In this example, you extract the features from the lower convolutional layer of InceptionV3 giving us a vector of shape (8, 8, 2048).\n",
625 | "* You squash that to a shape of (64, 2048).\n",
626 | "* This vector is then passed through the CNN Encoder (which consists of a single Fully connected layer).\n",
627 | "* The RNN (here GRU) attends over the image to predict the next word."
628 | ]
629 | },
630 | {
631 | "cell_type": "code",
632 | "metadata": {
633 | "colab_type": "code",
634 | "id": "ja2LFTMSdeV3",
635 | "colab": {}
636 | },
637 | "source": [
638 | "class BahdanauAttention(tf.keras.Model):\n",
639 | " def __init__(self, units):\n",
640 | " super(BahdanauAttention, self).__init__()\n",
641 | " self.W1 = tf.keras.layers.Dense(units)\n",
642 | " self.W2 = tf.keras.layers.Dense(units)\n",
643 | " self.V = tf.keras.layers.Dense(1)\n",
644 | "\n",
645 | " def call(self, features, hidden):\n",
646 | " # features(CNN_encoder output) shape == (batch_size, 64, embedding_dim)\n",
647 | "\n",
648 | " # hidden shape == (batch_size, hidden_size)\n",
649 | " # hidden_with_time_axis shape == (batch_size, 1, hidden_size)\n",
650 | " hidden_with_time_axis = tf.expand_dims(hidden, 1)\n",
651 | "\n",
652 | " # score shape == (batch_size, 64, hidden_size)\n",
653 | " score = tf.nn.tanh(self.W1(features) + self.W2(hidden_with_time_axis))\n",
654 | "\n",
655 | " # attention_weights shape == (batch_size, 64, 1)\n",
656 | " # you get 1 at the last axis because you are applying score to self.V\n",
657 | " attention_weights = tf.nn.softmax(self.V(score), axis=1)\n",
658 | "\n",
659 | " # context_vector shape after sum == (batch_size, hidden_size)\n",
660 | " context_vector = attention_weights * features\n",
661 | " context_vector = tf.reduce_sum(context_vector, axis=1)\n",
662 | "\n",
663 | " return context_vector, attention_weights"
664 | ],
665 | "execution_count": null,
666 | "outputs": []
667 | },
668 | {
669 | "cell_type": "code",
670 | "metadata": {
671 | "colab_type": "code",
672 | "id": "AZ7R1RxHRPGf",
673 | "colab": {}
674 | },
675 | "source": [
676 | "class CNN_Encoder(tf.keras.Model):\n",
677 | " # Since you have already extracted the features and dumped it using pickle\n",
678 | " # This encoder passes those features through a Fully connected layer\n",
679 | " def __init__(self, embedding_dim):\n",
680 | " super(CNN_Encoder, self).__init__()\n",
681 | " # shape after fc == (batch_size, 64, embedding_dim)\n",
682 | " self.fc = tf.keras.layers.Dense(embedding_dim)\n",
683 | "\n",
684 | " def call(self, x):\n",
685 | " x = self.fc(x)\n",
686 | " x = tf.nn.relu(x)\n",
687 | " return x"
688 | ],
689 | "execution_count": null,
690 | "outputs": []
691 | },
692 | {
693 | "cell_type": "code",
694 | "metadata": {
695 | "colab_type": "code",
696 | "id": "V9UbGQmERPGi",
697 | "colab": {}
698 | },
699 | "source": [
700 | "class RNN_Decoder(tf.keras.Model):\n",
701 | " def __init__(self, embedding_dim, units, vocab_size):\n",
702 | " super(RNN_Decoder, self).__init__()\n",
703 | " self.units = units\n",
704 | "\n",
705 | " self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n",
706 | " self.gru = tf.keras.layers.GRU(self.units,\n",
707 | " return_sequences=True,\n",
708 | " return_state=True,\n",
709 | " recurrent_initializer='glorot_uniform')\n",
710 | " self.fc1 = tf.keras.layers.Dense(self.units)\n",
711 | " self.fc2 = tf.keras.layers.Dense(vocab_size)\n",
712 | "\n",
713 | " self.attention = BahdanauAttention(self.units)\n",
714 | "\n",
715 | " def call(self, x, features, hidden):\n",
716 | " # defining attention as a separate model\n",
717 | " context_vector, attention_weights = self.attention(features, hidden)\n",
718 | "\n",
719 | " # x shape after passing through embedding == (batch_size, 1, embedding_dim)\n",
720 | " x = self.embedding(x)\n",
721 | "\n",
722 | " # x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)\n",
723 | " x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)\n",
724 | "\n",
725 | " # passing the concatenated vector to the GRU\n",
726 | " output, state = self.gru(x)\n",
727 | "\n",
728 | " # shape == (batch_size, max_length, hidden_size)\n",
729 | " x = self.fc1(output)\n",
730 | "\n",
731 | " # x shape == (batch_size * max_length, hidden_size)\n",
732 | " x = tf.reshape(x, (-1, x.shape[2]))\n",
733 | "\n",
734 | " # output shape == (batch_size * max_length, vocab)\n",
735 | " x = self.fc2(x)\n",
736 | "\n",
737 | " return x, state, attention_weights\n",
738 | "\n",
739 | " def reset_state(self, batch_size):\n",
740 | " return tf.zeros((batch_size, self.units))"
741 | ],
742 | "execution_count": null,
743 | "outputs": []
744 | },
745 | {
746 | "cell_type": "code",
747 | "metadata": {
748 | "colab_type": "code",
749 | "id": "Qs_Sr03wRPGk",
750 | "colab": {}
751 | },
752 | "source": [
753 | "encoder = CNN_Encoder(embedding_dim)\n",
754 | "decoder = RNN_Decoder(embedding_dim, units, vocab_size)"
755 | ],
756 | "execution_count": null,
757 | "outputs": []
758 | },
759 | {
760 | "cell_type": "code",
761 | "metadata": {
762 | "colab_type": "code",
763 | "id": "-bYN7xA0RPGl",
764 | "colab": {}
765 | },
766 | "source": [
767 | "optimizer = tf.keras.optimizers.Adam()\n",
768 | "loss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n",
769 | " from_logits=True, reduction='none')\n",
770 | "\n",
771 | "def loss_function(real, pred):\n",
772 | " mask = tf.math.logical_not(tf.math.equal(real, 0))\n",
773 | " loss_ = loss_object(real, pred)\n",
774 | "\n",
775 | " mask = tf.cast(mask, dtype=loss_.dtype)\n",
776 | " loss_ *= mask\n",
777 | "\n",
778 | " return tf.reduce_mean(loss_)"
779 | ],
780 | "execution_count": null,
781 | "outputs": []
782 | },
783 | {
784 | "cell_type": "markdown",
785 | "metadata": {
786 | "colab_type": "text",
787 | "id": "6A3Ni64joyab"
788 | },
789 | "source": [
790 | "## Checkpoint"
791 | ]
792 | },
793 | {
794 | "cell_type": "code",
795 | "metadata": {
796 | "colab_type": "code",
797 | "id": "PpJAqPMWo0uE",
798 | "colab": {}
799 | },
800 | "source": [
801 | "checkpoint_path = \"./checkpoints/train\"\n",
802 | "ckpt = tf.train.Checkpoint(encoder=encoder,\n",
803 | " decoder=decoder,\n",
804 | " optimizer = optimizer)\n",
805 | "ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)"
806 | ],
807 | "execution_count": null,
808 | "outputs": []
809 | },
810 | {
811 | "cell_type": "code",
812 | "metadata": {
813 | "colab_type": "code",
814 | "id": "fUkbqhc_uObw",
815 | "colab": {}
816 | },
817 | "source": [
818 | "start_epoch = 0\n",
819 | "if ckpt_manager.latest_checkpoint:\n",
820 | " start_epoch = int(ckpt_manager.latest_checkpoint.split('-')[-1])\n",
821 | " # restoring the latest checkpoint in checkpoint_path\n",
822 | " ckpt.restore(ckpt_manager.latest_checkpoint)"
823 | ],
824 | "execution_count": null,
825 | "outputs": []
826 | },
827 | {
828 | "cell_type": "markdown",
829 | "metadata": {
830 | "colab_type": "text",
831 | "id": "PHod7t72RPGn"
832 | },
833 | "source": [
834 | "## Training\n",
835 | "\n",
836 | "* You extract the features stored in the respective `.npy` files and then pass those features through the encoder.\n",
837 | "* The encoder output, hidden state(initialized to 0) and the decoder input (which is the start token) is passed to the decoder.\n",
838 | "* The decoder returns the predictions and the decoder hidden state.\n",
839 | "* The decoder hidden state is then passed back into the model and the predictions are used to calculate the loss.\n",
840 | "* Use teacher forcing to decide the next input to the decoder.\n",
841 | "* Teacher forcing is the technique where the target word is passed as the next input to the decoder.\n",
842 | "* The final step is to calculate the gradients and apply it to the optimizer and backpropagate.\n"
843 | ]
844 | },
845 | {
846 | "cell_type": "code",
847 | "metadata": {
848 | "colab_type": "code",
849 | "id": "Vt4WZ5mhJE-E",
850 | "colab": {}
851 | },
852 | "source": [
853 | "# adding this in a separate cell because if you run the training cell\n",
854 | "# many times, the loss_plot array will be reset\n",
855 | "loss_plot = []"
856 | ],
857 | "execution_count": null,
858 | "outputs": []
859 | },
860 | {
861 | "cell_type": "code",
862 | "metadata": {
863 | "colab_type": "code",
864 | "id": "sqgyz2ANKlpU",
865 | "colab": {}
866 | },
867 | "source": [
868 | "@tf.function\n",
869 | "def train_step(img_tensor, target):\n",
870 | " loss = 0\n",
871 | "\n",
872 | " # initializing the hidden state for each batch\n",
873 | " # because the captions are not related from image to image\n",
874 | " hidden = decoder.reset_state(batch_size=target.shape[0])\n",
875 | "\n",
876 | " dec_input = tf.expand_dims([tokenizer.word_index['']] * target.shape[0], 1)\n",
877 | "\n",
878 | " with tf.GradientTape() as tape:\n",
879 | " features = encoder(img_tensor)\n",
880 | "\n",
881 | " for i in range(1, target.shape[1]):\n",
882 | " # passing the features through the decoder\n",
883 | " predictions, hidden, _ = decoder(dec_input, features, hidden)\n",
884 | "\n",
885 | " loss += loss_function(target[:, i], predictions)\n",
886 | "\n",
887 | " # using teacher forcing\n",
888 | " dec_input = tf.expand_dims(target[:, i], 1)\n",
889 | "\n",
890 | " total_loss = (loss / int(target.shape[1]))\n",
891 | "\n",
892 | " trainable_variables = encoder.trainable_variables + decoder.trainable_variables\n",
893 | "\n",
894 | " gradients = tape.gradient(loss, trainable_variables)\n",
895 | "\n",
896 | " optimizer.apply_gradients(zip(gradients, trainable_variables))\n",
897 | "\n",
898 | " return loss, total_loss"
899 | ],
900 | "execution_count": null,
901 | "outputs": []
902 | },
903 | {
904 | "cell_type": "code",
905 | "metadata": {
906 | "colab_type": "code",
907 | "id": "UlA4VIQpRPGo",
908 | "colab": {}
909 | },
910 | "source": [
911 | "EPOCHS = 20\n",
912 | "\n",
913 | "for epoch in range(start_epoch, EPOCHS):\n",
914 | " start = time.time()\n",
915 | " total_loss = 0\n",
916 | "\n",
917 | " for (batch, (img_tensor, target)) in enumerate(dataset):\n",
918 | " batch_loss, t_loss = train_step(img_tensor, target)\n",
919 | " total_loss += t_loss\n",
920 | "\n",
921 | " if batch % 100 == 0:\n",
922 | " print ('Epoch {} Batch {} Loss {:.4f}'.format(\n",
923 | " epoch + 1, batch, batch_loss.numpy() / int(target.shape[1])))\n",
924 | " # storing the epoch end loss value to plot later\n",
925 | " loss_plot.append(total_loss / num_steps)\n",
926 | "\n",
927 | " if epoch % 5 == 0:\n",
928 | " ckpt_manager.save()\n",
929 | "\n",
930 | " print ('Epoch {} Loss {:.6f}'.format(epoch + 1,\n",
931 | " total_loss/num_steps))\n",
932 | " print ('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))"
933 | ],
934 | "execution_count": null,
935 | "outputs": []
936 | },
937 | {
938 | "cell_type": "code",
939 | "metadata": {
940 | "colab_type": "code",
941 | "id": "1Wm83G-ZBPcC",
942 | "colab": {}
943 | },
944 | "source": [
945 | "plt.plot(loss_plot)\n",
946 | "plt.xlabel('Epochs')\n",
947 | "plt.ylabel('Loss')\n",
948 | "plt.title('Loss Plot')\n",
949 | "plt.show()"
950 | ],
951 | "execution_count": null,
952 | "outputs": []
953 | },
954 | {
955 | "cell_type": "markdown",
956 | "metadata": {
957 | "colab_type": "text",
958 | "id": "xGvOcLQKghXN"
959 | },
960 | "source": [
961 | "## Caption!\n",
962 | "\n",
963 | "* The evaluate function is similar to the training loop, except you don't use teacher forcing here. The input to the decoder at each time step is its previous predictions along with the hidden state and the encoder output.\n",
964 | "* Stop predicting when the model predicts the end token.\n",
965 | "* And store the attention weights for every time step."
966 | ]
967 | },
968 | {
969 | "cell_type": "code",
970 | "metadata": {
971 | "colab_type": "code",
972 | "id": "RCWpDtyNRPGs",
973 | "colab": {}
974 | },
975 | "source": [
976 | "def evaluate(image):\n",
977 | " attention_plot = np.zeros((max_length, attention_features_shape))\n",
978 | "\n",
979 | " hidden = decoder.reset_state(batch_size=1)\n",
980 | "\n",
981 | " temp_input = tf.expand_dims(load_image(image)[0], 0)\n",
982 | " img_tensor_val = image_features_extract_model(temp_input)\n",
983 | " img_tensor_val = tf.reshape(img_tensor_val, (img_tensor_val.shape[0], -1, img_tensor_val.shape[3]))\n",
984 | "\n",
985 | " features = encoder(img_tensor_val)\n",
986 | "\n",
987 | " dec_input = tf.expand_dims([tokenizer.word_index['']], 0)\n",
988 | " result = []\n",
989 | "\n",
990 | " for i in range(max_length):\n",
991 | " predictions, hidden, attention_weights = decoder(dec_input, features, hidden)\n",
992 | "\n",
993 | " attention_plot[i] = tf.reshape(attention_weights, (-1, )).numpy()\n",
994 | "\n",
995 | " predicted_id = tf.random.categorical(predictions, 1)[0][0].numpy()\n",
996 | " result.append(tokenizer.index_word[predicted_id])\n",
997 | "\n",
998 | " if tokenizer.index_word[predicted_id] == '':\n",
999 | " return result, attention_plot\n",
1000 | "\n",
1001 | " dec_input = tf.expand_dims([predicted_id], 0)\n",
1002 | "\n",
1003 | " attention_plot = attention_plot[:len(result), :]\n",
1004 | " return result, attention_plot"
1005 | ],
1006 | "execution_count": null,
1007 | "outputs": []
1008 | },
1009 | {
1010 | "cell_type": "code",
1011 | "metadata": {
1012 | "colab_type": "code",
1013 | "id": "fD_y7PD6RPGt",
1014 | "colab": {}
1015 | },
1016 | "source": [
1017 | "def plot_attention(image, result, attention_plot):\n",
1018 | " temp_image = np.array(Image.open(image))\n",
1019 | "\n",
1020 | " fig = plt.figure(figsize=(10, 10))\n",
1021 | "\n",
1022 | " len_result = len(result)\n",
1023 | " for l in range(len_result):\n",
1024 | " temp_att = np.resize(attention_plot[l], (8, 8))\n",
1025 | " ax = fig.add_subplot(len_result//2, len_result//2, l+1)\n",
1026 | " ax.set_title(result[l])\n",
1027 | " img = ax.imshow(temp_image)\n",
1028 | " ax.imshow(temp_att, cmap='gray', alpha=0.6, extent=img.get_extent())\n",
1029 | "\n",
1030 | " plt.tight_layout()\n",
1031 | " plt.show()"
1032 | ],
1033 | "execution_count": null,
1034 | "outputs": []
1035 | },
1036 | {
1037 | "cell_type": "code",
1038 | "metadata": {
1039 | "colab_type": "code",
1040 | "id": "7x8RiPHe_4qI",
1041 | "colab": {}
1042 | },
1043 | "source": [
1044 | "# captions on the validation set\n",
1045 | "rid = np.random.randint(0, len(img_name_val))\n",
1046 | "image = img_name_val[rid]\n",
1047 | "real_caption = ' '.join([tokenizer.index_word[i] for i in cap_val[rid] if i not in [0]])\n",
1048 | "result, attention_plot = evaluate(image)\n",
1049 | "\n",
1050 | "print ('Real Caption:', real_caption)\n",
1051 | "print ('Prediction Caption:', ' '.join(result))\n",
1052 | "plot_attention(image, result, attention_plot)\n"
1053 | ],
1054 | "execution_count": null,
1055 | "outputs": []
1056 | },
1057 | {
1058 | "cell_type": "markdown",
1059 | "metadata": {
1060 | "colab_type": "text",
1061 | "id": "Rprk3HEvZuxb"
1062 | },
1063 | "source": [
1064 | "## Try it on your own images\n",
1065 | "For fun, below we've provided a method you can use to caption your own images with the model we've just trained. Keep in mind, it was trained on a relatively small amount of data, and your images may be different from the training data (so be prepared for weird results!)\n"
1066 | ]
1067 | },
1068 | {
1069 | "cell_type": "code",
1070 | "metadata": {
1071 | "colab_type": "code",
1072 | "id": "9Psd1quzaAWg",
1073 | "colab": {}
1074 | },
1075 | "source": [
1076 | "image_url = 'https://tensorflow.org/images/surf.jpg'\n",
1077 | "image_extension = image_url[-4:]\n",
1078 | "image_path = tf.keras.utils.get_file('image'+image_extension,\n",
1079 | " origin=image_url)\n",
1080 | "\n",
1081 | "result, attention_plot = evaluate(image_path)\n",
1082 | "print ('Prediction Caption:', ' '.join(result))\n",
1083 | "plot_attention(image_path, result, attention_plot)\n",
1084 | "# opening the image\n",
1085 | "Image.open(image_path)"
1086 | ],
1087 | "execution_count": null,
1088 | "outputs": []
1089 | },
1090 | {
1091 | "cell_type": "markdown",
1092 | "metadata": {
1093 | "colab_type": "text",
1094 | "id": "VJZXyJco6uLO"
1095 | },
1096 | "source": [
1097 | "# Next steps\n",
1098 | "\n",
1099 | "Congrats! You've just trained an image captioning model with attention. Next, take a look at this example [Neural Machine Translation with Attention](../sequences/nmt_with_attention.ipynb). It uses a similar architecture to translate between Spanish and English sentences. You can also experiment with training the code in this notebook on a different dataset."
1100 | ]
1101 | }
1102 | ]
1103 | }
--------------------------------------------------------------------------------
/PAIGCP_text_cleaning.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "PAIGCP_text_cleaning.ipynb",
7 | "provenance": [],
8 | "authorship_tag": "ABX9TyMSP4WgeV5o3jxbRp687qIZ",
9 | "include_colab_link": true
10 | },
11 | "kernelspec": {
12 | "name": "python3",
13 | "display_name": "Python 3"
14 | }
15 | },
16 | "cells": [
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {
20 | "id": "view-in-github",
21 | "colab_type": "text"
22 | },
23 | "source": [
24 | "
"
25 | ]
26 | },
27 | {
28 | "cell_type": "code",
29 | "metadata": {
30 | "id": "DbkMepZnYVHs",
31 | "colab_type": "code",
32 | "colab": {}
33 | },
34 | "source": [
35 | "import urllib.request"
36 | ],
37 | "execution_count": 1,
38 | "outputs": []
39 | },
40 | {
41 | "cell_type": "markdown",
42 | "metadata": {
43 | "id": "SLUJ5DYpY_yH",
44 | "colab_type": "text"
45 | },
46 | "source": [
47 | "Pull down Mody Dick"
48 | ]
49 | },
50 | {
51 | "cell_type": "code",
52 | "metadata": {
53 | "id": "dPyg06asYkY_",
54 | "colab_type": "code",
55 | "colab": {}
56 | },
57 | "source": [
58 | "url = \"https://www.gutenberg.org/files/2701/2701-0.txt\"\n",
59 | "file = urllib.request.urlopen(url)"
60 | ],
61 | "execution_count": 2,
62 | "outputs": []
63 | },
64 | {
65 | "cell_type": "markdown",
66 | "metadata": {
67 | "id": "XFw0-dPOZDCZ",
68 | "colab_type": "text"
69 | },
70 | "source": [
71 | "Load the text"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "metadata": {
77 | "id": "ER0LYVxLYo2k",
78 | "colab_type": "code",
79 | "colab": {
80 | "base_uri": "https://localhost:8080/",
81 | "height": 52
82 | },
83 | "outputId": "755b6782-95fc-4e1e-cccd-9e0b360f4cfb"
84 | },
85 | "source": [
86 | "text = [line.decode('utf-8') for line in file]\n",
87 | "text = ''.join(text)\n",
88 | "text[7600:8000]"
89 | ],
90 | "execution_count": 3,
91 | "outputs": [
92 | {
93 | "output_type": "execute_result",
94 | "data": {
95 | "application/vnd.google.colaboratory.intrinsic+json": {
96 | "type": "string"
97 | },
98 | "text/plain": [
99 | "'ok whatsoever,\\r\\n sacred or profane. Therefore you must not, in every case at least,\\r\\n take the higgledy-piggledy whale statements, however authentic, in\\r\\n these extracts, for veritable gospel cetology. Far from it. As\\r\\n touching the ancient authors generally, as well as the poets here\\r\\n appearing, these extracts are solely valuable or entertaining, as\\r\\n affording a glancing bird’s eye view o'"
100 | ]
101 | },
102 | "metadata": {
103 | "tags": []
104 | },
105 | "execution_count": 3
106 | }
107 | ]
108 | },
109 | {
110 | "cell_type": "markdown",
111 | "metadata": {
112 | "id": "yN2YwlWcY72h",
113 | "colab_type": "text"
114 | },
115 | "source": [
116 | "Tokenize\n"
117 | ]
118 | },
119 | {
120 | "cell_type": "code",
121 | "metadata": {
122 | "id": "WmXGjk_YY9Wc",
123 | "colab_type": "code",
124 | "colab": {
125 | "base_uri": "https://localhost:8080/",
126 | "height": 391
127 | },
128 | "outputId": "b0b21983-ad30-49d5-c573-cf29a8412344"
129 | },
130 | "source": [
131 | "tokens = text.split()\n",
132 | "tokens[200:222]"
133 | ],
134 | "execution_count": 5,
135 | "outputs": [
136 | {
137 | "output_type": "execute_result",
138 | "data": {
139 | "text/plain": [
140 | "['Merry',\n",
141 | " 'Christmas.',\n",
142 | " 'CHAPTER',\n",
143 | " '23.',\n",
144 | " 'The',\n",
145 | " 'Lee',\n",
146 | " 'Shore.',\n",
147 | " 'CHAPTER',\n",
148 | " '24.',\n",
149 | " 'The',\n",
150 | " 'Advocate.',\n",
151 | " 'CHAPTER',\n",
152 | " '25.',\n",
153 | " 'Postscript.',\n",
154 | " 'CHAPTER',\n",
155 | " '26.',\n",
156 | " 'Knights',\n",
157 | " 'and',\n",
158 | " 'Squires.',\n",
159 | " 'CHAPTER',\n",
160 | " '27.',\n",
161 | " 'Knights']"
162 | ]
163 | },
164 | "metadata": {
165 | "tags": []
166 | },
167 | "execution_count": 5
168 | }
169 | ]
170 | },
171 | {
172 | "cell_type": "markdown",
173 | "metadata": {
174 | "id": "GHvzrkUsZUs8",
175 | "colab_type": "text"
176 | },
177 | "source": [
178 | "Lowercase"
179 | ]
180 | },
181 | {
182 | "cell_type": "code",
183 | "metadata": {
184 | "id": "bb2pv0mLZLxV",
185 | "colab_type": "code",
186 | "colab": {
187 | "base_uri": "https://localhost:8080/",
188 | "height": 391
189 | },
190 | "outputId": "b8d5ddd8-06af-4abe-9d8f-1823752c145d"
191 | },
192 | "source": [
193 | "tokens = text.lower().split()\n",
194 | "tokens[200:222]"
195 | ],
196 | "execution_count": 6,
197 | "outputs": [
198 | {
199 | "output_type": "execute_result",
200 | "data": {
201 | "text/plain": [
202 | "['merry',\n",
203 | " 'christmas.',\n",
204 | " 'chapter',\n",
205 | " '23.',\n",
206 | " 'the',\n",
207 | " 'lee',\n",
208 | " 'shore.',\n",
209 | " 'chapter',\n",
210 | " '24.',\n",
211 | " 'the',\n",
212 | " 'advocate.',\n",
213 | " 'chapter',\n",
214 | " '25.',\n",
215 | " 'postscript.',\n",
216 | " 'chapter',\n",
217 | " '26.',\n",
218 | " 'knights',\n",
219 | " 'and',\n",
220 | " 'squires.',\n",
221 | " 'chapter',\n",
222 | " '27.',\n",
223 | " 'knights']"
224 | ]
225 | },
226 | "metadata": {
227 | "tags": []
228 | },
229 | "execution_count": 6
230 | }
231 | ]
232 | },
233 | {
234 | "cell_type": "markdown",
235 | "metadata": {
236 | "id": "zA8tdJU0ZXZC",
237 | "colab_type": "text"
238 | },
239 | "source": [
240 | "Punctuation"
241 | ]
242 | },
243 | {
244 | "cell_type": "code",
245 | "metadata": {
246 | "id": "_qQo2cT7ZZg5",
247 | "colab_type": "code",
248 | "colab": {
249 | "base_uri": "https://localhost:8080/",
250 | "height": 391
251 | },
252 | "outputId": "ee052edb-ccd8-4f12-f0c3-96380698d779"
253 | },
254 | "source": [
255 | "import string\n",
256 | "table = str.maketrans('', '', string.punctuation)\n",
257 | "\n",
258 | "tokens = [w.translate(table) for w in tokens]\n",
259 | "\n",
260 | "tokens[200:222]"
261 | ],
262 | "execution_count": 7,
263 | "outputs": [
264 | {
265 | "output_type": "execute_result",
266 | "data": {
267 | "text/plain": [
268 | "['merry',\n",
269 | " 'christmas',\n",
270 | " 'chapter',\n",
271 | " '23',\n",
272 | " 'the',\n",
273 | " 'lee',\n",
274 | " 'shore',\n",
275 | " 'chapter',\n",
276 | " '24',\n",
277 | " 'the',\n",
278 | " 'advocate',\n",
279 | " 'chapter',\n",
280 | " '25',\n",
281 | " 'postscript',\n",
282 | " 'chapter',\n",
283 | " '26',\n",
284 | " 'knights',\n",
285 | " 'and',\n",
286 | " 'squires',\n",
287 | " 'chapter',\n",
288 | " '27',\n",
289 | " 'knights']"
290 | ]
291 | },
292 | "metadata": {
293 | "tags": []
294 | },
295 | "execution_count": 7
296 | }
297 | ]
298 | },
299 | {
300 | "cell_type": "markdown",
301 | "metadata": {
302 | "id": "2EHfQLMOZoOt",
303 | "colab_type": "text"
304 | },
305 | "source": [
306 | "Alpha only"
307 | ]
308 | },
309 | {
310 | "cell_type": "code",
311 | "metadata": {
312 | "id": "Npw5JfpeZp-2",
313 | "colab_type": "code",
314 | "colab": {
315 | "base_uri": "https://localhost:8080/",
316 | "height": 391
317 | },
318 | "outputId": "b6d7c335-ccea-4f07-dbc1-8d08486ac027"
319 | },
320 | "source": [
321 | "tokens = [word for word in tokens if word.isalpha()]\n",
322 | "tokens[200:222]"
323 | ],
324 | "execution_count": 8,
325 | "outputs": [
326 | {
327 | "output_type": "execute_result",
328 | "data": {
329 | "text/plain": [
330 | "['queen',\n",
331 | " 'mab',\n",
332 | " 'chapter',\n",
333 | " 'cetology',\n",
334 | " 'chapter',\n",
335 | " 'the',\n",
336 | " 'specksnyder',\n",
337 | " 'chapter',\n",
338 | " 'the',\n",
339 | " 'cabintable',\n",
340 | " 'chapter',\n",
341 | " 'the',\n",
342 | " 'masthead',\n",
343 | " 'chapter',\n",
344 | " 'the',\n",
345 | " 'quarterdeck',\n",
346 | " 'chapter',\n",
347 | " 'sunset',\n",
348 | " 'chapter',\n",
349 | " 'dusk',\n",
350 | " 'chapter',\n",
351 | " 'first']"
352 | ]
353 | },
354 | "metadata": {
355 | "tags": []
356 | },
357 | "execution_count": 8
358 | }
359 | ]
360 | }
361 | ]
362 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PAIGCP
2 | Course content for Practical AI on the Google Cloud Platform
3 |
--------------------------------------------------------------------------------