File size: 36,014 Bytes
eec604d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Machine Translation Project (English to French)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import numpy as np\n",
    "import json\n",
    "\n",
    "from keras.preprocessing.text import Tokenizer\n",
    "from keras.utils import pad_sequences\n",
    "from keras.models import Model, Sequential\n",
    "from keras.layers import Input, Dense, Embedding, GRU, LSTM, Bidirectional, Dropout, Activation, TimeDistributed, RepeatVector\n",
    "from keras.optimizers import Adam\n",
    "from keras.losses import sparse_categorical_crossentropy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Verify access to the GPU"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[name: \"/device:CPU:0\"\n",
      "device_type: \"CPU\"\n",
      "memory_limit: 268435456\n",
      "locality {\n",
      "}\n",
      "incarnation: 8951901467623568752\n",
      "xla_global_id: -1\n",
      ", name: \"/device:GPU:0\"\n",
      "device_type: \"GPU\"\n",
      "memory_limit: 1733715559\n",
      "locality {\n",
      "  bus_id: 1\n",
      "  links {\n",
      "  }\n",
      "}\n",
      "incarnation: 7542354691675806642\n",
      "physical_device_desc: \"device: 0, name: NVIDIA GeForce RTX 2050, pci bus id: 0000:01:00.0, compute capability: 8.6\"\n",
      "xla_global_id: 416903419\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "from tensorflow.python.client import device_lib\n",
    "print(device_lib.list_local_devices())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataset\n",
    "For our machine translation project, we opt for a dataset featuring a limited vocabulary, specifically designed to facilitate a more manageable and efficient training process. Unlike the extensive [WMT](http://www.statmt.org/) datasets, our chosen dataset ensures a quicker training time and demands fewer computational resources. This strategic decision aims to balance the learning experience while still achieving meaningful results within practical time constraints.\n",
    "### Load Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_data(path):\n",
    "    input_file = path\n",
    "    with open(input_file, \"r\") as f:\n",
    "        data = f.read()\n",
    "    return data.split('\\n')\n",
    "\n",
    "english_sentences = load_data('data/english')\n",
    "french_sentences = load_data('data/french')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sample Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['new jersey is sometimes quiet during autumn , and it is snowy in april .',\n",
       " 'the united states is usually chilly during july , and it is usually freezing in november .',\n",
       " 'california is usually quiet during march , and it is usually hot in june .',\n",
       " 'the united states is sometimes mild during june , and it is cold in september .',\n",
       " 'your least liked fruit is the grape , but my least liked is the apple .']"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "english_sentences[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By examining the sentences, it's apparent that they have undergone preprocessing: punctuation has been delimited with spaces, and all the text has been converted to lowercase. This preprocessing serves a crucial purpose in text preparation. Firstly, delimiting punctuation with spaces ensures that each punctuation mark is treated as a separate token, aiding the model in understanding sentence structure. Secondly, converting the entire text to lowercase standardizes the input, preventing the model from distinguishing between words solely based on their casing. This uniformity facilitates more effective training and generalization, enhancing the model's ability to grasp patterns and generate accurate translations."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Structure of the Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1823250 English words.\n",
      "227 unique English words.\n",
      "10 Most common words in the English dataset:\n",
      "\"is\" \",\" \".\" \"in\" \"it\" \"during\" \"the\" \"but\" \"and\" \"sometimes\"\n",
      "\n",
      "1961295 French words.\n",
      "355 unique French words.\n",
      "10 Most common words in the French dataset:\n",
      "\"est\" \".\" \",\" \"en\" \"il\" \"les\" \"mais\" \"et\" \"la\" \"parfois\"\n"
     ]
    }
   ],
   "source": [
    "english_words_counter = collections.Counter([word for sentence in english_sentences for word in sentence.split()])\n",
    "french_words_counter = collections.Counter([word for sentence in french_sentences for word in sentence.split()])\n",
    "\n",
    "print('{} English words.'.format(len([word for sentence in english_sentences for word in sentence.split()])))\n",
    "print('{} unique English words.'.format(len(english_words_counter)))\n",
    "print('10 Most common words in the English dataset:')\n",
    "print('\"' + '\" \"'.join(list(zip(*english_words_counter.most_common(10)))[0]) + '\"')\n",
    "\n",
    "print()\n",
    "print('{} French words.'.format(len([word for sentence in french_sentences for word in sentence.split()])))\n",
    "print('{} unique French words.'.format(len(french_words_counter)))\n",
    "print('10 Most common words in the French dataset:')\n",
    "print('\"' + '\" \"'.join(list(zip(*french_words_counter.most_common(10)))[0]) + '\"')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Preprocess\n",
    "1. Tokenize the words into ids\n",
    "2. Add padding to make all the sequences the same length."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'the': 1, 'quick': 2, 'a': 3, 'brown': 4, 'fox': 5, 'jumps': 6, 'over': 7, 'lazy': 8, 'dog': 9, 'by': 10, 'jove': 11, 'my': 12, 'study': 13, 'of': 14, 'lexicography': 15, 'won': 16, 'prize': 17, 'this': 18, 'is': 19, 'short': 20, 'sentence': 21}\n",
      "\n",
      "Sequence 1 in x\n",
      "  Input:  The quick brown fox jumps over the lazy dog .\n",
      "  Output: [1, 2, 4, 5, 6, 7, 1, 8, 9]\n",
      "Sequence 2 in x\n",
      "  Input:  By Jove , my quick study of lexicography won a prize .\n",
      "  Output: [10, 11, 12, 2, 13, 14, 15, 16, 3, 17]\n",
      "Sequence 3 in x\n",
      "  Input:  This is a short sentence .\n",
      "  Output: [18, 19, 3, 20, 21]\n"
     ]
    }
   ],
   "source": [
    "def tokenize(x):\n",
    "    tokenizer = Tokenizer()\n",
    "    tokenizer.fit_on_texts(x)\n",
    "    return tokenizer.texts_to_sequences(x), tokenizer\n",
    "\n",
    "text_sentences = [\n",
    "    'The quick brown fox jumps over the lazy dog .',\n",
    "    'By Jove , my quick study of lexicography won a prize .',\n",
    "    'This is a short sentence .']\n",
    "\n",
    "text_tokenized, text_tokenizer = tokenize(text_sentences)\n",
    "print(text_tokenizer.word_index)\n",
    "print()\n",
    "for sample_i, (sent, token_sent) in enumerate(zip(text_sentences, text_tokenized)):\n",
    "    print('Sequence {} in x'.format(sample_i + 1))\n",
    "    print('  Input:  {}'.format(sent))\n",
    "    print('  Output: {}'.format(token_sent))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sequence 1 in x\n",
      "  Input:  [1 2 4 5 6 7 1 8 9]\n",
      "  Output: [1 2 4 5 6 7 1 8 9 0]\n",
      "Sequence 2 in x\n",
      "  Input:  [10 11 12  2 13 14 15 16  3 17]\n",
      "  Output: [10 11 12  2 13 14 15 16  3 17]\n",
      "Sequence 3 in x\n",
      "  Input:  [18 19  3 20 21]\n",
      "  Output: [18 19  3 20 21  0  0  0  0  0]\n"
     ]
    }
   ],
   "source": [
    "def pad(x, length=None):\n",
    "    if length is None:\n",
    "        length = max([len(sentence) for sentence in x])\n",
    "    return pad_sequences(x, maxlen=length, padding='post')\n",
    "\n",
    "test_pad = pad(text_tokenized)\n",
    "for sample_i, (token_sent, pad_sent) in enumerate(zip(text_tokenized, test_pad)):\n",
    "    print('Sequence {} in x'.format(sample_i + 1))\n",
    "    print('  Input:  {}'.format(np.array(token_sent)))\n",
    "    print('  Output: {}'.format(pad_sent))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data Preprocessed\n",
      "Max English sentence length: 15\n",
      "Max French sentence length: 21\n",
      "English vocabulary size: 199\n",
      "French vocabulary size: 344\n"
     ]
    }
   ],
   "source": [
    "def preprocess(x,y):\n",
    "    preprocess_x, x_tk = tokenize(x)\n",
    "    preprocess_y, y_tk = tokenize(y)\n",
    "    \n",
    "    preprocess_x = pad(preprocess_x)\n",
    "    preprocess_y = pad(preprocess_y)\n",
    "    \n",
    "    preprocess_y = preprocess_y.reshape(*preprocess_y.shape, 1)\n",
    "    \n",
    "    return preprocess_x, preprocess_y, x_tk, y_tk\n",
    "\n",
    "preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer = preprocess(english_sentences, french_sentences)\n",
    "\n",
    "max_english_sequence_length = preproc_english_sentences.shape[1]\n",
    "max_french_sequence_length = preproc_french_sentences.shape[1]\n",
    "english_vocab_size = len(english_tokenizer.word_index)\n",
    "french_vocab_size = len(french_tokenizer.word_index)\n",
    "\n",
    "print('Data Preprocessed')\n",
    "print(\"Max English sentence length:\", max_english_sequence_length)\n",
    "print(\"Max French sentence length:\", max_french_sequence_length)\n",
    "print(\"English vocabulary size:\", english_vocab_size)\n",
    "print(\"French vocabulary size:\", french_vocab_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Models\n",
    "- Model 1 is a simple RNN\n",
    "- Model 2 is a Bidirectional RNN\n",
    "- Model 3 is an Embedding RNN\n",
    "\n",
    "### Ids Back to Text\n",
    "The neural network will be translating the input to words ids, which isn't the final form we want.  We want the French translation.  The function `logits_to_text` will bridge the gab between the logits from the neural network to the French translation.  You'll be using this function to better understand the output of the neural network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def logits_to_text(logits, tokenizer):\n",
    "    index_to_words = {id: word for word, id in tokenizer.word_index.items()}\n",
    "    index_to_words[0] = '<PAD>'\n",
    "    \n",
    "    return ' '.join([index_to_words[prediction] for prediction in np.argmax(logits, 1)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model 1: RNN\n",
    "![RNN](images/rnn.png)\n",
    "A basic RNN model is a good baseline for sequence data.  In this model, you'll build a RNN that translates English to French."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/20\n",
      "108/108 [==============================] - 17s 90ms/step - loss: 1.9094 - accuracy: 0.5446 - val_loss: nan - val_accuracy: 0.6307\n",
      "Epoch 2/20\n",
      "108/108 [==============================] - 9s 84ms/step - loss: 1.2243 - accuracy: 0.6429 - val_loss: nan - val_accuracy: 0.6716\n",
      "Epoch 3/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 1.0848 - accuracy: 0.6683 - val_loss: nan - val_accuracy: 0.6864\n",
      "Epoch 4/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 1.0057 - accuracy: 0.6832 - val_loss: nan - val_accuracy: 0.6927\n",
      "Epoch 5/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.9484 - accuracy: 0.6931 - val_loss: nan - val_accuracy: 0.7108\n",
      "Epoch 6/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.9019 - accuracy: 0.7036 - val_loss: nan - val_accuracy: 0.7007\n",
      "Epoch 7/20\n",
      "108/108 [==============================] - 9s 84ms/step - loss: 0.8916 - accuracy: 0.6999 - val_loss: nan - val_accuracy: 0.7244\n",
      "Epoch 8/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.8407 - accuracy: 0.7178 - val_loss: nan - val_accuracy: 0.7567\n",
      "Epoch 9/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.7807 - accuracy: 0.7405 - val_loss: nan - val_accuracy: 0.7405\n",
      "Epoch 10/20\n",
      "108/108 [==============================] - 9s 84ms/step - loss: 0.7474 - accuracy: 0.7496 - val_loss: nan - val_accuracy: 0.7721\n",
      "Epoch 11/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.7739 - accuracy: 0.7392 - val_loss: nan - val_accuracy: 0.7392\n",
      "Epoch 12/20\n",
      "108/108 [==============================] - 9s 84ms/step - loss: 0.7552 - accuracy: 0.7420 - val_loss: nan - val_accuracy: 0.7851\n",
      "Epoch 13/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.7238 - accuracy: 0.7550 - val_loss: nan - val_accuracy: 0.7937\n",
      "Epoch 14/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.7126 - accuracy: 0.7568 - val_loss: nan - val_accuracy: 0.7830\n",
      "Epoch 15/20\n",
      "108/108 [==============================] - 9s 84ms/step - loss: 0.6838 - accuracy: 0.7650 - val_loss: nan - val_accuracy: 0.7976\n",
      "Epoch 16/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.6577 - accuracy: 0.7776 - val_loss: nan - val_accuracy: 0.7995\n",
      "Epoch 17/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.6447 - accuracy: 0.7821 - val_loss: nan - val_accuracy: 0.8072\n",
      "Epoch 18/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.6309 - accuracy: 0.7858 - val_loss: nan - val_accuracy: 0.8100\n",
      "Epoch 19/20\n",
      "108/108 [==============================] - 9s 84ms/step - loss: 0.6073 - accuracy: 0.7930 - val_loss: nan - val_accuracy: 0.8111\n",
      "Epoch 20/20\n",
      "108/108 [==============================] - 9s 83ms/step - loss: 0.6100 - accuracy: 0.7912 - val_loss: nan - val_accuracy: 0.8150\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x2573cec49a0>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def simple_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n",
    "    \n",
    "    #Hyperparameters\n",
    "    learning_rate = 0.005\n",
    "    \n",
    "    # Build the layers\n",
    "    model = Sequential()\n",
    "    model.add(GRU(256, input_shape=input_shape[1:], return_sequences=True))\n",
    "    model.add(TimeDistributed(Dense(1024, activation='relu')))\n",
    "    model.add(Dropout(0.5))\n",
    "    model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax')))\n",
    "    \n",
    "    # Compile model\n",
    "    model.compile(loss = sparse_categorical_crossentropy,\n",
    "                  optimizer = Adam(learning_rate),\n",
    "                  metrics = ['accuracy'])\n",
    "    \n",
    "    return model\n",
    "\n",
    "tmp_x = pad(preproc_english_sentences, max_french_sequence_length)\n",
    "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n",
    "\n",
    "#Train the neural network\n",
    "simple_rnn_model = simple_model(\n",
    "    tmp_x.shape,\n",
    "    max_french_sequence_length,\n",
    "    english_vocab_size,\n",
    "    french_vocab_size)\n",
    "\n",
    "simple_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=20, validation_split=0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prediciton:\n",
      "1/1 [==============================] - 0s 259ms/step\n",
      "new jersey est parfois calme en mois et il est il est en <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>\n",
      "\n",
      "Correct Translation:\n",
      "[\"new jersey est parfois calme pendant l' automne , et il est neigeux en avril .\"]\n",
      "\n",
      "Original text:\n",
      "['new jersey is sometimes quiet during autumn , and it is snowy in april .']\n"
     ]
    }
   ],
   "source": [
    "# Print prediction(s)\n",
    "print(\"Prediciton:\")\n",
    "print(logits_to_text(simple_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))\n",
    "\n",
    "print(\"\\nCorrect Translation:\")\n",
    "print(french_sentences[:1])\n",
    "\n",
    "print('\\nOriginal text:')\n",
    "print(english_sentences[:1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model 2: Bidirectional RNNs\n",
    "![RNN](images/bidirectional.png)\n",
    "One restriction of a RNN is that it can't see the future input, only the past.  This is where bidirectional recurrent neural networks come in.  They are able to see the future data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_1\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " bidirectional (Bidirectiona  (None, 21, 256)          100608    \n",
      " l)                                                              \n",
      "                                                                 \n",
      " time_distributed_2 (TimeDis  (None, 21, 1024)         263168    \n",
      " tributed)                                                       \n",
      "                                                                 \n",
      " dropout_1 (Dropout)         (None, 21, 1024)          0         \n",
      "                                                                 \n",
      " time_distributed_3 (TimeDis  (None, 21, 344)          352600    \n",
      " tributed)                                                       \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 716,376\n",
      "Trainable params: 716,376\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "None\n",
      "Epoch 1/20\n",
      "108/108 [==============================] - 12s 90ms/step - loss: 1.7553 - accuracy: 0.5756 - val_loss: nan - val_accuracy: 0.6505\n",
      "Epoch 2/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 1.1655 - accuracy: 0.6550 - val_loss: nan - val_accuracy: 0.6802\n",
      "Epoch 3/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 1.0423 - accuracy: 0.6759 - val_loss: nan - val_accuracy: 0.6903\n",
      "Epoch 4/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.9663 - accuracy: 0.6880 - val_loss: nan - val_accuracy: 0.7003\n",
      "Epoch 5/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.9119 - accuracy: 0.6974 - val_loss: nan - val_accuracy: 0.7207\n",
      "Epoch 6/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.8700 - accuracy: 0.7059 - val_loss: nan - val_accuracy: 0.7287\n",
      "Epoch 7/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.8359 - accuracy: 0.7129 - val_loss: nan - val_accuracy: 0.7301\n",
      "Epoch 8/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.8495 - accuracy: 0.7090 - val_loss: nan - val_accuracy: 0.7300\n",
      "Epoch 9/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.8025 - accuracy: 0.7197 - val_loss: nan - val_accuracy: 0.7386\n",
      "Epoch 10/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.7839 - accuracy: 0.7228 - val_loss: nan - val_accuracy: 0.7429\n",
      "Epoch 11/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.7671 - accuracy: 0.7248 - val_loss: nan - val_accuracy: 0.7461\n",
      "Epoch 12/20\n",
      "108/108 [==============================] - 9s 86ms/step - loss: 0.7490 - accuracy: 0.7278 - val_loss: nan - val_accuracy: 0.7487\n",
      "Epoch 13/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.7341 - accuracy: 0.7307 - val_loss: nan - val_accuracy: 0.7473\n",
      "Epoch 14/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.7183 - accuracy: 0.7363 - val_loss: nan - val_accuracy: 0.7614\n",
      "Epoch 15/20\n",
      "108/108 [==============================] - 9s 86ms/step - loss: 0.6998 - accuracy: 0.7427 - val_loss: nan - val_accuracy: 0.7594\n",
      "Epoch 16/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.7086 - accuracy: 0.7361 - val_loss: nan - val_accuracy: 0.7596\n",
      "Epoch 17/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.6889 - accuracy: 0.7424 - val_loss: nan - val_accuracy: 0.7679\n",
      "Epoch 18/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.6780 - accuracy: 0.7493 - val_loss: nan - val_accuracy: 0.7763\n",
      "Epoch 19/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.6625 - accuracy: 0.7535 - val_loss: nan - val_accuracy: 0.7771\n",
      "Epoch 20/20\n",
      "108/108 [==============================] - 9s 85ms/step - loss: 0.6572 - accuracy: 0.7553 - val_loss: nan - val_accuracy: 0.7560\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x2573f78f0a0>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def bd_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n",
    "    \n",
    "    #Hyperparameters\n",
    "    learning_rate = 0.005\n",
    "    \n",
    "    # Build the layers\n",
    "    model = Sequential()\n",
    "    model.add(Bidirectional(GRU(128, return_sequences=True), input_shape=input_shape[1:]))\n",
    "    model.add(TimeDistributed(Dense(1024, activation='relu')))\n",
    "    model.add(Dropout(0.5))\n",
    "    model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax')))\n",
    "    \n",
    "    # Compile model\n",
    "    model.compile(loss = sparse_categorical_crossentropy,\n",
    "                  optimizer = Adam(learning_rate),\n",
    "                  metrics = ['accuracy'])\n",
    "    \n",
    "    return model\n",
    "\n",
    "tmp_x = pad(preproc_english_sentences, max_french_sequence_length)\n",
    "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n",
    "\n",
    "# Train the neural network\n",
    "bd_rnn_model = bd_model(\n",
    "    tmp_x.shape,\n",
    "    max_french_sequence_length,\n",
    "    english_vocab_size,\n",
    "    french_vocab_size)\n",
    "\n",
    "print(bd_rnn_model.summary())\n",
    "\n",
    "bd_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=20, validation_split=0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prediciton:\n",
      "1/1 [==============================] - 1s 544ms/step\n",
      "new jersey est parfois chaud en mois et il et il est en en <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>\n",
      "\n",
      "Correct Translation:\n",
      "[\"new jersey est parfois calme pendant l' automne , et il est neigeux en avril .\"]\n",
      "\n",
      "Original text:\n",
      "['new jersey is sometimes quiet during autumn , and it is snowy in april .']\n"
     ]
    }
   ],
   "source": [
    "# Print prediction(s)\n",
    "print(\"Prediciton:\")\n",
    "print(logits_to_text(bd_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))\n",
    "\n",
    "print(\"\\nCorrect Translation:\")\n",
    "print(french_sentences[:1])\n",
    "\n",
    "print('\\nOriginal text:')\n",
    "print(english_sentences[:1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model 3: Embedding\n",
    "![RNN](images/embedding-words.png)\n",
    "You've turned the words into ids, but there's a better representation of a word.  This is called word embeddings.  An embedding is a vector representation of the word that is close to similar words in n-dimensional space, where the n represents the size of the embedding vectors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_2\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " embedding (Embedding)       (None, 21, 256)           50944     \n",
      "                                                                 \n",
      " bidirectional_1 (Bidirectio  (None, 21, 512)          789504    \n",
      " nal)                                                            \n",
      "                                                                 \n",
      " time_distributed_4 (TimeDis  (None, 21, 1024)         525312    \n",
      " tributed)                                                       \n",
      "                                                                 \n",
      " dropout_2 (Dropout)         (None, 21, 1024)          0         \n",
      "                                                                 \n",
      " time_distributed_5 (TimeDis  (None, 21, 344)          352600    \n",
      " tributed)                                                       \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 1,718,360\n",
      "Trainable params: 1,718,360\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "None\n",
      "Epoch 1/20\n",
      "108/108 [==============================] - 17s 130ms/step - loss: 1.3473 - accuracy: 0.6924 - val_loss: nan - val_accuracy: 0.8697\n",
      "Epoch 2/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.3152 - accuracy: 0.9003 - val_loss: nan - val_accuracy: 0.9346\n",
      "Epoch 3/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.1808 - accuracy: 0.9434 - val_loss: nan - val_accuracy: 0.9578\n",
      "Epoch 4/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.1291 - accuracy: 0.9601 - val_loss: nan - val_accuracy: 0.9702\n",
      "Epoch 5/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.1022 - accuracy: 0.9688 - val_loss: nan - val_accuracy: 0.9737\n",
      "Epoch 6/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0854 - accuracy: 0.9739 - val_loss: nan - val_accuracy: 0.9772\n",
      "Epoch 7/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0763 - accuracy: 0.9767 - val_loss: nan - val_accuracy: 0.9780\n",
      "Epoch 8/20\n",
      "108/108 [==============================] - 14s 127ms/step - loss: 0.0658 - accuracy: 0.9798 - val_loss: nan - val_accuracy: 0.9798\n",
      "Epoch 9/20\n",
      "108/108 [==============================] - 14s 127ms/step - loss: 0.0604 - accuracy: 0.9815 - val_loss: nan - val_accuracy: 0.9816\n",
      "Epoch 10/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0572 - accuracy: 0.9825 - val_loss: nan - val_accuracy: 0.9823\n",
      "Epoch 11/20\n",
      "108/108 [==============================] - 14s 127ms/step - loss: 0.0511 - accuracy: 0.9842 - val_loss: nan - val_accuracy: 0.9836\n",
      "Epoch 12/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0519 - accuracy: 0.9840 - val_loss: nan - val_accuracy: 0.9839\n",
      "Epoch 13/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0494 - accuracy: 0.9850 - val_loss: nan - val_accuracy: 0.9813\n",
      "Epoch 14/20\n",
      "108/108 [==============================] - 14s 127ms/step - loss: 0.0499 - accuracy: 0.9847 - val_loss: nan - val_accuracy: 0.9837\n",
      "Epoch 15/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0471 - accuracy: 0.9856 - val_loss: nan - val_accuracy: 0.9838\n",
      "Epoch 16/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0411 - accuracy: 0.9874 - val_loss: nan - val_accuracy: 0.9843\n",
      "Epoch 17/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0378 - accuracy: 0.9883 - val_loss: nan - val_accuracy: 0.9851\n",
      "Epoch 18/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0368 - accuracy: 0.9886 - val_loss: nan - val_accuracy: 0.9853\n",
      "Epoch 19/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0386 - accuracy: 0.9883 - val_loss: nan - val_accuracy: 0.9845\n",
      "Epoch 20/20\n",
      "108/108 [==============================] - 14s 126ms/step - loss: 0.0459 - accuracy: 0.9863 - val_loss: nan - val_accuracy: 0.9843\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x2573f340d90>"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def bidirectional_embed_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n",
    "    \n",
    "    # Hyperparameters\n",
    "    learning_rate = 0.005\n",
    "    \n",
    "    # Build the layers\n",
    "    model = Sequential()\n",
    "    model.add(Embedding(english_vocab_size, 256, input_length=input_shape[1], input_shape=input_shape[1:]))\n",
    "    model.add(Bidirectional(GRU(256, return_sequences=True)))\n",
    "    model.add(TimeDistributed(Dense(1024, activation='relu')))\n",
    "    model.add(Dropout(0.5))\n",
    "    model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax')))\n",
    "    \n",
    "    # Compile model\n",
    "    model.compile(loss = sparse_categorical_crossentropy,\n",
    "                  optimizer = Adam(learning_rate),\n",
    "                  metrics = ['accuracy'])\n",
    "    \n",
    "    return model\n",
    "\n",
    "tmp_x = pad(preproc_english_sentences, max_french_sequence_length)\n",
    "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2]))\n",
    "\n",
    "# Build the model\n",
    "embed_rnn_model = bidirectional_embed_model(\n",
    "    tmp_x.shape,\n",
    "    max_french_sequence_length,\n",
    "    english_vocab_size,\n",
    "    french_vocab_size)\n",
    "\n",
    "print(embed_rnn_model.summary())\n",
    "\n",
    "embed_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=20, validation_split=0.2)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prediciton:\n",
      "1/1 [==============================] - 0s 410ms/step\n",
      "new jersey est parfois calme pendant l' automne et il est neigeux en avril <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>\n",
      "\n",
      "Correct Translation:\n",
      "[\"new jersey est parfois calme pendant l' automne , et il est neigeux en avril .\"]\n",
      "\n",
      "Original text:\n",
      "['new jersey is sometimes quiet during autumn , and it is snowy in april .']\n"
     ]
    }
   ],
   "source": [
    "# Print prediction(s)\n",
    "print(\"Prediciton:\")\n",
    "print(logits_to_text(embed_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))\n",
    "\n",
    "print(\"\\nCorrect Translation:\")\n",
    "print(french_sentences[:1])\n",
    "\n",
    "print('\\nOriginal text:')\n",
    "print(english_sentences[:1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING:absl:Found untraced functions such as gru_cell_5_layer_call_fn, gru_cell_5_layer_call_and_return_conditional_losses, gru_cell_6_layer_call_fn, gru_cell_6_layer_call_and_return_conditional_losses while saving (showing 4 of 4). These functions will not be directly callable after loading.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: english_to_french_model\\assets\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: english_to_french_model\\assets\n"
     ]
    }
   ],
   "source": [
    "embed_rnn_model.save('english_to_french_model')\n",
    "# Serialize English Tokenizer to JSON\n",
    "with open('english_tokenizer.json', 'w', encoding='utf8') as f:\n",
    "    f.write(json.dumps(english_tokenizer.to_json(), ensure_ascii=False))\n",
    "    \n",
    "# Serialize French Tokenizer to JSON\n",
    "with open('french_tokenizer.json', 'w', encoding='utf8') as f:\n",
    "    f.write(json.dumps(french_tokenizer.to_json(), ensure_ascii=False))\n",
    "    \n",
    "# Save max lengths\n",
    "max_french_sequence_length_json = max_french_sequence_length\n",
    "with open('sequence_length.json', 'w', encoding='utf8') as f:\n",
    "    f.write(json.dumps(max_french_sequence_length_json, ensure_ascii=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}