File size: 47,570 Bytes
baa1558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "IZ6SNYq_tVVC"
   },
   "source": [
    "# Intent Classification with BERT\n",
    "\n",
    "This notebook demonstrates the fine-tuning of BERT to perform intent classification.\n",
    "Intent classification tries to map given instructions (sentence in natural language) to a set of predefined intents. \n",
    "\n",
    "## What you will learn\n",
    "\n",
    "- Load data from csv and preprocess it for training and test\n",
    "- Load a BERT model from TensorFlow Hub\n",
    "- Build your own model by combining BERT with a classifier\n",
    "- Train your own model, fine-tuning BERT as part of that\n",
    "- Save your model and use it to recognize the intend of instructions\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2PHBpLPuQdmK"
   },
   "source": [
    "## About BERT\n",
    "\n",
    "[BERT](https://arxiv.org/abs/1810.04805) and other Transformer encoder architectures have been shown to be successful on a variety of tasks in NLP (natural language processing). They compute vector-space representations of natural language that are suitable for use in deep learning models. The BERT family of models uses the Transformer encoder architecture to process each token of input text in the full context of all tokens before and after, hence the name: Bidirectional Encoder Representations from Transformers. \n",
    "\n",
    "BERT models are usually pre-trained on a large corpus of text, then fine-tuned for specific tasks.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "SCjmX4zTCkRK"
   },
   "source": [
    "## Setup\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:07:33.561260Z",
     "iopub.status.busy": "2021-01-13T03:07:33.560567Z",
     "iopub.status.idle": "2021-01-13T03:07:40.852309Z",
     "shell.execute_reply": "2021-01-13T03:07:40.851601Z"
    },
    "id": "_XgTpm9ZxoN9"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "#import shutil\n",
    "import pandas as pd\n",
    "\n",
    "import tensorflow as tf\n",
    "import tensorflow_hub as hub\n",
    "import tensorflow_text as text\n",
    "import seaborn as sns\n",
    "from pylab import rcParams\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "tf.get_logger().setLevel('ERROR')\n",
    "\n",
    "sns.set(style='whitegrid', palette='muted', font_scale=1.2)\n",
    "HAPPY_COLORS_PALETTE = [\"#01BEFE\", \"#FFDD00\", \"#FF7D00\", \"#FF006D\", \"#ADFF02\", \"#8F00FF\"]\n",
    "sns.set_palette(sns.color_palette(HAPPY_COLORS_PALETTE))\n",
    "rcParams['figure.figsize'] = 12, 8\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Access\n",
    "The data contains various user queries categorized into seven intents. It is hosted on [GitHub](https://github.com/snipsco/nlu-benchmark/tree/master/2017-06-custom-intent-engines) and is first presented in [this paper](https://arxiv.org/abs/1805.10190). In the list below the classes and an example for each class is given:\n",
    "\n",
    "* `class`: SearchCreativeWork - `example`:*play hell house song*\n",
    "* `class`: GetWeather - `example`: *is it windy in boston, mb right now*\n",
    "* `class`: BookRestaurant - `example`: *book a restaurant for eight people in six years*\n",
    "* `class`: PlayMusic - `example`: *play the song little robin redbreast*\n",
    "* `class`: AddToPlaylist - `example`: *add step to me to the 50 clásicos playlist*\n",
    "* `class`: RateBook - `example`: *give 6 stars to of mice and men*\n",
    "* `class`: SearchScreeningEvent - `example` : *find fish story*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Data can be downloaded from a Google Drive by applying [gdown](https://pypi.org/project/gdown/). In the following code cells the download is invoked only if the corresponding file, does not yet exist at the corresponding location."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "datafolder=\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainfile=datafolder+\"train.csv\"\n",
    "testfile=datafolder+\"test.csv\"\n",
    "validfile=datafolder+\"valid.csv\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, the downloaded .csv-files for training, validation and test are imported into pandas dataframes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "traindf = pd.read_csv(trainfile)\n",
    "validdf = pd.read_csv(validfile)\n",
    "testdf = pd.read_csv(testfile)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>text</th>\n",
       "      <th>intent</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>listen to westbam alumb allergic on google music</td>\n",
       "      <td>PlayMusic</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>add step to me to the 50 clásicos playlist</td>\n",
       "      <td>AddToPlaylist</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>i give this current textbook a rating value of...</td>\n",
       "      <td>RateBook</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>play the song little robin redbreast</td>\n",
       "      <td>PlayMusic</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>please add iris dement to my playlist this is ...</td>\n",
       "      <td>AddToPlaylist</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                text         intent\n",
       "0   listen to westbam alumb allergic on google music      PlayMusic\n",
       "1         add step to me to the 50 clásicos playlist  AddToPlaylist\n",
       "2  i give this current textbook a rating value of...       RateBook\n",
       "3               play the song little robin redbreast      PlayMusic\n",
       "4  please add iris dement to my playlist this is ...  AddToPlaylist"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "traindf.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Training data contains 13084 instructions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(13084, 2)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "traindf.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainfeatures=traindf.copy()\n",
    "trainlabels=trainfeatures.pop(\"intent\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainfeatures=trainfeatures.values"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Distribution of class-labels in training-data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "#chart = sns.countplot(trainlabels, palette=HAPPY_COLORS_PALETTE)\n",
    "#plt.title(\"Number of texts per intent\")\n",
    "#chart\n",
    "#`chart.set_xticklabels(chart.get_xticklabels(), rotation=30, horizontalalignment='right')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One-Hot-Encoding of class-labels:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import LabelBinarizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "binarizer=LabelBinarizer()\n",
    "trainlabels=binarizer.fit_transform(trainlabels.values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(13084, 7)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trainlabels.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Preprocess test- and validation data in the same way as it has been done for training-data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "testfeatures=testdf.copy()\n",
    "testlabels=testfeatures.pop(\"intent\")\n",
    "validfeatures=validdf.copy()\n",
    "validlabels=validfeatures.pop(\"intent\")\n",
    "\n",
    "testfeatures=testfeatures.values\n",
    "validfeatures=validfeatures.values\n",
    "\n",
    "testlabels=binarizer.transform(testlabels.values)\n",
    "validlabels=binarizer.transform(validlabels.values)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dX8FtlpGJRE6"
   },
   "source": [
    "## Loading models from TensorFlow Hub\n",
    "\n",
    "Here you can choose which BERT model you will load from TensorFlow Hub and fine-tune. There are multiple BERT models available.\n",
    "\n",
    "  - [BERT-Base](https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3), [Uncased](https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3) and [seven more models](https://tfhub.dev/google/collections/bert/1) with trained weights released by the original BERT authors.\n",
    "  - [Small BERTs](https://tfhub.dev/google/collections/bert/1) have the same general architecture but fewer and/or smaller Transformer blocks, which lets you explore tradeoffs between speed, size and quality.\n",
    "  - [ALBERT](https://tfhub.dev/google/collections/albert/1): four different sizes of \"A Lite BERT\" that reduces model size (but not computation time) by sharing parameters between layers.\n",
    "  - [BERT Experts](https://tfhub.dev/google/collections/experts/bert/1): eight models that all have the BERT-base architecture but offer a choice between different pre-training domains, to align more closely with the target task.\n",
    "  - [Electra](https://tfhub.dev/google/collections/electra/1) has the same architecture as BERT (in three different sizes), but gets pre-trained as a discriminator in a set-up that resembles a Generative Adversarial Network (GAN).\n",
    "  - BERT with Talking-Heads Attention and Gated GELU [[base](https://tfhub.dev/tensorflow/talkheads_ggelu_bert_en_base/1), [large](https://tfhub.dev/tensorflow/talkheads_ggelu_bert_en_large/1)] has two improvements to the core of the Transformer architecture.\n",
    "\n",
    "The model documentation on TensorFlow Hub has more details and references to the\n",
    "research literature. Follow the links above, or click on the [`tfhub.dev`](http://tfhub.dev) URL\n",
    "printed after the next cell execution.\n",
    "\n",
    "The suggestion is to start with a Small BERT (with fewer parameters) since they are faster to fine-tune. If you like a small model but with higher accuracy, ALBERT might be your next option. If you want even better accuracy, choose\n",
    "one of the classic BERT sizes or their recent refinements like Electra, Talking Heads, or a BERT Expert.\n",
    "\n",
    "Aside from the models available below, there are [multiple versions](https://tfhub.dev/google/collections/transformer_encoders_text/1) of the models that are larger and can yield even better accuracy but they are too big to be fine-tuned on a single GPU. You will be able to do that on the [Solve GLUE tasks using BERT on a TPU colab](https://www.tensorflow.org/tutorials/text/solve_glue_tasks_using_bert_on_tpu).\n",
    "\n",
    "You'll see in the code below that switching the tfhub.dev URL is enough to try any of these models, because all the differences between them are encapsulated in the SavedModels from TF Hub."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:07.421163Z",
     "iopub.status.busy": "2021-01-13T03:08:07.420022Z",
     "iopub.status.idle": "2021-01-13T03:08:07.423061Z",
     "shell.execute_reply": "2021-01-13T03:08:07.423513Z"
    },
    "id": "y8_ctG55-uTX"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BERT model selected           : https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-512_A-8/1\n",
      "Preprocess model auto-selected: https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2\n"
     ]
    }
   ],
   "source": [
    "bert_model_name = 'small_bert/bert_en_uncased_L-8_H-512_A-8' \n",
    "map_name_to_handle = {\n",
    "    'bert_en_uncased_L-12_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3',\n",
    "    'bert_en_cased_L-12_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_cased_L-12_H-768_A-12/3',\n",
    "    'bert_multi_cased_L-12_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/3',\n",
    "    'small_bert/bert_en_uncased_L-2_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-128_A-2/1',\n",
    "    'small_bert/bert_en_uncased_L-2_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-256_A-4/1',\n",
    "    'small_bert/bert_en_uncased_L-2_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-512_A-8/1',\n",
    "    'small_bert/bert_en_uncased_L-2_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-2_H-768_A-12/1',\n",
    "    'small_bert/bert_en_uncased_L-4_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-128_A-2/1',\n",
    "    'small_bert/bert_en_uncased_L-4_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-256_A-4/1',\n",
    "    'small_bert/bert_en_uncased_L-4_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-512_A-8/1',\n",
    "    'small_bert/bert_en_uncased_L-4_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-768_A-12/1',\n",
    "    'small_bert/bert_en_uncased_L-6_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-6_H-128_A-2/1',\n",
    "    'small_bert/bert_en_uncased_L-6_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-6_H-256_A-4/1',\n",
    "    'small_bert/bert_en_uncased_L-6_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-6_H-512_A-8/1',\n",
    "    'small_bert/bert_en_uncased_L-6_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-6_H-768_A-12/1',\n",
    "    'small_bert/bert_en_uncased_L-8_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-128_A-2/1',\n",
    "    'small_bert/bert_en_uncased_L-8_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-256_A-4/1',\n",
    "    'small_bert/bert_en_uncased_L-8_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-512_A-8/1',\n",
    "    'small_bert/bert_en_uncased_L-8_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-768_A-12/1',\n",
    "    'small_bert/bert_en_uncased_L-10_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-10_H-128_A-2/1',\n",
    "    'small_bert/bert_en_uncased_L-10_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-10_H-256_A-4/1',\n",
    "    'small_bert/bert_en_uncased_L-10_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-10_H-512_A-8/1',\n",
    "    'small_bert/bert_en_uncased_L-10_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-10_H-768_A-12/1',\n",
    "    'small_bert/bert_en_uncased_L-12_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-128_A-2/1',\n",
    "    'small_bert/bert_en_uncased_L-12_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-256_A-4/1',\n",
    "    'small_bert/bert_en_uncased_L-12_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-512_A-8/1',\n",
    "    'small_bert/bert_en_uncased_L-12_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-12_H-768_A-12/1',\n",
    "    'albert_en_base':\n",
    "        'https://tfhub.dev/tensorflow/albert_en_base/2',\n",
    "    'electra_small':\n",
    "        'https://tfhub.dev/google/electra_small/2',\n",
    "    'electra_base':\n",
    "        'https://tfhub.dev/google/electra_base/2',\n",
    "    'experts_pubmed':\n",
    "        'https://tfhub.dev/google/experts/bert/pubmed/2',\n",
    "    'experts_wiki_books':\n",
    "        'https://tfhub.dev/google/experts/bert/wiki_books/2',\n",
    "    'talking-heads_base':\n",
    "        'https://tfhub.dev/tensorflow/talkheads_ggelu_bert_en_base/1',\n",
    "}\n",
    "\n",
    "map_model_to_preprocess = {\n",
    "    'bert_en_uncased_L-12_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'bert_en_cased_L-12_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_cased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-2_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-2_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-2_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-2_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-4_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-4_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-4_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-4_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-6_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-6_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-6_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-6_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-8_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-8_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-8_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-8_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-10_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-10_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-10_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-10_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-12_H-128_A-2':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-12_H-256_A-4':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-12_H-512_A-8':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'small_bert/bert_en_uncased_L-12_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'bert_multi_cased_L-12_H-768_A-12':\n",
    "        'https://tfhub.dev/tensorflow/bert_multi_cased_preprocess/2',\n",
    "    'albert_en_base':\n",
    "        'https://tfhub.dev/tensorflow/albert_en_preprocess/2',\n",
    "    'electra_small':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'electra_base':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'experts_pubmed':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'experts_wiki_books':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "    'talking-heads_base':\n",
    "        'https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/2',\n",
    "}\n",
    "\n",
    "tfhub_handle_encoder = map_name_to_handle[bert_model_name]\n",
    "tfhub_handle_preprocess = map_model_to_preprocess[bert_model_name]\n",
    "\n",
    "print(f'BERT model selected           : {tfhub_handle_encoder}')\n",
    "print(f'Preprocess model auto-selected: {tfhub_handle_preprocess}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "7WrcxxTRDdHi"
   },
   "source": [
    "## The preprocessing model\n",
    "\n",
    "Text inputs need to be transformed to numeric token ids and arranged in several Tensors before being input to BERT. TensorFlow Hub provides a matching preprocessing model for each of the BERT models discussed above, which implements this transformation using TF ops from the TF.text library. It is not necessary to run pure Python code outside your TensorFlow model to preprocess text.\n",
    "\n",
    "The preprocessing model must be the one referenced by the documentation of the BERT model, which you can read at the URL printed above. For BERT models from the drop-down above, the preprocessing model is selected automatically.\n",
    "\n",
    "Note: You will load the preprocessing model into a [hub.KerasLayer](https://www.tensorflow.org/hub/api_docs/python/hub/KerasLayer) to compose your fine-tuned model. This is the preferred API to load a TF2-style SavedModel from TF Hub into a Keras model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:07.428866Z",
     "iopub.status.busy": "2021-01-13T03:08:07.427625Z",
     "iopub.status.idle": "2021-01-13T03:08:10.467605Z",
     "shell.execute_reply": "2021-01-13T03:08:10.468143Z"
    },
    "id": "0SQi-jWd_jzq"
   },
   "outputs": [],
   "source": [
    "bert_preprocess_model = hub.KerasLayer(tfhub_handle_preprocess)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "x4naBiEE_cZX"
   },
   "source": [
    "Let's try the preprocessing model on some text and see the output:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['listen to westbam alumb allergic on google music'], dtype=object)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trainfeatures[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:10.482448Z",
     "iopub.status.busy": "2021-01-13T03:08:10.478061Z",
     "iopub.status.idle": "2021-01-13T03:08:10.652900Z",
     "shell.execute_reply": "2021-01-13T03:08:10.652248Z"
    },
    "id": "r9-zCzJpnuwS"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Keys       : ['input_type_ids', 'input_mask', 'input_word_ids']\n",
      "Shape      : (1, 128)\n",
      "Word Ids   : [  101  4952  2000  2225  3676  2213  2632 25438 27395  2006  8224  2189]\n",
      "Input Mask : [1 1 1 1 1 1 1 1 1 1 1 1]\n",
      "Type Ids   : [0 0 0 0 0 0 0 0 0 0 0 0]\n"
     ]
    }
   ],
   "source": [
    "text_test = trainfeatures[0]\n",
    "text_preprocessed = bert_preprocess_model(text_test)\n",
    "\n",
    "print(f'Keys       : {list(text_preprocessed.keys())}')\n",
    "print(f'Shape      : {text_preprocessed[\"input_word_ids\"].shape}')\n",
    "print(f'Word Ids   : {text_preprocessed[\"input_word_ids\"][0, :12]}')\n",
    "print(f'Input Mask : {text_preprocessed[\"input_mask\"][0, :12]}')\n",
    "print(f'Type Ids   : {text_preprocessed[\"input_type_ids\"][0, :12]}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EqL7ihkN_862"
   },
   "source": [
    "As can be seen, there are 3 outputs from the preprocessing that a BERT model would use (`input_words_id`, `input_mask` and `input_type_ids`).\n",
    "\n",
    "Some other important points:\n",
    "- The input is truncated to 128 tokens. The number of tokens can be customized and you can see more details on the [Solve GLUE tasks using BERT on a TPU colab](https://www.tensorflow.org/tutorials/text/solve_glue_tasks_using_bert_on_tpu).\n",
    "- The `input_type_ids` only have one value (0) because this is a single sentence input. For a multiple sentence input, it would have one number for each input.\n",
    "\n",
    "Since this text preprocessor is a TensorFlow model, It can be included in your model directly."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "DKnLPSEmtp9i"
   },
   "source": [
    "## Using the BERT model\n",
    "\n",
    "Before putting BERT into an own model, let's take a look at its outputs. You will load it from TF Hub and see the returned values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:10.658519Z",
     "iopub.status.busy": "2021-01-13T03:08:10.657556Z",
     "iopub.status.idle": "2021-01-13T03:08:19.674983Z",
     "shell.execute_reply": "2021-01-13T03:08:19.675465Z"
    },
    "id": "tXxYpK8ixL34"
   },
   "outputs": [],
   "source": [
    "bert_model = hub.KerasLayer(tfhub_handle_encoder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:19.682552Z",
     "iopub.status.busy": "2021-01-13T03:08:19.681441Z",
     "iopub.status.idle": "2021-01-13T03:08:20.297383Z",
     "shell.execute_reply": "2021-01-13T03:08:20.297932Z"
    },
    "id": "_OoF9mebuSZc"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loaded BERT: https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-512_A-8/1\n",
      "Pooled Outputs Shape:(1, 512)\n",
      "Pooled Outputs Values:[-0.04969434 -0.16525201 -0.99807066 -0.93279284 -0.6145217  -0.22613084\n",
      " -0.95588505 -0.50678337  0.29122898  0.2631647   0.7982282   0.49405995]\n",
      "Sequence Outputs Shape:(1, 128, 512)\n",
      "Sequence Outputs Values:[[-0.1024768   0.22204846  0.59883934 ... -0.25584042  0.61985433\n",
      "  -0.01822574]\n",
      " [ 0.4550366  -0.57238305  0.5542101  ... -0.28608793  1.3628979\n",
      "   0.9131196 ]\n",
      " [ 0.42473704  0.29045174  0.82693    ...  0.28371704  1.7948036\n",
      "  -0.36674204]\n",
      " ...\n",
      " [-0.46153253  0.02829356  0.51673454 ... -0.15035403  1.4651561\n",
      "   0.6449582 ]\n",
      " [ 0.7110826   1.0848484   0.66065294 ...  0.4794111   0.723307\n",
      "  -0.08312207]\n",
      " [ 0.35558882 -0.3890488   0.5101847  ...  0.19970936  0.86474574\n",
      "   0.12227032]]\n"
     ]
    }
   ],
   "source": [
    "bert_results = bert_model(text_preprocessed)\n",
    "\n",
    "print(f'Loaded BERT: {tfhub_handle_encoder}')\n",
    "print(f'Pooled Outputs Shape:{bert_results[\"pooled_output\"].shape}')\n",
    "print(f'Pooled Outputs Values:{bert_results[\"pooled_output\"][0, :12]}')\n",
    "print(f'Sequence Outputs Shape:{bert_results[\"sequence_output\"].shape}')\n",
    "print(f'Sequence Outputs Values:{bert_results[\"sequence_output\"][0, :12]}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "sm61jDrezAll"
   },
   "source": [
    "The BERT models return a map with 3 important keys: `pooled_output`, `sequence_output`, `encoder_outputs`:\n",
    "\n",
    "- `pooled_output` to represent each input sequence as a whole. The shape is `[batch_size, H]`. You can think of this as an embedding for the entire movie review.\n",
    "- `sequence_output` represents each input token in the context. The shape is `[batch_size, seq_length, H]`. You can think of this as a contextual embedding for every token in the movie review.\n",
    "- `encoder_outputs` are the intermediate activations of the `L` Transformer blocks. `outputs[\"encoder_outputs\"][i]` is a Tensor of shape `[batch_size, seq_length, 1024]` with the outputs of the i-th Transformer block, for `0 <= i < L`. The last value of the list is equal to `sequence_output`.\n",
    "\n",
    "For the fine-tuning you are going to use the `pooled_output` array."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pDNKfAXbDnJH"
   },
   "source": [
    "## Define your model\n",
    "\n",
    "You will create a very simple fine-tuned model, with the preprocessing model, the selected BERT model, one Dense and a Dropout layer.\n",
    "\n",
    "Note: for more information about the base model's input and output you can use just follow the model's url for documentation. Here specifically you don't need to worry about it because the preprocessing model will take care of that for you.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:20.306302Z",
     "iopub.status.busy": "2021-01-13T03:08:20.305016Z",
     "iopub.status.idle": "2021-01-13T03:08:20.307988Z",
     "shell.execute_reply": "2021-01-13T03:08:20.307291Z"
    },
    "id": "aksj743St9ga"
   },
   "outputs": [],
   "source": [
    "def build_classifier_model():\n",
    "  text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text')\n",
    "  preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name='preprocessing')\n",
    "  encoder_inputs = preprocessing_layer(text_input)\n",
    "  encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name='BERT_encoder')\n",
    "  outputs = encoder(encoder_inputs)\n",
    "  net = outputs['pooled_output']\n",
    "  net = tf.keras.layers.Dropout(0.1)(net)\n",
    "  net = tf.keras.layers.Dense(7, activation=None, name='classifier')(net)\n",
    "  return tf.keras.Model(text_input, net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Zs4yhFraBuGQ"
   },
   "source": [
    "Let's check that the model runs with the output of the preprocessing model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:20.317706Z",
     "iopub.status.busy": "2021-01-13T03:08:20.316292Z",
     "iopub.status.idle": "2021-01-13T03:08:27.279676Z",
     "shell.execute_reply": "2021-01-13T03:08:27.279042Z"
    },
    "id": "mGMF8AZcB2Zy"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(\n",
      "[[0.15770487 0.21116826 0.03859028 0.04381749 0.03109054 0.0646299\n",
      "  0.4529987 ]], shape=(1, 7), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "classifier_model = build_classifier_model()\n",
    "bert_raw_result = classifier_model(tf.constant(trainfeatures[0]))\n",
    "print(tf.keras.activations.softmax(bert_raw_result))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ZTUzNV2JE2G3"
   },
   "source": [
    "The output is meaningless, of course, because the model has not been trained yet.\n",
    "\n",
    "Let's take a look at the model's structure."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"model\"\n",
      "__________________________________________________________________________________________________\n",
      " Layer (type)                   Output Shape         Param #     Connected to                     \n",
      "==================================================================================================\n",
      " text (InputLayer)              [(None,)]            0           []                               \n",
      "                                                                                                  \n",
      " preprocessing (KerasLayer)     {'input_type_ids':   0           ['text[0][0]']                   \n",
      "                                (None, 128),                                                      \n",
      "                                 'input_mask': (Non                                               \n",
      "                                e, 128),                                                          \n",
      "                                 'input_word_ids':                                                \n",
      "                                (None, 128)}                                                      \n",
      "                                                                                                  \n",
      " BERT_encoder (KerasLayer)      {'encoder_outputs':  41373185    ['preprocessing[0][0]',          \n",
      "                                 [(None, 128, 512),               'preprocessing[0][1]',          \n",
      "                                 (None, 128, 512),                'preprocessing[0][2]']          \n",
      "                                 (None, 128, 512),                                                \n",
      "                                 (None, 128, 512),                                                \n",
      "                                 (None, 128, 512),                                                \n",
      "                                 (None, 128, 512),                                                \n",
      "                                 (None, 128, 512),                                                \n",
      "                                 (None, 128, 512)],                                               \n",
      "                                 'default': (None,                                                \n",
      "                                512),                                                             \n",
      "                                 'sequence_output':                                               \n",
      "                                 (None, 128, 512),                                                \n",
      "                                 'pooled_output': (                                               \n",
      "                                None, 512)}                                                       \n",
      "                                                                                                  \n",
      " dropout (Dropout)              (None, 512)          0           ['BERT_encoder[0][9]']           \n",
      "                                                                                                  \n",
      " classifier (Dense)             (None, 7)            3591        ['dropout[0][0]']                \n",
      "                                                                                                  \n",
      "==================================================================================================\n",
      "Total params: 41,376,776\n",
      "Trainable params: 41,376,775\n",
      "Non-trainable params: 1\n",
      "__________________________________________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "classifier_model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WbUWoZMwc302"
   },
   "source": [
    "## Model training\n",
    "\n",
    "You now have all the pieces to train a model, including the preprocessing module, BERT encoder, data, and classifier."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WpJ3xcwDT56v"
   },
   "source": [
    "Since this is a non-binary classification problem and the model outputs probabilities, you'll use `losses.CategoricalCrossentropy` loss function.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:27.596402Z",
     "iopub.status.busy": "2021-01-13T03:08:27.595622Z",
     "iopub.status.idle": "2021-01-13T03:08:27.600436Z",
     "shell.execute_reply": "2021-01-13T03:08:27.600889Z"
    },
    "id": "OWPOZE-L3AgE"
   },
   "outputs": [],
   "source": [
    "loss = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n",
    "metrics = tf.metrics.CategoricalAccuracy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "SqlarlpC_v0g"
   },
   "source": [
    "### Loading the BERT model and training\n",
    "\n",
    "Using the `classifier_model` you created earlier, you can compile the model with the loss, metric and optimizer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:27.621858Z",
     "iopub.status.busy": "2021-01-13T03:08:27.621180Z",
     "iopub.status.idle": "2021-01-13T03:08:27.631397Z",
     "shell.execute_reply": "2021-01-13T03:08:27.631841Z"
    },
    "id": "-7GPDhR98jsD"
   },
   "outputs": [],
   "source": [
    "epochs=5\n",
    "optimizer=tf.keras.optimizers.Adam(1e-5)\n",
    "classifier_model.compile(optimizer=optimizer,\n",
    "                         loss=loss,\n",
    "                         metrics=metrics)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CpBuV5j2cS_b"
   },
   "source": [
    "Note: training time will vary depending on the complexity of the BERT model you have selected."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:08:27.636326Z",
     "iopub.status.busy": "2021-01-13T03:08:27.635519Z",
     "iopub.status.idle": "2021-01-13T03:15:50.893395Z",
     "shell.execute_reply": "2021-01-13T03:15:50.893900Z"
    },
    "id": "HtfDFAnN_Neu",
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training model with https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-8_H-512_A-8/1\n",
      "Epoch 1/5\n",
      " 11/409 [..............................] - ETA: 1:40:36 - loss: 1.9467 - categorical_accuracy: 0.2159"
     ]
    }
   ],
   "source": [
    "print(f'Training model with {tfhub_handle_encoder}')\n",
    "history = classifier_model.fit(x=trainfeatures,y=trainlabels,\n",
    "                               validation_data=(validfeatures,validlabels),\n",
    "                               batch_size=32,\n",
    "                               epochs=epochs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "uBthMlTSV8kn"
   },
   "source": [
    "### Evaluate the model\n",
    "\n",
    "Let's see how the model performs. Two values will be returned. Loss (a number which represents the error, lower values are better), and accuracy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:15:50.898967Z",
     "iopub.status.busy": "2021-01-13T03:15:50.898282Z",
     "iopub.status.idle": "2021-01-13T03:16:53.613847Z",
     "shell.execute_reply": "2021-01-13T03:16:53.614285Z"
    },
    "id": "slqB-urBV9sP"
   },
   "outputs": [],
   "source": [
    "loss, accuracy = classifier_model.evaluate(testfeatures,testlabels)\n",
    "\n",
    "print(f'Loss: {loss}')\n",
    "print(f'Accuracy: {accuracy}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "uttWpgmSfzq9"
   },
   "source": [
    "### Plot the accuracy and loss over time\n",
    "\n",
    "Based on the `History` object returned by `model.fit()`. You can plot the training and validation loss for comparison, as well as the training and validation accuracy:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:16:53.641616Z",
     "iopub.status.busy": "2021-01-13T03:16:53.638634Z",
     "iopub.status.idle": "2021-01-13T03:16:53.950276Z",
     "shell.execute_reply": "2021-01-13T03:16:53.950768Z"
    },
    "id": "fiythcODf0xo"
   },
   "outputs": [],
   "source": [
    "history_dict = history.history\n",
    "print(history_dict.keys())\n",
    "\n",
    "acc = history_dict['categorical_accuracy']\n",
    "val_acc = history_dict['val_categorical_accuracy']\n",
    "loss = history_dict['loss']\n",
    "val_loss = history_dict['val_loss']\n",
    "\n",
    "epochs = range(1, len(acc) + 1)\n",
    "fig = plt.figure(figsize=(10, 8))\n",
    "fig.tight_layout()\n",
    "\n",
    "plt.subplot(2, 1, 1)\n",
    "# \"bo\" is for \"blue dot\"\n",
    "plt.plot(epochs, loss, 'r', label='Training loss')\n",
    "# b is for \"solid blue line\"\n",
    "plt.plot(epochs, val_loss, 'b', label='Validation loss')\n",
    "plt.title('Training and validation loss')\n",
    "plt.grid(True)\n",
    "# plt.xlabel('Epochs')\n",
    "plt.ylabel('Loss')\n",
    "plt.legend()\n",
    "\n",
    "plt.subplot(2, 1, 2)\n",
    "plt.plot(epochs, acc, 'r', label='Training acc')\n",
    "plt.plot(epochs, val_acc, 'b', label='Validation acc')\n",
    "plt.title('Training and validation accuracy')\n",
    "plt.grid(True)\n",
    "plt.xlabel('Epochs')\n",
    "plt.ylabel('Accuracy')\n",
    "plt.legend(loc='lower right')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WzJZCo-cf-Jf"
   },
   "source": [
    "In this plot, the red lines represents the training loss and accuracy, and the blue lines are the validation loss and accuracy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "oyTappHTvNCz"
   },
   "source": [
    "Classifying arbitrary instructions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:17:08.070832Z",
     "iopub.status.busy": "2021-01-13T03:17:08.068184Z",
     "iopub.status.idle": "2021-01-13T03:17:08.879352Z",
     "shell.execute_reply": "2021-01-13T03:17:08.878815Z"
    },
    "id": "VBWzH6exlCPS"
   },
   "outputs": [],
   "source": [
    "def print_my_examples(inputs, results):\n",
    "  result_for_printing = \\\n",
    "    [f'input: {inputs[i]:<30} : estimated intent: {results[i]}'\n",
    "                         for i in range(len(inputs))]\n",
    "  print(*result_for_printing, sep='\\n')\n",
    "  print()\n",
    "\n",
    "\n",
    "examples = [\n",
    "    'play a song from U2',  # this is the same sentence tried earlier\n",
    "    'Will it rain tomorrow',\n",
    "    'I like to hear greatist hits from beastie boys',\n",
    "    'I like to book a table for 3 persons',\n",
    "    '5 stars for machines like me'\n",
    "]\n",
    "\n",
    "results = tf.nn.softmax(classifier_model(tf.constant(examples)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "binarizer.classes_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "intents=binarizer.inverse_transform(results.numpy())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-13T03:17:08.070832Z",
     "iopub.status.busy": "2021-01-13T03:17:08.068184Z",
     "iopub.status.idle": "2021-01-13T03:17:08.879352Z",
     "shell.execute_reply": "2021-01-13T03:17:08.878815Z"
    },
    "id": "VBWzH6exlCPS"
   },
   "outputs": [],
   "source": [
    "print_my_examples(examples, intents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "classify_text_with_bert.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3.8.10 ('caesarainl': venv)",
   "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.8.10"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "vscode": {
   "interpreter": {
    "hash": "405f94f3dc67f15d7addffc962b8172d0d4960d3524e541166097ab2d7a328e0"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}