-
Notifications
You must be signed in to change notification settings - Fork 0
/
dlnd_tv_script_generation.ipynb.json
1707 lines (1707 loc) · 61.1 KB
/
dlnd_tv_script_generation.ipynb.json
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# TV Script Generation\n",
"\n",
"In this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons. The Neural Network you'll build will generate a new ,\"fake\" TV script, based on patterns it recognizes in this training data.\n",
"\n",
"## Get the Data\n",
"\n",
"The data is already provided for you in `./data/Seinfeld_Scripts.txt` and you're encouraged to open that file and look at the text. \n",
">* As a first step, we'll load in this data and look at some samples. \n",
"* Then, you'll be tasked with defining and training an RNN to generate a new script!"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--2019-06-01 21:20:10-- https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5b0dea96_workspace-utils/workspace-utils.py\n",
"Resolving s3.amazonaws.com (s3.amazonaws.com)... 52.216.160.53\n",
"Connecting to s3.amazonaws.com (s3.amazonaws.com)|52.216.160.53|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 1540 (1.5K) []\n",
"Saving to: ‘workspace_utils.py’\n",
"\n",
"workspace_utils.py 100%[===================>] 1.50K --.-KB/s in 0s \n",
"\n",
"2019-06-01 21:20:10 (74.4 MB/s) - ‘workspace_utils.py’ saved [1540/1540]\n",
"\n"
]
}
],
"source": [
"!wget -O workspace_utils.py \"https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5b0dea96_workspace-utils/workspace-utils.py\""
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"# load in data\n",
"import helper\n",
"data_dir = './data/Seinfeld_Scripts.txt'\n",
"text = helper.load_data(data_dir)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Explore the Data\n",
"Play around with `view_line_range` to view different parts of the data. This will give you a sense of the data you'll be working with. You can see, for example, that it is all lowercase text, and each new line of dialogue is separated by a newline character `\\n`."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dataset Stats\n",
"Roughly the number of unique words: 46367\n",
"Number of lines: 109233\n",
"Average number of words in each line: 5.544240293684143\n",
"\n",
"The lines 0 to 10:\n",
"jerry: do you know what this is all about? do you know, why were here? to be out, this is out...and out is one of the single most enjoyable experiences of life. people...did you ever hear people talking about we should go out? this is what theyre talking about...this whole thing, were all out now, no one is home. not one person here is home, were all out! there are people trying to find us, they dont know where we are. (on an imaginary phone) did you ring?, i cant find him. where did he go? he didnt tell me where he was going. he must have gone out. you wanna go out you get ready, you pick out the clothes, right? you take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation...then youre standing around, what do you do? you go we gotta be getting back. once youre out, you wanna get back! you wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right? where ever you are in life, its my feeling, youve gotta go. \n",
"\n",
"jerry: (pointing at georges shirt) see, to me, that button is in the worst possible spot. the second button literally makes or breaks the shirt, look at it. its too high! its in no-mans-land. you look like you live with your mother. \n",
"\n",
"george: are you through? \n",
"\n",
"jerry: you do of course try on, when you buy? \n",
"\n",
"george: yes, it was purple, i liked it, i dont actually recall considering the buttons. \n",
"\n"
]
}
],
"source": [
"view_line_range = (0, 10)\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"import numpy as np\n",
"\n",
"print('Dataset Stats')\n",
"print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\n",
"\n",
"lines = text.split('\\n')\n",
"print('Number of lines: {}'.format(len(lines)))\n",
"word_count_line = [len(line.split()) for line in lines]\n",
"print('Average number of words in each line: {}'.format(np.average(word_count_line)))\n",
"\n",
"print()\n",
"print('The lines {} to {}:'.format(*view_line_range))\n",
"print('\\n'.join(text.split('\\n')[view_line_range[0]:view_line_range[1]]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## Implement Pre-processing Functions\n",
"The first thing to do to any dataset is pre-processing. Implement the following pre-processing functions below:\n",
"- Lookup Table\n",
"- Tokenize Punctuation\n",
"\n",
"### Lookup Table\n",
"To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:\n",
"- Dictionary to go from the words to an id, we'll call `vocab_to_int`\n",
"- Dictionary to go from the id to word, we'll call `int_to_vocab`\n",
"\n",
"Return these dictionaries in the following **tuple** `(vocab_to_int, int_to_vocab)`"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"import problem_unittests as tests\n",
"\n",
"def create_lookup_tables(text):\n",
" \"\"\"\n",
" Create lookup tables for vocabulary\n",
" :param text: The text of tv scripts split into words\n",
" :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n",
" \"\"\"\n",
" # TODO: Implement Function\n",
" word_to_int = {}\n",
" int_to_word = {}\n",
" for i, word in enumerate(set(text)):\n",
" word_to_int[word] = i\n",
" int_to_word[i] = word\n",
" # return tuple\n",
" return (word_to_int, int_to_word)\n",
" #return (None, None)\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_create_lookup_tables(create_lookup_tables)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Tokenize Punctuation\n",
"We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks can create multiple ids for the same word. For example, \"bye\" and \"bye!\" would generate two different word ids.\n",
"\n",
"Implement the function `token_lookup` to return a dict that will be used to tokenize symbols like \"!\" into \"||Exclamation_Mark||\". Create a dictionary for the following symbols where the symbol is the key and value is the token:\n",
"- Period ( **.** )\n",
"- Comma ( **,** )\n",
"- Quotation Mark ( **\"** )\n",
"- Semicolon ( **;** )\n",
"- Exclamation mark ( **!** )\n",
"- Question mark ( **?** )\n",
"- Left Parentheses ( **(** )\n",
"- Right Parentheses ( **)** )\n",
"- Dash ( **-** )\n",
"- Return ( **\\n** )\n",
"\n",
"This dictionary will be used to tokenize the symbols and add the delimiter (space) around it. This separates each symbols as its own word, making it easier for the neural network to predict the next word. Make sure you don't use a value that could be confused as a word; for example, instead of using the value \"dash\", try using something like \"||dash||\"."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def token_lookup():\n",
" \"\"\"\n",
" Generate a dict to turn punctuation into a token.\n",
" :return: Tokenized dictionary where the key is the punctuation and the value is the token\n",
" \"\"\"\n",
" # TODO: Implement Function\n",
" token = {\n",
" '.' : '||Period||',\n",
" ',' : '||Comma||',\n",
" '\"' : '||Quotation_Mark||',\n",
" ';' : '||Semicolon||',\n",
" '!' : '||Exclamation_Mark||',\n",
" '?' : '||Question_Mark||',\n",
" '(' : '||Left_Parentheses||',\n",
" ')' : '||Right_Parentheses||',\n",
" '-' : '||Dash||',\n",
" '\\n': '||Return||'\n",
" }\n",
" return token \n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_tokenize(token_lookup)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Pre-process all the data and save it\n",
"\n",
"Running the code cell below will pre-process all the data and save it to file. You're encouraged to lok at the code for `preprocess_and_save_data` in the `helpers.py` file to see what it's doing in detail, but you do not need to change this code."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"# pre-process training data\n",
"helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Check Point\n",
"This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"import helper\n",
"import problem_unittests as tests\n",
"\n",
"int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Build the Neural Network\n",
"In this section, you'll build the components necessary to build an RNN by implementing the RNN Module and forward and backpropagation functions.\n",
"\n",
"### Check Access to GPU"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"import torch\n",
"\n",
"# Check for a GPU\n",
"train_on_gpu = torch.cuda.is_available()\n",
"if not train_on_gpu:\n",
" print('No GPU found. Please use a GPU to train your neural network.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Input\n",
"Let's start with the preprocessed input data. We'll use [TensorDataset](http://pytorch.org/docs/master/data.html#torch.utils.data.TensorDataset) to provide a known format to our dataset; in combination with [DataLoader](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader), it will handle batching, shuffling, and other dataset iteration functions.\n",
"\n",
"You can create data with TensorDataset by passing in feature and target tensors. Then create a DataLoader as usual.\n",
"```\n",
"data = TensorDataset(feature_tensors, target_tensors)\n",
"data_loader = torch.utils.data.DataLoader(data, \n",
" batch_size=batch_size)\n",
"```\n",
"\n",
"### Batching\n",
"Implement the `batch_data` function to batch `words` data into chunks of size `batch_size` using the `TensorDataset` and `DataLoader` classes.\n",
"\n",
">You can batch words using the DataLoader, but it will be up to you to create `feature_tensors` and `target_tensors` of the correct size and content for a given `sequence_length`.\n",
"\n",
"For example, say we have these as input:\n",
"```\n",
"words = [1, 2, 3, 4, 5, 6, 7]\n",
"sequence_length = 4\n",
"```\n",
"\n",
"Your first `feature_tensor` should contain the values:\n",
"```\n",
"[1, 2, 3, 4]\n",
"```\n",
"And the corresponding `target_tensor` should just be the next \"word\"/tokenized word value:\n",
"```\n",
"5\n",
"```\n",
"This should continue with the second `feature_tensor`, `target_tensor` being:\n",
"```\n",
"[2, 3, 4, 5] # features\n",
"6 # target\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[tensor([[ 2, 3, 4, 5],\n",
" [ 1, 2, 3, 4],\n",
" [ 3, 4, 5, 6]]), tensor([ 6, 5, 7])]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from torch.utils.data import TensorDataset, DataLoader\n",
"\n",
"\n",
"def batch_data(words, sequence_length, batch_size):\n",
" \"\"\"\n",
" Batch the neural network data using DataLoader\n",
" :param words: The word ids of the TV scripts\n",
" :param sequence_length: The sequence length of each batch\n",
" :param batch_size: The size of each batch; the number of sequences in a batch\n",
" :return: DataLoader with batched data\n",
" \"\"\"\n",
" # TODO: Implement function\n",
" # TODO: Implement function \n",
" size = len(words) - sequence_length\n",
" train_x = np.zeros([size, sequence_length])\n",
" train_y = np.zeros(size)\n",
" \n",
" # iterate through the array, one sequence at a time\n",
" for i in range(0, len(words)-sequence_length, 1):\n",
" # The features\n",
" train_x[i] = words[i: i+sequence_length]\n",
" # The targets, shifted by one\n",
" train_y[i] = words[i+sequence_length]\n",
" \n",
" train_x = np.asarray(train_x, np.int64)\n",
" train_y = np.asarray(train_y, np.int64)\n",
" \n",
" # create Tensor datasets\n",
" data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))\n",
" data_loader = DataLoader(data, batch_size=batch_size, shuffle=True) \n",
" \n",
" # return a dataloader\n",
" return data_loader\n",
"\n",
"# there is no test for this function, but you are encouraged to create\n",
"# print statements and tests of your own\n",
"words = [1, 2, 3, 4, 5, 6, 7]\n",
"s_length = 4\n",
"loader = batch_data(np.array(words), s_length, 3)\n",
"\n",
"detaiter = iter(loader)\n",
"detaiter.next()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Test your dataloader \n",
"\n",
"You'll have to modify this code to test a batching function, but it should look fairly similar.\n",
"\n",
"Below, we're generating some test text data and defining a dataloader using the function you defined, above. Then, we are getting some sample batch of inputs `sample_x` and targets `sample_y` from our dataloader.\n",
"\n",
"Your code should return something like the following (likely in a different order, if you shuffled your data):\n",
"\n",
"```\n",
"torch.Size([10, 5])\n",
"tensor([[ 28, 29, 30, 31, 32],\n",
" [ 21, 22, 23, 24, 25],\n",
" [ 17, 18, 19, 20, 21],\n",
" [ 34, 35, 36, 37, 38],\n",
" [ 11, 12, 13, 14, 15],\n",
" [ 23, 24, 25, 26, 27],\n",
" [ 6, 7, 8, 9, 10],\n",
" [ 38, 39, 40, 41, 42],\n",
" [ 25, 26, 27, 28, 29],\n",
" [ 7, 8, 9, 10, 11]])\n",
"\n",
"torch.Size([10])\n",
"tensor([ 33, 26, 22, 39, 16, 28, 11, 43, 30, 12])\n",
"```\n",
"\n",
"### Sizes\n",
"Your sample_x should be of size `(batch_size, sequence_length)` or (10, 5) in this case and sample_y should just have one dimension: batch_size (10). \n",
"\n",
"### Values\n",
"\n",
"You should also notice that the targets, sample_y, are the *next* value in the ordered test_text data. So, for an input sequence `[ 28, 29, 30, 31, 32]` that ends with the value `32`, the corresponding output should be `33`."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"torch.Size([10, 5])\n",
"tensor([[ 15, 16, 17, 18, 19],\n",
" [ 3, 4, 5, 6, 7],\n",
" [ 34, 35, 36, 37, 38],\n",
" [ 44, 45, 46, 47, 48],\n",
" [ 16, 17, 18, 19, 20],\n",
" [ 12, 13, 14, 15, 16],\n",
" [ 9, 10, 11, 12, 13],\n",
" [ 33, 34, 35, 36, 37],\n",
" [ 39, 40, 41, 42, 43],\n",
" [ 6, 7, 8, 9, 10]])\n",
"\n",
"torch.Size([10])\n",
"tensor([ 20, 8, 39, 49, 21, 17, 14, 38, 44, 11])\n"
]
}
],
"source": [
"# test dataloader\n",
"\n",
"test_text = range(50)\n",
"t_loader = batch_data(test_text, sequence_length=5, batch_size=10)\n",
"\n",
"data_iter = iter(t_loader)\n",
"sample_x, sample_y = data_iter.next()\n",
"\n",
"print(sample_x.shape)\n",
"print(sample_x)\n",
"print()\n",
"print(sample_y.shape)\n",
"print(sample_y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## Build the Neural Network\n",
"Implement an RNN using PyTorch's [Module class](http://pytorch.org/docs/master/nn.html#torch.nn.Module). You may choose to use a GRU or an LSTM. To complete the RNN, you'll have to implement the following functions for the class:\n",
" - `__init__` - The initialize function. \n",
" - `init_hidden` - The initialization function for an LSTM/GRU hidden state\n",
" - `forward` - Forward propagation function.\n",
" \n",
"The initialize function should create the layers of the neural network and save them to the class. The forward propagation function will use these layers to run forward propagation and generate an output and a hidden state.\n",
"\n",
"**The output of this model should be the *last* batch of word scores** after a complete sequence has been processed. That is, for each input sequence of words, we only want to output the word scores for a single, most likely, next word.\n",
"\n",
"### Hints\n",
"\n",
"1. Make sure to stack the outputs of the lstm to pass to your fully-connected layer, you can do this with `lstm_output = lstm_output.contiguous().view(-1, self.hidden_dim)`\n",
"2. You can get the last batch of word scores by shaping the output of the final, fully-connected layer like so:\n",
"\n",
"```\n",
"# reshape into (batch_size, seq_length, output_size)\n",
"output = output.view(batch_size, -1, self.output_size)\n",
"# get last batch\n",
"out = output[:, -1]\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"import torch.nn as nn\n",
"\n",
"class RNN(nn.Module):\n",
" \n",
" def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):\n",
" \"\"\"\n",
" Initialize the PyTorch RNN Module\n",
" :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary)\n",
" :param output_size: The number of output dimensions of the neural network\n",
" :param embedding_dim: The size of embeddings, should you choose to use them \n",
" :param hidden_dim: The size of the hidden layer outputs\n",
" :param dropout: dropout to add in between LSTM/GRU layers\n",
" \"\"\"\n",
" super(RNN, self).__init__()\n",
" # TODO: Implement function\n",
" # set class variables\n",
" self.output_size = output_size\n",
" self.n_layers = n_layers\n",
" self.hidden_dim = hidden_dim\n",
" \n",
" self.embedding = nn.Embedding(vocab_size, embedding_dim)\n",
" self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True)\n",
" \n",
" self.fc = nn.Linear(hidden_dim, output_size)\n",
" \n",
" def forward(self, nn_input, hidden):\n",
" \"\"\"\n",
" Forward propagation of the neural network\n",
" :param nn_input: The input to the neural network\n",
" :param hidden: The hidden state \n",
" :return: Two Tensors, the output of the neural network and the latest hidden state\n",
" \"\"\"\n",
" # TODO: Implement function \n",
" batch_size = nn_input.size(0)\n",
"\n",
" # embeddings and lstm_out\n",
" embeds = self.embedding(nn_input)\n",
" lstm_out, hidden = self.lstm(embeds, hidden)\n",
" \n",
" # fully-connected layer\n",
" out = self.fc(lstm_out)\n",
" out = out.view(batch_size, -1, self.output_size)\n",
" out = out[:, -1]\n",
" \n",
" # return one batch of output word scores and the hidden state\n",
" return out, hidden\n",
" \n",
" \n",
" def init_hidden(self, batch_size):\n",
" '''\n",
" Initialize the hidden state of an LSTM/GRU\n",
" :param batch_size: The batch_size of the hidden state\n",
" :return: hidden state of dims (n_layers, batch_size, hidden_dim)\n",
" '''\n",
" # Implement function\n",
" \n",
" # initialize hidden state with zero weights, and move to GPU if available\n",
" weight = next(self.parameters()).data\n",
" \n",
" if (train_on_gpu):\n",
" hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(),\n",
" weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda())\n",
" else:\n",
" hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(),\n",
" weight.new(self.n_layers, batch_size, self.hidden_dim).zero_())\n",
" \n",
" return hidden\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_rnn(RNN, train_on_gpu)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Define forward and backpropagation\n",
"\n",
"Use the RNN class you implemented to apply forward and back propagation. This function will be called, iteratively, in the training loop as follows:\n",
"```\n",
"loss = forward_back_prop(decoder, decoder_optimizer, criterion, inp, target)\n",
"```\n",
"\n",
"And it should return the average loss over a batch and the hidden state returned by a call to `RNN(inp, hidden)`. Recall that you can get this loss by computing it, as usual, and calling `loss.item()`.\n",
"\n",
"**If a GPU is available, you should move your data to that GPU device, here.**"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def forward_back_prop(rnn, optimizer, criterion, inp, target, hidden):\n",
" \"\"\"\n",
" Forward and backward propagation on the neural network\n",
" :param decoder: The PyTorch Module that holds the neural network\n",
" :param decoder_optimizer: The PyTorch optimizer for the neural network\n",
" :param criterion: The PyTorch loss function\n",
" :param inp: A batch of input to the neural network\n",
" :param target: The target output for the batch of input\n",
" :return: The loss and the latest hidden state Tensor\n",
" \"\"\"\n",
" \n",
" # TODO: Implement Function\n",
" \n",
" # move data to GPU, if available\n",
" if(train_on_gpu):\n",
" inp, target = inp.cuda(), target.cuda()\n",
" \n",
" hidden = tuple([each.data for each in hidden])\n",
" \n",
" # perform backpropagation and optimization\n",
" rnn.zero_grad()\n",
" \n",
" output, hidden = rnn(inp, hidden)\n",
" \n",
" loss = criterion(output, target)\n",
" loss.backward()\n",
" \n",
" nn.utils.clip_grad_norm_(rnn.parameters(), 5)\n",
" optimizer.step()\n",
"\n",
" # return the loss over a batch and the hidden state produced by our model\n",
" return loss.item(), hidden\n",
"\n",
"# Note that these tests aren't completely extensive.\n",
"# they are here to act as general checks on the expected outputs of your functions\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_forward_back_prop(RNN, forward_back_prop, train_on_gpu)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Neural Network Training\n",
"\n",
"With the structure of the network complete and data ready to be fed in the neural network, it's time to train it.\n",
"\n",
"### Train Loop\n",
"\n",
"The training loop is implemented for you in the `train_decoder` function. This function will train the network over all the batches for the number of epochs given. The model progress will be shown every number of batches. This number is set with the `show_every_n_batches` parameter. You'll set this parameter along with other parameters in the next section."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"from workspace_utils import active_session\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"\n",
"def train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches=100):\n",
" batch_losses = []\n",
" \n",
" rnn.train()\n",
"\n",
" print(\"Training for %d epoch(s)...\" % n_epochs)\n",
" with active_session():\n",
" for epoch_i in range(1, n_epochs + 1):\n",
" \n",
" # initialize hidden state\n",
" hidden = rnn.init_hidden(batch_size)\n",
" \n",
" for batch_i, (inputs, labels) in enumerate(train_loader, 1):\n",
" \n",
" # make sure you iterate over completely full batches, only\n",
" n_batches = len(train_loader.dataset)//batch_size\n",
" if(batch_i > n_batches):\n",
" break\n",
" \n",
" # forward, back prop\n",
" loss, hidden = forward_back_prop(rnn, optimizer, criterion, inputs, labels, hidden) \n",
" # record loss\n",
" batch_losses.append(loss)\n",
"\n",
" # printing loss stats\n",
" if batch_i % show_every_n_batches == 0:\n",
" print('Epoch: {:>4}/{:<4} Loss: {}\\n'.format(\n",
" epoch_i, n_epochs, np.average(batch_losses)))\n",
" batch_losses = []\n",
"\n",
" # returns a trained rnn\n",
" return rnn"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Hyperparameters\n",
"\n",
"Set and train the neural network with the following parameters:\n",
"- Set `sequence_length` to the length of a sequence.\n",
"- Set `batch_size` to the batch size.\n",
"- Set `num_epochs` to the number of epochs to train for.\n",
"- Set `learning_rate` to the learning rate for an Adam optimizer.\n",
"- Set `vocab_size` to the number of uniqe tokens in our vocabulary.\n",
"- Set `output_size` to the desired size of the output.\n",
"- Set `embedding_dim` to the embedding dimension; smaller than the vocab_size.\n",
"- Set `hidden_dim` to the hidden dimension of your RNN.\n",
"- Set `n_layers` to the number of layers/cells in your RNN.\n",
"- Set `show_every_n_batches` to the number of batches at which the neural network should print progress.\n",
"\n",
"If the network isn't getting the desired results, tweak these parameters and/or the layers in the `RNN` class."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"# Data params\n",
"# Sequence Length\n",
"sequence_length = 10 # of words in a sequence\n",
"# Batch Size\n",
"batch_size = 128\n",
"\n",
"# data loader - do not change\n",
"train_loader = batch_data(int_text, sequence_length, batch_size)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"# Training parameters\n",
"# Number of Epochs\n",
"num_epochs = 20\n",
"# Learning Rate\n",
"learning_rate = 0.001\n",
"\n",
"# Model parameters\n",
"# Vocab size\n",
"vocab_size = len(int_to_vocab)\n",
"# Output size\n",
"output_size = vocab_size\n",
"# Embedding Dimension\n",
"embedding_dim = 100\n",
"# Hidden Dimension\n",
"hidden_dim = 512\n",
"# Number of RNN Layers\n",
"n_layers = 3\n",
"\n",
"# Show stats for every n number of batches\n",
"show_every_n_batches = 500"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Train\n",
"In the next cell, you'll train the neural network on the pre-processed data. If you have a hard time getting a good loss, you may consider changing your hyperparameters. In general, you may get better results with larger hidden and n_layer dimensions, but larger models take a longer time to train. \n",
"> **You should aim for a loss less than 3.5.** \n",
"\n",
"You should also experiment with different sequence lengths, which determine the size of the long range dependencies that a model can learn."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Training for 20 epoch(s)...\n",
"Epoch: 1/20 Loss: 5.918743462562561\n",
"\n",
"Epoch: 1/20 Loss: 5.772099603652954\n",
"\n",
"Epoch: 1/20 Loss: 5.435618295669555\n",
"\n",
"Epoch: 1/20 Loss: 4.961533260822296\n",
"\n",
"Epoch: 1/20 Loss: 4.778547787666321\n",
"\n",
"Epoch: 1/20 Loss: 4.656524988174438\n",
"\n",
"Epoch: 1/20 Loss: 4.581083584785461\n",
"\n",
"Epoch: 1/20 Loss: 4.53672585105896\n",
"\n",
"Epoch: 1/20 Loss: 4.4532477259635925\n",
"\n",
"Epoch: 1/20 Loss: 4.42803996181488\n",
"\n",
"Epoch: 1/20 Loss: 4.3850785875320435\n",
"\n",
"Epoch: 1/20 Loss: 4.361739029407501\n",
"\n",
"Epoch: 1/20 Loss: 4.339055198669434\n",
"\n",
"Epoch: 2/20 Loss: 4.251022740414268\n",
"\n",
"Epoch: 2/20 Loss: 4.155552201271057\n",
"\n",
"Epoch: 2/20 Loss: 4.141916169166565\n",
"\n",
"Epoch: 2/20 Loss: 4.138434875011444\n",
"\n",
"Epoch: 2/20 Loss: 4.126246815681458\n",
"\n",
"Epoch: 2/20 Loss: 4.094669606685638\n",
"\n",
"Epoch: 2/20 Loss: 4.091036114692688\n",
"\n",
"Epoch: 2/20 Loss: 4.095439943790436\n",
"\n",
"Epoch: 2/20 Loss: 4.068950582027435\n",
"\n",
"Epoch: 2/20 Loss: 4.094452954769134\n",
"\n",
"Epoch: 2/20 Loss: 4.040277134418488\n",
"\n",
"Epoch: 2/20 Loss: 4.082005407810211\n",
"\n",
"Epoch: 2/20 Loss: 4.0705086078643795\n",
"\n",
"Epoch: 3/20 Loss: 3.957608231573036\n",
"\n",
"Epoch: 3/20 Loss: 3.8926219596862794\n",
"\n",
"Epoch: 3/20 Loss: 3.8614029397964478\n",
"\n",
"Epoch: 3/20 Loss: 3.86249937915802\n",
"\n",
"Epoch: 3/20 Loss: 3.877663541793823\n",
"\n",
"Epoch: 3/20 Loss: 3.884052364826202\n",
"\n",
"Epoch: 3/20 Loss: 3.851079290866852\n",
"\n",
"Epoch: 3/20 Loss: 3.860819251060486\n",
"\n",
"Epoch: 3/20 Loss: 3.849953127861023\n",
"\n",
"Epoch: 3/20 Loss: 3.8462717909812927\n",
"\n",
"Epoch: 3/20 Loss: 3.8536752219200134\n",
"\n",
"Epoch: 3/20 Loss: 3.852174315452576\n",
"\n",
"Epoch: 3/20 Loss: 3.8367164244651795\n",
"\n",
"Epoch: 4/20 Loss: 3.791541559162278\n",
"\n",
"Epoch: 4/20 Loss: 3.678291651725769\n",
"\n",
"Epoch: 4/20 Loss: 3.7065518765449523\n",
"\n",
"Epoch: 4/20 Loss: 3.6851482162475584\n",
"\n",
"Epoch: 4/20 Loss: 3.678934198856354\n",
"\n",
"Epoch: 4/20 Loss: 3.707548828601837\n",
"\n",
"Epoch: 4/20 Loss: 3.7041877965927124\n",
"\n",
"Epoch: 4/20 Loss: 3.720532441139221\n",
"\n",
"Epoch: 4/20 Loss: 3.712341673374176\n",
"\n",
"Epoch: 4/20 Loss: 3.6959442658424377\n",
"\n",
"Epoch: 4/20 Loss: 3.7271562213897704\n",
"\n",
"Epoch: 4/20 Loss: 3.700769513130188\n",
"\n",
"Epoch: 4/20 Loss: 3.765475507259369\n",
"\n",
"Epoch: 5/20 Loss: 3.6520945440258896\n",
"\n",
"Epoch: 5/20 Loss: 3.584222987651825\n",
"\n",
"Epoch: 5/20 Loss: 3.565965784549713\n",
"\n",
"Epoch: 5/20 Loss: 3.5705834374427794\n",
"\n",
"Epoch: 5/20 Loss: 3.5715735549926757\n",
"\n",
"Epoch: 5/20 Loss: 3.5691100163459777\n",
"\n",
"Epoch: 5/20 Loss: 3.583567938327789\n",
"\n",
"Epoch: 5/20 Loss: 3.5868593220710756\n",
"\n",
"Epoch: 5/20 Loss: 3.588245330810547\n",
"\n",
"Epoch: 5/20 Loss: 3.6059749670028687\n",
"\n",
"Epoch: 5/20 Loss: 3.6178996019363403\n",
"\n",
"Epoch: 5/20 Loss: 3.6355547256469727\n",
"\n",
"Epoch: 5/20 Loss: 3.597506148815155\n",
"\n",
"Epoch: 6/20 Loss: 3.545071743344129\n",
"\n",
"Epoch: 6/20 Loss: 3.451103861808777\n",
"\n",
"Epoch: 6/20 Loss: 3.4747545318603517\n",
"\n",
"Epoch: 6/20 Loss: 3.4726830439567564\n",
"\n",
"Epoch: 6/20 Loss: 3.482848666191101\n",
"\n",
"Epoch: 6/20 Loss: 3.4693091192245484\n",
"\n",
"Epoch: 6/20 Loss: 3.4982065329551695\n",
"\n",
"Epoch: 6/20 Loss: 3.5074794573783876\n",
"\n",
"Epoch: 6/20 Loss: 3.5201871967315674\n",
"\n",
"Epoch: 6/20 Loss: 3.5080386419296263\n",
"\n",
"Epoch: 6/20 Loss: 3.533263790607452\n",
"\n",
"Epoch: 6/20 Loss: 3.551649441242218\n",
"\n",
"Epoch: 6/20 Loss: 3.52618469953537\n",
"\n",
"Epoch: 7/20 Loss: 3.443628930947114\n",
"\n",
"Epoch: 7/20 Loss: 3.3765234928131105\n",
"\n",
"Epoch: 7/20 Loss: 3.375647795677185\n",
"\n",
"Epoch: 7/20 Loss: 3.4002633543014524\n",
"\n",
"Epoch: 7/20 Loss: 3.39659779882431\n",
"\n",
"Epoch: 7/20 Loss: 3.411064960002899\n",
"\n",
"Epoch: 7/20 Loss: 3.4132818880081177\n",
"\n",
"Epoch: 7/20 Loss: 3.409409534454346\n",
"\n",
"Epoch: 7/20 Loss: 3.419993821144104\n",
"\n",
"Epoch: 7/20 Loss: 3.421748062610626\n",
"\n",
"Epoch: 7/20 Loss: 3.451345284461975\n",
"\n",