File size: 87,013 Bytes
03287bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8ea54fcd-ef4a-42cb-ae26-cbdc6f6ffc64",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Duct Tape Pipeline\n",
    "To explore how users may interact with interactive visualizations of counterfactuals for evolving the Interactive Model Card, we will need to first find a way to generate counterfactuals based on a given input. We want the user to be able to provide their input and direct the system to generate counterfactuals based on a part of speech that is significant to the model. The system should then provide a data frame of counterfactuals to be used in an interactive visualization. Below is an example wireframe of the experience based on previous research.\n",
    "\n",
    "![wireframe](Assets/VizNLC-Wireframe-example.png)\n",
    "\n",
    "## Goals of this notebook\n",
    "* Clean up the flow in the \"duct tape pipeline\".\n",
    "* See if I can extract the LIME list for visualization"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "736e6375-dd6d-4188-b8b1-92bded2bcd02",
   "metadata": {},
   "source": [
    "## Loading the libraries and models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7f581785-e642-4f74-9f67-06a63820eaf2",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Import the libraries we know we'll need for the Generator.\n",
    "import pandas as pd, spacy, nltk, numpy as np\n",
    "from spacy import displacy\n",
    "from spacy.matcher import Matcher\n",
    "#!python -m spacy download en_core_web_sm\n",
    "nlp = spacy.load(\"en_core_web_md\")\n",
    "lemmatizer = nlp.get_pipe(\"lemmatizer\")\n",
    "\n",
    "#Import the libraries to support the model, predictions, and LIME.\n",
    "from transformers import AutoTokenizer, AutoModelForSequenceClassification, TextClassificationPipeline\n",
    "import lime\n",
    "import torch\n",
    "import torch.nn.functional as F\n",
    "from lime.lime_text import LimeTextExplainer\n",
    "\n",
    "#Import the libraries for generating interactive visualizations.\n",
    "import altair as alt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cbe2b292-e33e-4915-8e61-bba5327fb643",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Defining all necessary variables and instances.\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"distilbert-base-uncased-finetuned-sst-2-english\")\n",
    "model = AutoModelForSequenceClassification.from_pretrained(\"distilbert-base-uncased-finetuned-sst-2-english\")\n",
    "class_names = ['negative', 'positive']\n",
    "explainer = LimeTextExplainer(class_names=class_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "197c3e26-0fdf-49c6-9135-57f1fd55d3e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Defining a Predictor required for LIME to function.\n",
    "def predictor(texts):\n",
    "    outputs = model(**tokenizer(texts, return_tensors=\"pt\", padding=True))\n",
    "    probas = F.softmax(outputs.logits, dim=1).detach().numpy()\n",
    "    return probas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "013af6ac-f7d1-41d2-a601-b0f9a4870815",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Instantiate a matcher and use it to test some patterns.\n",
    "matcher = Matcher(nlp.vocab)\n",
    "pattern = [{\"ENT_TYPE\": {\"IN\":[\"NORP\",\"GPE\"]}}]\n",
    "matcher.add(\"proper_noun\", [pattern])\n",
    "pattern_test = [{\"DEP\": \"amod\"},{\"DEP\":\"attr\"},{\"TEXT\":\"-\"},{\"DEP\":\"attr\",\"OP\":\"+\"}]\n",
    "matcher.add(\"amod_attr\",[pattern_test])\n",
    "pattern_an = [{\"DEP\": \"amod\"},{\"POS\":{\"IN\":[\"NOUN\",\"PROPN\"]}},{\"DEP\":{\"NOT_IN\":[\"attr\"]}}]\n",
    "matcher.add(\"amod_noun\", [pattern_an])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f6ac821d-7b56-446e-b9ca-42a5f5afd198",
   "metadata": {},
   "outputs": [],
   "source": [
    "def match_this(matcher, doc):\n",
    "    matches = matcher(doc)\n",
    "    for match_id, start, end in matches:\n",
    "        matched_span = doc[start:end]\n",
    "        print(f\"Mached {matched_span.text} by the rule {nlp.vocab.strings[match_id]}.\")\n",
    "    return matches"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c23d48c4-f5ab-4428-9244-0786e9903a8e",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Building the Duct-Tape Pipeline cell-by-cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a373fc00-401a-4def-9f09-de73d485ac13",
   "metadata": {},
   "outputs": [],
   "source": [
    "gender = [\"man\", \"woman\",\"girl\",\"boy\",\"male\",\"female\",\"husband\",\"wife\",\"girlfriend\",\"boyfriend\",\"brother\",\"sister\",\"aunt\",\"uncle\",\"grandma\",\"grandpa\",\"granny\",\"granps\",\"grandmother\",\"grandfather\",\"mama\",\"dada\",\"Ma\",\"Pa\",\"lady\",\"gentleman\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8b02a5d4-8a6b-4e5e-8f15-4f9182fe341f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def select_crit(document, options=False, limelist=False):\n",
    "    '''This function is meant to select the critical part of a sentence. Critical, in this context means\n",
    "    the part of the sentence that is either: A) a PROPN from the correct entity group; B) an ADJ associated with a NOUN;\n",
    "    C) a NOUN that represents gender. It also checks this against what the model thinks is important if the user defines \"options\" as \"LIME\" or True.'''\n",
    "    chunks = list(document.noun_chunks)\n",
    "    pos_options = []\n",
    "    lime_options = []\n",
    "    \n",
    "    #Identify what the model cares about.\n",
    "    if options:\n",
    "        exp = explainer.explain_instance(document.text, predictor, num_features=15, num_samples=2000)\n",
    "        lime_results = exp.as_list()\n",
    "        #prints the results from lime for QA.\n",
    "        if limelist == True:\n",
    "            print(lime_results)\n",
    "        for feature in lime_results:\n",
    "            lime_options.append(feature[0])\n",
    "        lime_results = pd.DataFrame(lime_results, columns=[\"Word\",\"Weight\"])\n",
    "    \n",
    "    #Identify what we care about \"parts of speech\"\n",
    "    for chunk in chunks:\n",
    "        #The use of chunk[-1] is due to testing that it appears to always match the root\n",
    "        root = chunk[-1]\n",
    "        #This currently matches to a list I've created. I don't know the best way to deal with this so I'm leaving it as is for the moment.\n",
    "        if root.text.lower() in gender:\n",
    "            cur_values = [token.text for token in chunk if token.pos_ in [\"NOUN\",\"ADJ\"]]\n",
    "            if (all(elem in lime_options for elem in cur_values) and ((options == \"LIME\") or (options == True))) or ((options != \"LIME\") and (options != True)):\n",
    "                pos_options.extend(cur_values)\n",
    "                #print(f\"From {chunk.text}, {cur_values} added to pos_options due to gender.\") #for QA\n",
    "        #This is currently set to pick up entities in a particular set of groups (which I recently expanded). Should it just pick up all named entities?\n",
    "        elif root.ent_type_ in [\"GPE\",\"NORP\",\"DATE\",\"EVENT\"]:\n",
    "            cur_values = []\n",
    "            if (len(chunk) > 1) and (chunk[-2].dep_ == \"compound\"):\n",
    "                #creates the compound element of the noun\n",
    "                compound = [x.text for x in chunk if x.dep_ == \"compound\"]\n",
    "                print(f\"This is the contents of {compound} and it is {all(elem in lime_options for elem in compound)} that all elements are present in {lime_options}.\") #for QA\n",
    "                #checks to see all elements in the compound are important to the model or use the compound if not checking importance.\n",
    "                if (all(elem in lime_options for elem in compound) and ((options == \"LIME\") or (options == True))) or ((options != \"LIME\") and (options != True)):\n",
    "                    #creates a span for the entirety of the compound noun and adds it to the list.\n",
    "                    span = -1 * (1 + len(compound))\n",
    "                    pos_options.append(chunk[span:].text)\n",
    "                    cur_values + [token.text for token in chunk if token.pos_ == \"ADJ\"]\n",
    "            else: \n",
    "                cur_values = [token.text for token in chunk if (token.ent_type_ in [\"GPE\",\"NORP\",\"DATE\",\"EVENT\"]) or (token.pos_ == \"ADJ\")]\n",
    "            if (all(elem in lime_options for elem in cur_values) and ((options == \"LIME\") or (options == True))) or ((options != \"LIME\") and (options != True)):\n",
    "                pos_options.extend(cur_values)\n",
    "                print(f\"From {chunk.text}, {cur_values} and {pos_options} added to pos_options due to entity recognition.\") #for QA\n",
    "        elif len(chunk) > 1:\n",
    "            cur_values = [token.text for token in chunk if token.pos_ in [\"NOUN\",\"ADJ\"]]\n",
    "            if (all(elem in lime_options for elem in cur_values) and ((options == \"LIME\") or (options == True))) or ((options != \"LIME\") and (options != True)):\n",
    "                pos_options.extend(cur_values)\n",
    "                print(f\"From {chunk.text}, {cur_values} added to pos_options due to wildcard.\") #for QA\n",
    "        else:\n",
    "            print(f\"No options added for \\'{chunk.text}\\' \")\n",
    "    \n",
    "    \n",
    "    #Return the correct set of options based on user input, defaults to POS for simplicity.\n",
    "    if options == \"LIME\":\n",
    "        return pos_options, lime_results\n",
    "    else:\n",
    "        return pos_options"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d43e202e-64b9-4cea-b117-82492c9ee5f4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "From This film, ['film'] added to pos_options due to wildcard.\n",
      "From Iraq, ['Iraq'] and ['film', 'Iraq'] added to pos_options due to entity recognition.\n"
     ]
    }
   ],
   "source": [
    "#Test to make sure all three options work\n",
    "text4 = \"This film was filmed in Iraq.\"\n",
    "doc4 = nlp(text4)\n",
    "lime4, limedf = select_crit(doc4,options=\"LIME\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a0e55a24-65df-429e-a0cd-8daf91a5d242",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-23e37c16acf34cbead4ebdbe2bddfdb5\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  var VEGA_DEBUG = (typeof VEGA_DEBUG == \"undefined\") ? {} : VEGA_DEBUG;\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-23e37c16acf34cbead4ebdbe2bddfdb5\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-23e37c16acf34cbead4ebdbe2bddfdb5\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.17.0?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function maybeLoadScript(lib, version) {\n",
       "      var key = `${lib.replace(\"-\", \"\")}_version`;\n",
       "      return (VEGA_DEBUG[key] == version) ?\n",
       "        Promise.resolve(paths[lib]) :\n",
       "        new Promise(function(resolve, reject) {\n",
       "          var s = document.createElement('script');\n",
       "          document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "          s.async = true;\n",
       "          s.onload = () => {\n",
       "            VEGA_DEBUG[key] = version;\n",
       "            return resolve(paths[lib]);\n",
       "          };\n",
       "          s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "          s.src = paths[lib];\n",
       "        });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else {\n",
       "      maybeLoadScript(\"vega\", \"5\")\n",
       "        .then(() => maybeLoadScript(\"vega-lite\", \"4.17.0\"))\n",
       "        .then(() => maybeLoadScript(\"vega-embed\", \"6\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300, \"strokeWidth\": 0}, \"axis\": {\"grid\": false}}, \"layer\": [{\"mark\": \"bar\", \"encoding\": {\"color\": {\"field\": \"Weight\", \"legend\": null, \"scale\": {\"domain\": [0], \"range\": \"diverging\", \"scheme\": \"blueorange\", \"type\": \"threshold\"}, \"type\": \"quantitative\"}, \"tooltip\": [{\"field\": \"Word\", \"type\": \"nominal\"}, {\"field\": \"Weight\", \"type\": \"quantitative\"}], \"x\": {\"field\": \"Weight\", \"scale\": {\"domain\": [-1, 1]}, \"type\": \"quantitative\"}, \"y\": {\"axis\": null, \"field\": \"Word\", \"sort\": \"x\", \"type\": \"nominal\"}}, \"title\": \"Importance of individual words\"}, {\"mark\": {\"type\": \"text\", \"align\": \"right\", \"baseline\": \"middle\", \"fill\": \"black\"}, \"encoding\": {\"color\": {\"field\": \"Weight\", \"legend\": null, \"scale\": {\"domain\": [0], \"range\": \"diverging\", \"scheme\": \"blueorange\", \"type\": \"threshold\"}, \"type\": \"quantitative\"}, \"text\": {\"field\": \"Word\", \"type\": \"nominal\"}, \"tooltip\": [{\"field\": \"Word\", \"type\": \"nominal\"}, {\"field\": \"Weight\", \"type\": \"quantitative\"}], \"x\": {\"field\": \"Weight\", \"scale\": {\"domain\": [-1, 1]}, \"type\": \"quantitative\"}, \"y\": {\"axis\": null, \"field\": \"Word\", \"sort\": \"x\", \"type\": \"nominal\"}}, \"title\": \"Importance of individual words\"}], \"data\": {\"name\": \"data-1b001587c028498e70538ed310063e51\"}, \"width\": 300, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.17.0.json\", \"datasets\": {\"data-1b001587c028498e70538ed310063e51\": [{\"Word\": \"Iraq\", \"Weight\": -0.9358529031331603}, {\"Word\": \"was\", \"Weight\": -0.0358845002692577}, {\"Word\": \"in\", \"Weight\": -0.017416213388210394}, {\"Word\": \"filmed\", \"Weight\": 0.00802450706528586}, {\"Word\": \"film\", \"Weight\": 0.0077573875142285895}, {\"Word\": \"This\", \"Weight\": 0.0031263867499817305}]}}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.LayerChart(...)"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "single_nearest = alt.selection_single(on='mouseover', nearest=True)\n",
    "viz = alt.Chart(limedf).encode(\n",
    "    alt.X('Weight:Q', scale=alt.Scale(domain=(-1, 1))),\n",
    "    alt.Y('Word:N', sort='x', axis=None),\n",
    "    color=alt.Color(\"Weight\", scale=alt.Scale(scheme='blueorange', domain=[0], type=\"threshold\", range='diverging'), legend=None),\n",
    "    tooltip = (\"Word\",\"Weight\")\n",
    ").mark_bar().properties(title =\"Importance of individual words\")\n",
    "\n",
    "text = viz.mark_text(\n",
    "    fill=\"black\",\n",
    "    align='right',\n",
    "    baseline='middle'\n",
    ").encode(\n",
    "    text='Word:N'\n",
    ")\n",
    "limeplot = alt.LayerChart(layer=[viz,text], width = 300).configure_axis(grid=False).configure_view(strokeWidth=0)\n",
    "limeplot"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf0512b6-336e-4842-9bde-34e03a1ca7c6",
   "metadata": {},
   "source": [
    "### Testing predictions and visualization\n",
    "Here I will attempt to import the model from huggingface, generate predictions for each of the sentences, and then visualize those predictions into a dot plot. If I can get this to work then I will move on to testing a full pipeline for letting the user pick which part of the sentence they wish to generate counterfactuals for."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "74c639bb-e74a-4a46-8047-3552265ae6a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Discovering that there's a pipeline specifically to provide scores. \n",
    "#I used it to get a list of lists of dictionaries that I can then manipulate to calculate the proper prediction score.\n",
    "pipe = TextClassificationPipeline(model=model, tokenizer=tokenizer, return_all_scores=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "8726a284-99bd-47f1-9756-1c3ae603db10",
   "metadata": {},
   "outputs": [],
   "source": [
    "def eval_pred(text):\n",
    "    '''A basic function for evaluating the prediction from the model and turning it into a visualization friendly number.'''\n",
    "    preds = pipe(text)\n",
    "    neg_score = preds[0][0]['score']\n",
    "    pos_score = preds[0][1]['score']\n",
    "    if pos_score >= neg_score:\n",
    "        return pos_score\n",
    "    if neg_score >= pos_score:\n",
    "        return -1 * neg_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "f38f5061-f30a-4c81-9465-37951c3ad9f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def eval_pred_test(text, return_all = False):\n",
    "    '''A basic function for evaluating the prediction from the model and turning it into a visualization friendly number.'''\n",
    "    preds = pipe(text)\n",
    "    neg_score = -1 * preds[0][0]['score']\n",
    "    sent_neg = preds[0][0]['label']\n",
    "    pos_score = preds[0][1]['score']\n",
    "    sent_pos = preds[0][1]['label']\n",
    "    prediction = 0\n",
    "    sentiment = ''\n",
    "    if pos_score > abs(neg_score):\n",
    "        prediction = pos_score\n",
    "        sentiment = sent_pos\n",
    "    elif abs(neg_score) > pos_score:\n",
    "        prediction = neg_score\n",
    "        sentiment = sent_neg\n",
    "        \n",
    "    if return_all:\n",
    "        return prediction, sentiment\n",
    "    else:\n",
    "        return prediction"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b349a87-fe83-4045-a63a-d054489bb461",
   "metadata": {},
   "source": [
    "## Load the dummy countries I created to test generating counterfactuals\n",
    "I decided to test the pipeline with a known problem space. Taking the text from Aurélien Géron's observations in twitter, I built a built a small scale test using the learnings I had to prove that we can identify a particular part of speech, use it to generate counterfactuals, and then build a visualization off it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "46ab3332-964c-449f-8cef-a9ff7df397a4",
   "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>Country</th>\n",
       "      <th>Continent</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Algeria</td>\n",
       "      <td>Africa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Angola</td>\n",
       "      <td>Africa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Benin</td>\n",
       "      <td>Africa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Botswana</td>\n",
       "      <td>Africa</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Burkina</td>\n",
       "      <td>Africa</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    Country Continent\n",
       "0   Algeria    Africa\n",
       "1    Angola    Africa\n",
       "2     Benin    Africa\n",
       "3  Botswana    Africa\n",
       "4   Burkina    Africa"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#load my test data from https://github.com/dbouquin/IS_608/blob/master/NanosatDB_munging/Countries-Continents.csv\n",
    "df = pd.read_csv(\"Assets/Countries/countries.csv\")\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "51c75894-80af-4625-8ce8-660e500b496b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "From This film, ['film'] added to pos_options due to wildcard.\n",
      "From Iraq, ['Iraq'] and ['film', 'Iraq'] added to pos_options due to entity recognition.\n",
      "['film', 'Iraq']\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Iraq'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Note: we will need to build the function that lets the user choose from the options available. For now I have hard coded it as \"selection\", from \"user_options\".\n",
    "user_options = select_crit(doc4)\n",
    "print(user_options)\n",
    "selection = user_options[1]\n",
    "selection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "3d6419f1-bf7d-44bc-afb8-ac26ef9002df",
   "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>Country</th>\n",
       "      <th>Continent</th>\n",
       "      <th>text</th>\n",
       "      <th>prediction</th>\n",
       "      <th>seed</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Algeria</td>\n",
       "      <td>Africa</td>\n",
       "      <td>This film was filmed in Algeria.</td>\n",
       "      <td>0.806454</td>\n",
       "      <td>alternative</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Angola</td>\n",
       "      <td>Africa</td>\n",
       "      <td>This film was filmed in Angola.</td>\n",
       "      <td>-0.775854</td>\n",
       "      <td>alternative</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Benin</td>\n",
       "      <td>Africa</td>\n",
       "      <td>This film was filmed in Benin.</td>\n",
       "      <td>0.962272</td>\n",
       "      <td>alternative</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Botswana</td>\n",
       "      <td>Africa</td>\n",
       "      <td>This film was filmed in Botswana.</td>\n",
       "      <td>0.785837</td>\n",
       "      <td>alternative</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Burkina</td>\n",
       "      <td>Africa</td>\n",
       "      <td>This film was filmed in Burkina.</td>\n",
       "      <td>0.872980</td>\n",
       "      <td>alternative</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    Country Continent                               text  prediction  \\\n",
       "0   Algeria    Africa   This film was filmed in Algeria.    0.806454   \n",
       "1    Angola    Africa    This film was filmed in Angola.   -0.775854   \n",
       "2     Benin    Africa     This film was filmed in Benin.    0.962272   \n",
       "3  Botswana    Africa  This film was filmed in Botswana.    0.785837   \n",
       "4   Burkina    Africa   This film was filmed in Burkina.    0.872980   \n",
       "\n",
       "          seed  \n",
       "0  alternative  \n",
       "1  alternative  \n",
       "2  alternative  \n",
       "3  alternative  \n",
       "4  alternative  "
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Create a function that generates the counterfactuals within a data frame.\n",
    "def gen_cf_country(df,document,selection):\n",
    "    df['text'] = df.Country.apply(lambda x: document.text.replace(selection,x))\n",
    "    df['prediction'] = df.text.apply(eval_pred_test)\n",
    "    #added this because I think it will make the end results better if we ensure the seed is in the data we generate counterfactuals from.\n",
    "    df['seed'] = df.Country.apply(lambda x: 'seed' if x == selection else 'alternative')\n",
    "    return df\n",
    "\n",
    "df = gen_cf_country(df,doc4,selection)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "ecb9dd41-2fab-49bd-bae5-30300ce39e41",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-b04081e2f48148ebbc743fff61e76f2f\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  var VEGA_DEBUG = (typeof VEGA_DEBUG == \"undefined\") ? {} : VEGA_DEBUG;\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-b04081e2f48148ebbc743fff61e76f2f\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-b04081e2f48148ebbc743fff61e76f2f\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.17.0?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function maybeLoadScript(lib, version) {\n",
       "      var key = `${lib.replace(\"-\", \"\")}_version`;\n",
       "      return (VEGA_DEBUG[key] == version) ?\n",
       "        Promise.resolve(paths[lib]) :\n",
       "        new Promise(function(resolve, reject) {\n",
       "          var s = document.createElement('script');\n",
       "          document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "          s.async = true;\n",
       "          s.onload = () => {\n",
       "            VEGA_DEBUG[key] = version;\n",
       "            return resolve(paths[lib]);\n",
       "          };\n",
       "          s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "          s.src = paths[lib];\n",
       "        });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else {\n",
       "      maybeLoadScript(\"vega\", \"5\")\n",
       "        .then(() => maybeLoadScript(\"vega-lite\", \"4.17.0\"))\n",
       "        .then(() => maybeLoadScript(\"vega-embed\", \"6\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"name\": \"data-d6144c20ed1c104065f226d393d7e424\"}, \"mark\": {\"type\": \"circle\", \"opacity\": 0.5}, \"encoding\": {\"color\": {\"field\": \"seed\", \"legend\": {\"title\": \"Seed or Alternative\"}, \"type\": \"nominal\"}, \"size\": {\"field\": \"seed\", \"type\": \"nominal\"}, \"tooltip\": [{\"field\": \"Country\", \"type\": \"nominal\"}, {\"field\": \"prediction\", \"type\": \"quantitative\"}], \"x\": {\"field\": \"Continent\", \"type\": \"nominal\"}, \"y\": {\"field\": \"prediction\", \"type\": \"quantitative\"}}, \"selection\": {\"selector002\": {\"type\": \"single\", \"on\": \"mouseover\", \"nearest\": true}}, \"width\": 300, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.17.0.json\", \"datasets\": {\"data-d6144c20ed1c104065f226d393d7e424\": [{\"Country\": \"Algeria\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Algeria.\", \"prediction\": 0.8064541816711426, \"seed\": \"alternative\"}, {\"Country\": \"Angola\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Angola.\", \"prediction\": -0.7758541703224182, \"seed\": \"alternative\"}, {\"Country\": \"Benin\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Benin.\", \"prediction\": 0.9622722268104553, \"seed\": \"alternative\"}, {\"Country\": \"Botswana\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Botswana.\", \"prediction\": 0.7858365774154663, \"seed\": \"alternative\"}, {\"Country\": \"Burkina\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Burkina.\", \"prediction\": 0.8729804754257202, \"seed\": \"alternative\"}, {\"Country\": \"Burundi\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Burundi.\", \"prediction\": -0.6306232810020447, \"seed\": \"alternative\"}, {\"Country\": \"Cameroon\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Cameroon.\", \"prediction\": 0.5283073782920837, \"seed\": \"alternative\"}, {\"Country\": \"Cape Verde\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Cape Verde.\", \"prediction\": 0.8932027220726013, \"seed\": \"alternative\"}, {\"Country\": \"Central African Republic\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Central African Republic.\", \"prediction\": 0.9326885342597961, \"seed\": \"alternative\"}, {\"Country\": \"Chad\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Chad.\", \"prediction\": 0.788737952709198, \"seed\": \"alternative\"}, {\"Country\": \"Comoros\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Comoros.\", \"prediction\": 0.9623100757598877, \"seed\": \"alternative\"}, {\"Country\": \"Congo\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Congo.\", \"prediction\": 0.6309685707092285, \"seed\": \"alternative\"}, {\"Country\": \"Congo, Democratic Republic of\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Congo, Democratic Republic of.\", \"prediction\": -0.54060298204422, \"seed\": \"alternative\"}, {\"Country\": \"Djibouti\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Djibouti.\", \"prediction\": 0.8894529938697815, \"seed\": \"alternative\"}, {\"Country\": \"Egypt\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Egypt.\", \"prediction\": 0.9648140072822571, \"seed\": \"alternative\"}, {\"Country\": \"Equatorial Guinea\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Equatorial Guinea.\", \"prediction\": 0.6021467447280884, \"seed\": \"alternative\"}, {\"Country\": \"Eritrea\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Eritrea.\", \"prediction\": 0.5404142141342163, \"seed\": \"alternative\"}, {\"Country\": \"Ethiopia\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Ethiopia.\", \"prediction\": 0.7997546195983887, \"seed\": \"alternative\"}, {\"Country\": \"Gabon\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Gabon.\", \"prediction\": -0.8517823219299316, \"seed\": \"alternative\"}, {\"Country\": \"Gambia\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Gambia.\", \"prediction\": -0.5401656031608582, \"seed\": \"alternative\"}, {\"Country\": \"Ghana\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Ghana.\", \"prediction\": 0.9684805870056152, \"seed\": \"alternative\"}, {\"Country\": \"Guinea\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Guinea.\", \"prediction\": 0.6188081502914429, \"seed\": \"alternative\"}, {\"Country\": \"Guinea-Bissau\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Guinea-Bissau.\", \"prediction\": -0.500963032245636, \"seed\": \"alternative\"}, {\"Country\": \"Ivory Coast\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Ivory Coast.\", \"prediction\": 0.9872506856918335, \"seed\": \"alternative\"}, {\"Country\": \"Kenya\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Kenya.\", \"prediction\": 0.9789031744003296, \"seed\": \"alternative\"}, {\"Country\": \"Lesotho\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Lesotho.\", \"prediction\": 0.6674107313156128, \"seed\": \"alternative\"}, {\"Country\": \"Liberia\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Liberia.\", \"prediction\": -0.6720185279846191, \"seed\": \"alternative\"}, {\"Country\": \"Libya\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Libya.\", \"prediction\": 0.53217613697052, \"seed\": \"alternative\"}, {\"Country\": \"Madagascar\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Madagascar.\", \"prediction\": 0.9730344414710999, \"seed\": \"alternative\"}, {\"Country\": \"Malawi\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Malawi.\", \"prediction\": -0.7816339135169983, \"seed\": \"alternative\"}, {\"Country\": \"Mali\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Mali.\", \"prediction\": -0.6651991009712219, \"seed\": \"alternative\"}, {\"Country\": \"Mauritania\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Mauritania.\", \"prediction\": 0.6149344444274902, \"seed\": \"alternative\"}, {\"Country\": \"Mauritius\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Mauritius.\", \"prediction\": 0.9310740828514099, \"seed\": \"alternative\"}, {\"Country\": \"Morocco\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Morocco.\", \"prediction\": 0.9121577143669128, \"seed\": \"alternative\"}, {\"Country\": \"Mozambique\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Mozambique.\", \"prediction\": -0.7047757506370544, \"seed\": \"alternative\"}, {\"Country\": \"Namibia\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Namibia.\", \"prediction\": -0.5836523175239563, \"seed\": \"alternative\"}, {\"Country\": \"Niger\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Niger.\", \"prediction\": -0.6313472390174866, \"seed\": \"alternative\"}, {\"Country\": \"Nigeria\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Nigeria.\", \"prediction\": 0.7361583113670349, \"seed\": \"alternative\"}, {\"Country\": \"Rwanda\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Rwanda.\", \"prediction\": -0.7642565965652466, \"seed\": \"alternative\"}, {\"Country\": \"Sao Tome and Principe\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Sao Tome and Principe.\", \"prediction\": 0.6587044596672058, \"seed\": \"alternative\"}, {\"Country\": \"Senegal\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Senegal.\", \"prediction\": 0.8155898451805115, \"seed\": \"alternative\"}, {\"Country\": \"Seychelles\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Seychelles.\", \"prediction\": 0.8802894949913025, \"seed\": \"alternative\"}, {\"Country\": \"Sierra Leone\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Sierra Leone.\", \"prediction\": 0.9483919143676758, \"seed\": \"alternative\"}, {\"Country\": \"Somalia\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Somalia.\", \"prediction\": -0.6477505564689636, \"seed\": \"alternative\"}, {\"Country\": \"South Africa\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in South Africa.\", \"prediction\": 0.5048943161964417, \"seed\": \"alternative\"}, {\"Country\": \"South Sudan\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in South Sudan.\", \"prediction\": -0.8506219983100891, \"seed\": \"alternative\"}, {\"Country\": \"Sudan\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Sudan.\", \"prediction\": -0.8910807967185974, \"seed\": \"alternative\"}, {\"Country\": \"Swaziland\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Swaziland.\", \"prediction\": 0.7761040925979614, \"seed\": \"alternative\"}, {\"Country\": \"Tanzania\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Tanzania.\", \"prediction\": 0.669053316116333, \"seed\": \"alternative\"}, {\"Country\": \"Togo\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Togo.\", \"prediction\": 0.9404287934303284, \"seed\": \"alternative\"}, {\"Country\": \"Tunisia\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Tunisia.\", \"prediction\": 0.8345948457717896, \"seed\": \"alternative\"}, {\"Country\": \"Uganda\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Uganda.\", \"prediction\": 0.7823328971862793, \"seed\": \"alternative\"}, {\"Country\": \"Zambia\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Zambia.\", \"prediction\": -0.6479448080062866, \"seed\": \"alternative\"}, {\"Country\": \"Zimbabwe\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Zimbabwe.\", \"prediction\": 0.7163158059120178, \"seed\": \"alternative\"}, {\"Country\": \"Afghanistan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Afghanistan.\", \"prediction\": -0.8350331783294678, \"seed\": \"alternative\"}, {\"Country\": \"Bahrain\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Bahrain.\", \"prediction\": 0.9627965092658997, \"seed\": \"alternative\"}, {\"Country\": \"Bangladesh\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Bangladesh.\", \"prediction\": 0.6659616231918335, \"seed\": \"alternative\"}, {\"Country\": \"Bhutan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Bhutan.\", \"prediction\": 0.9108285307884216, \"seed\": \"alternative\"}, {\"Country\": \"Brunei\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Brunei.\", \"prediction\": 0.7673805952072144, \"seed\": \"alternative\"}, {\"Country\": \"Burma (Myanmar)\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Burma (Myanmar).\", \"prediction\": 0.5261574387550354, \"seed\": \"alternative\"}, {\"Country\": \"Cambodia\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Cambodia.\", \"prediction\": 0.9706045389175415, \"seed\": \"alternative\"}, {\"Country\": \"China\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in China.\", \"prediction\": 0.6985915303230286, \"seed\": \"alternative\"}, {\"Country\": \"East Timor\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in East Timor.\", \"prediction\": -0.7553014159202576, \"seed\": \"alternative\"}, {\"Country\": \"India\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in India.\", \"prediction\": 0.9856906533241272, \"seed\": \"alternative\"}, {\"Country\": \"Indonesia\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Indonesia.\", \"prediction\": 0.9617947936058044, \"seed\": \"alternative\"}, {\"Country\": \"Iran\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Iran.\", \"prediction\": 0.935718834400177, \"seed\": \"alternative\"}, {\"Country\": \"Iraq\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Iraq.\", \"prediction\": -0.9768388867378235, \"seed\": \"seed\"}, {\"Country\": \"Israel\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Israel.\", \"prediction\": 0.8940765261650085, \"seed\": \"alternative\"}, {\"Country\": \"Japan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Japan.\", \"prediction\": 0.8561221957206726, \"seed\": \"alternative\"}, {\"Country\": \"Jordan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Jordan.\", \"prediction\": 0.5632433891296387, \"seed\": \"alternative\"}, {\"Country\": \"Kazakhstan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Kazakhstan.\", \"prediction\": 0.8813521862030029, \"seed\": \"alternative\"}, {\"Country\": \"Korea, North\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Korea, North.\", \"prediction\": -0.692742645740509, \"seed\": \"alternative\"}, {\"Country\": \"Korea, South\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Korea, South.\", \"prediction\": 0.7591306567192078, \"seed\": \"alternative\"}, {\"Country\": \"Kuwait\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Kuwait.\", \"prediction\": 0.9136238098144531, \"seed\": \"alternative\"}, {\"Country\": \"Kyrgyzstan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Kyrgyzstan.\", \"prediction\": 0.9416173100471497, \"seed\": \"alternative\"}, {\"Country\": \"Laos\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Laos.\", \"prediction\": 0.7455804347991943, \"seed\": \"alternative\"}, {\"Country\": \"Lebanon\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Lebanon.\", \"prediction\": 0.9018603563308716, \"seed\": \"alternative\"}, {\"Country\": \"Malaysia\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Malaysia.\", \"prediction\": 0.9053533673286438, \"seed\": \"alternative\"}, {\"Country\": \"Maldives\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Maldives.\", \"prediction\": 0.8150556087493896, \"seed\": \"alternative\"}, {\"Country\": \"Mongolia\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Mongolia.\", \"prediction\": 0.9706059098243713, \"seed\": \"alternative\"}, {\"Country\": \"Nepal\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Nepal.\", \"prediction\": 0.9837730526924133, \"seed\": \"alternative\"}, {\"Country\": \"Oman\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Oman.\", \"prediction\": 0.8641175627708435, \"seed\": \"alternative\"}, {\"Country\": \"Pakistan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Pakistan.\", \"prediction\": 0.8881147503852844, \"seed\": \"alternative\"}, {\"Country\": \"Philippines\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Philippines.\", \"prediction\": 0.9892238974571228, \"seed\": \"alternative\"}, {\"Country\": \"Qatar\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Qatar.\", \"prediction\": 0.9696690440177917, \"seed\": \"alternative\"}, {\"Country\": \"Russian Federation\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Russian Federation.\", \"prediction\": 0.9777944087982178, \"seed\": \"alternative\"}, {\"Country\": \"Saudi Arabia\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Saudi Arabia.\", \"prediction\": -0.7760475873947144, \"seed\": \"alternative\"}, {\"Country\": \"Singapore\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Singapore.\", \"prediction\": 0.9684174060821533, \"seed\": \"alternative\"}, {\"Country\": \"Sri Lanka\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Sri Lanka.\", \"prediction\": 0.9552921056747437, \"seed\": \"alternative\"}, {\"Country\": \"Syria\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Syria.\", \"prediction\": -0.8887014985084534, \"seed\": \"alternative\"}, {\"Country\": \"Tajikistan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Tajikistan.\", \"prediction\": 0.8012317419052124, \"seed\": \"alternative\"}, {\"Country\": \"Thailand\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Thailand.\", \"prediction\": 0.8334980607032776, \"seed\": \"alternative\"}, {\"Country\": \"Turkey\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Turkey.\", \"prediction\": 0.5693907141685486, \"seed\": \"alternative\"}, {\"Country\": \"Turkmenistan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Turkmenistan.\", \"prediction\": 0.8194981813430786, \"seed\": \"alternative\"}, {\"Country\": \"United Arab Emirates\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in United Arab Emirates.\", \"prediction\": 0.921615719795227, \"seed\": \"alternative\"}, {\"Country\": \"Uzbekistan\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Uzbekistan.\", \"prediction\": 0.8483680486679077, \"seed\": \"alternative\"}, {\"Country\": \"Vietnam\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Vietnam.\", \"prediction\": -0.9427406191825867, \"seed\": \"alternative\"}, {\"Country\": \"Yemen\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Yemen.\", \"prediction\": -0.8567103743553162, \"seed\": \"alternative\"}, {\"Country\": \"Albania\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Albania.\", \"prediction\": 0.9874222278594971, \"seed\": \"alternative\"}, {\"Country\": \"Andorra\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Andorra.\", \"prediction\": 0.9597309231758118, \"seed\": \"alternative\"}, {\"Country\": \"Armenia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Armenia.\", \"prediction\": 0.986950695514679, \"seed\": \"alternative\"}, {\"Country\": \"Austria\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Austria.\", \"prediction\": 0.8858200907707214, \"seed\": \"alternative\"}, {\"Country\": \"Azerbaijan\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Azerbaijan.\", \"prediction\": 0.9770861268043518, \"seed\": \"alternative\"}, {\"Country\": \"Belarus\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Belarus.\", \"prediction\": 0.5220555663108826, \"seed\": \"alternative\"}, {\"Country\": \"Belgium\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Belgium.\", \"prediction\": 0.9663146138191223, \"seed\": \"alternative\"}, {\"Country\": \"Bosnia and Herzegovina\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Bosnia and Herzegovina.\", \"prediction\": 0.9699962139129639, \"seed\": \"alternative\"}, {\"Country\": \"Bulgaria\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Bulgaria.\", \"prediction\": 0.8968954086303711, \"seed\": \"alternative\"}, {\"Country\": \"Croatia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Croatia.\", \"prediction\": 0.8545156717300415, \"seed\": \"alternative\"}, {\"Country\": \"Cyprus\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Cyprus.\", \"prediction\": 0.9457007646560669, \"seed\": \"alternative\"}, {\"Country\": \"CZ\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in CZ.\", \"prediction\": -0.9620359539985657, \"seed\": \"alternative\"}, {\"Country\": \"Denmark\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Denmark.\", \"prediction\": 0.9433714747428894, \"seed\": \"alternative\"}, {\"Country\": \"Estonia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Estonia.\", \"prediction\": 0.9754448533058167, \"seed\": \"alternative\"}, {\"Country\": \"Finland\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Finland.\", \"prediction\": 0.9832987189292908, \"seed\": \"alternative\"}, {\"Country\": \"France\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in France.\", \"prediction\": 0.9652075171470642, \"seed\": \"alternative\"}, {\"Country\": \"Georgia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Georgia.\", \"prediction\": 0.9579687714576721, \"seed\": \"alternative\"}, {\"Country\": \"Germany\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Germany.\", \"prediction\": -0.7719752192497253, \"seed\": \"alternative\"}, {\"Country\": \"Greece\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Greece.\", \"prediction\": 0.974821925163269, \"seed\": \"alternative\"}, {\"Country\": \"Hungary\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Hungary.\", \"prediction\": 0.9794204831123352, \"seed\": \"alternative\"}, {\"Country\": \"Iceland\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Iceland.\", \"prediction\": 0.9596456289291382, \"seed\": \"alternative\"}, {\"Country\": \"Ireland\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Ireland.\", \"prediction\": 0.9691770076751709, \"seed\": \"alternative\"}, {\"Country\": \"Italy\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Italy.\", \"prediction\": 0.973678469657898, \"seed\": \"alternative\"}, {\"Country\": \"Latvia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Latvia.\", \"prediction\": 0.9340384006500244, \"seed\": \"alternative\"}, {\"Country\": \"Liechtenstein\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Liechtenstein.\", \"prediction\": 0.9714267253875732, \"seed\": \"alternative\"}, {\"Country\": \"Lithuania\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Lithuania.\", \"prediction\": 0.9562608599662781, \"seed\": \"alternative\"}, {\"Country\": \"Luxembourg\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Luxembourg.\", \"prediction\": 0.9322720170021057, \"seed\": \"alternative\"}, {\"Country\": \"Macedonia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Macedonia.\", \"prediction\": 0.8895869255065918, \"seed\": \"alternative\"}, {\"Country\": \"Malta\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Malta.\", \"prediction\": 0.979903519153595, \"seed\": \"alternative\"}, {\"Country\": \"Moldova\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Moldova.\", \"prediction\": 0.8919235467910767, \"seed\": \"alternative\"}, {\"Country\": \"Monaco\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Monaco.\", \"prediction\": 0.9971835017204285, \"seed\": \"alternative\"}, {\"Country\": \"Montenegro\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Montenegro.\", \"prediction\": 0.9382426738739014, \"seed\": \"alternative\"}, {\"Country\": \"Netherlands\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Netherlands.\", \"prediction\": 0.9562605023384094, \"seed\": \"alternative\"}, {\"Country\": \"Norway\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Norway.\", \"prediction\": 0.9528943300247192, \"seed\": \"alternative\"}, {\"Country\": \"Poland\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Poland.\", \"prediction\": 0.9124379754066467, \"seed\": \"alternative\"}, {\"Country\": \"Portugal\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Portugal.\", \"prediction\": 0.9363807439804077, \"seed\": \"alternative\"}, {\"Country\": \"Romania\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Romania.\", \"prediction\": 0.982775866985321, \"seed\": \"alternative\"}, {\"Country\": \"San Marino\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in San Marino.\", \"prediction\": 0.924018144607544, \"seed\": \"alternative\"}, {\"Country\": \"Serbia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Serbia.\", \"prediction\": 0.740748405456543, \"seed\": \"alternative\"}, {\"Country\": \"Slovakia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Slovakia.\", \"prediction\": 0.5953425168991089, \"seed\": \"alternative\"}, {\"Country\": \"Slovenia\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Slovenia.\", \"prediction\": 0.8840153217315674, \"seed\": \"alternative\"}, {\"Country\": \"Spain\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Spain.\", \"prediction\": 0.9535741209983826, \"seed\": \"alternative\"}, {\"Country\": \"Sweden\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Sweden.\", \"prediction\": 0.9694980382919312, \"seed\": \"alternative\"}, {\"Country\": \"Switzerland\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Switzerland.\", \"prediction\": 0.7584144473075867, \"seed\": \"alternative\"}, {\"Country\": \"Ukraine\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Ukraine.\", \"prediction\": 0.7340573668479919, \"seed\": \"alternative\"}, {\"Country\": \"United Kingdom\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in United Kingdom.\", \"prediction\": 0.8982904553413391, \"seed\": \"alternative\"}, {\"Country\": \"Vatican City\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Vatican City.\", \"prediction\": 0.7796335816383362, \"seed\": \"alternative\"}, {\"Country\": \"Antigua and Barbuda\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Antigua and Barbuda.\", \"prediction\": 0.9056354761123657, \"seed\": \"alternative\"}, {\"Country\": \"Bahamas\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Bahamas.\", \"prediction\": 0.9206929802894592, \"seed\": \"alternative\"}, {\"Country\": \"Barbados\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Barbados.\", \"prediction\": 0.9170283079147339, \"seed\": \"alternative\"}, {\"Country\": \"Belize\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Belize.\", \"prediction\": 0.9203323125839233, \"seed\": \"alternative\"}, {\"Country\": \"Canada\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Canada.\", \"prediction\": 0.9400970339775085, \"seed\": \"alternative\"}, {\"Country\": \"Costa Rica\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Costa Rica.\", \"prediction\": 0.9815211892127991, \"seed\": \"alternative\"}, {\"Country\": \"Cuba\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Cuba.\", \"prediction\": 0.7347409725189209, \"seed\": \"alternative\"}, {\"Country\": \"Dominica\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Dominica.\", \"prediction\": 0.5335615277290344, \"seed\": \"alternative\"}, {\"Country\": \"Dominican Republic\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Dominican Republic.\", \"prediction\": 0.9594704508781433, \"seed\": \"alternative\"}, {\"Country\": \"El Salvador\", \"Continent\": \"North America\", \"text\": \"This film was filmed in El Salvador.\", \"prediction\": 0.9804539084434509, \"seed\": \"alternative\"}, {\"Country\": \"Grenada\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Grenada.\", \"prediction\": 0.6266372799873352, \"seed\": \"alternative\"}, {\"Country\": \"Guatemala\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Guatemala.\", \"prediction\": 0.7368012070655823, \"seed\": \"alternative\"}, {\"Country\": \"Haiti\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Haiti.\", \"prediction\": 0.9208669662475586, \"seed\": \"alternative\"}, {\"Country\": \"Honduras\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Honduras.\", \"prediction\": 0.7440645098686218, \"seed\": \"alternative\"}, {\"Country\": \"Jamaica\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Jamaica.\", \"prediction\": 0.8702073097229004, \"seed\": \"alternative\"}, {\"Country\": \"Mexico\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Mexico.\", \"prediction\": 0.9770798683166504, \"seed\": \"alternative\"}, {\"Country\": \"Nicaragua\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Nicaragua.\", \"prediction\": -0.6681438684463501, \"seed\": \"alternative\"}, {\"Country\": \"Panama\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Panama.\", \"prediction\": 0.737115740776062, \"seed\": \"alternative\"}, {\"Country\": \"Saint Kitts and Nevis\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Saint Kitts and Nevis.\", \"prediction\": 0.9829047918319702, \"seed\": \"alternative\"}, {\"Country\": \"Saint Lucia\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Saint Lucia.\", \"prediction\": 0.7933508157730103, \"seed\": \"alternative\"}, {\"Country\": \"Saint Vincent and the Grenadines\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Saint Vincent and the Grenadines.\", \"prediction\": 0.8782792091369629, \"seed\": \"alternative\"}, {\"Country\": \"Trinidad and Tobago\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Trinidad and Tobago.\", \"prediction\": 0.9884806871414185, \"seed\": \"alternative\"}, {\"Country\": \"US\", \"Continent\": \"North America\", \"text\": \"This film was filmed in US.\", \"prediction\": 0.926520586013794, \"seed\": \"alternative\"}, {\"Country\": \"Australia\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Australia.\", \"prediction\": 0.9371141195297241, \"seed\": \"alternative\"}, {\"Country\": \"Fiji\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Fiji.\", \"prediction\": 0.9061108827590942, \"seed\": \"alternative\"}, {\"Country\": \"Kiribati\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Kiribati.\", \"prediction\": 0.9559115767478943, \"seed\": \"alternative\"}, {\"Country\": \"Marshall Islands\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Marshall Islands.\", \"prediction\": 0.96001136302948, \"seed\": \"alternative\"}, {\"Country\": \"Micronesia\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Micronesia.\", \"prediction\": -0.57024085521698, \"seed\": \"alternative\"}, {\"Country\": \"Nauru\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Nauru.\", \"prediction\": 0.9323841333389282, \"seed\": \"alternative\"}, {\"Country\": \"New Zealand\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in New Zealand.\", \"prediction\": 0.9654895663261414, \"seed\": \"alternative\"}, {\"Country\": \"Palau\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Palau.\", \"prediction\": 0.7104437351226807, \"seed\": \"alternative\"}, {\"Country\": \"Papua New Guinea\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Papua New Guinea.\", \"prediction\": 0.5819137692451477, \"seed\": \"alternative\"}, {\"Country\": \"Samoa\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Samoa.\", \"prediction\": 0.9161322712898254, \"seed\": \"alternative\"}, {\"Country\": \"Solomon Islands\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Solomon Islands.\", \"prediction\": 0.9441730976104736, \"seed\": \"alternative\"}, {\"Country\": \"Tonga\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Tonga.\", \"prediction\": 0.550994873046875, \"seed\": \"alternative\"}, {\"Country\": \"Tuvalu\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Tuvalu.\", \"prediction\": 0.9912257790565491, \"seed\": \"alternative\"}, {\"Country\": \"Vanuatu\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Vanuatu.\", \"prediction\": 0.9395317435264587, \"seed\": \"alternative\"}, {\"Country\": \"Argentina\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Argentina.\", \"prediction\": 0.9719653129577637, \"seed\": \"alternative\"}, {\"Country\": \"Bolivia\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Bolivia.\", \"prediction\": 0.8009489178657532, \"seed\": \"alternative\"}, {\"Country\": \"Brazil\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Brazil.\", \"prediction\": 0.968963086605072, \"seed\": \"alternative\"}, {\"Country\": \"Chile\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Chile.\", \"prediction\": 0.8917940258979797, \"seed\": \"alternative\"}, {\"Country\": \"Colombia\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Colombia.\", \"prediction\": 0.731931746006012, \"seed\": \"alternative\"}, {\"Country\": \"Ecuador\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Ecuador.\", \"prediction\": 0.845059335231781, \"seed\": \"alternative\"}, {\"Country\": \"Guyana\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Guyana.\", \"prediction\": 0.6705957055091858, \"seed\": \"alternative\"}, {\"Country\": \"Paraguay\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Paraguay.\", \"prediction\": 0.6165609359741211, \"seed\": \"alternative\"}, {\"Country\": \"Peru\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Peru.\", \"prediction\": 0.7860054969787598, \"seed\": \"alternative\"}, {\"Country\": \"Suriname\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Suriname.\", \"prediction\": 0.9488070607185364, \"seed\": \"alternative\"}, {\"Country\": \"Uruguay\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Uruguay.\", \"prediction\": 0.744226336479187, \"seed\": \"alternative\"}, {\"Country\": \"Venezuela\", \"Continent\": \"South America\", \"text\": \"This film was filmed in Venezuela.\", \"prediction\": 0.8343830108642578, \"seed\": \"alternative\"}]}}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "single_nearest = alt.selection_single(on='mouseover', nearest=True)\n",
    "full = alt.Chart(df).encode(\n",
    "    alt.X('Continent:N'),  # specify nominal data\n",
    "    alt.Y('prediction:Q'),  # specify quantitative data\n",
    "    color=alt.Color('seed:N', legend=alt.Legend(title=\"Seed or Alternative\")),\n",
    "    size='seed:N',\n",
    "    tooltip=('Country','prediction')\n",
    ").mark_circle(opacity=.5).properties(width=300).add_selection(single_nearest)\n",
    "\n",
    "full"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "56bc30d7-03a5-43ff-9dfe-878197628305",
   "metadata": {},
   "outputs": [],
   "source": [
    "df2 = df.nlargest(5, 'prediction')\n",
    "df3 = df.nsmallest(5, 'prediction')\n",
    "frames = [df2,df3]\n",
    "results = pd.concat(frames)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "1610bb48-c9b9-4bee-bcb5-999886acb9e3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-948f4471f5ee4ed8bb2720ca7dd085a7\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  var VEGA_DEBUG = (typeof VEGA_DEBUG == \"undefined\") ? {} : VEGA_DEBUG;\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-948f4471f5ee4ed8bb2720ca7dd085a7\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-948f4471f5ee4ed8bb2720ca7dd085a7\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.17.0?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function maybeLoadScript(lib, version) {\n",
       "      var key = `${lib.replace(\"-\", \"\")}_version`;\n",
       "      return (VEGA_DEBUG[key] == version) ?\n",
       "        Promise.resolve(paths[lib]) :\n",
       "        new Promise(function(resolve, reject) {\n",
       "          var s = document.createElement('script');\n",
       "          document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "          s.async = true;\n",
       "          s.onload = () => {\n",
       "            VEGA_DEBUG[key] = version;\n",
       "            return resolve(paths[lib]);\n",
       "          };\n",
       "          s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "          s.src = paths[lib];\n",
       "        });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else {\n",
       "      maybeLoadScript(\"vega\", \"5\")\n",
       "        .then(() => maybeLoadScript(\"vega-lite\", \"4.17.0\"))\n",
       "        .then(() => maybeLoadScript(\"vega-embed\", \"6\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300}}, \"data\": {\"name\": \"data-09f850c452d77d8e274c73526803ae5c\"}, \"mark\": \"circle\", \"encoding\": {\"color\": {\"field\": \"seed\", \"legend\": {\"title\": \"Seed or Alternative\"}, \"type\": \"nominal\"}, \"size\": {\"field\": \"seed\", \"type\": \"nominal\"}, \"tooltip\": [{\"field\": \"Country\", \"type\": \"nominal\"}, {\"field\": \"prediction\", \"type\": \"quantitative\"}], \"x\": {\"field\": \"prediction\", \"type\": \"quantitative\"}, \"y\": {\"field\": \"Country\", \"sort\": \"-x\", \"type\": \"nominal\"}}, \"selection\": {\"selector002\": {\"type\": \"single\", \"on\": \"mouseover\", \"nearest\": true}}, \"width\": 300, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.17.0.json\", \"datasets\": {\"data-09f850c452d77d8e274c73526803ae5c\": [{\"Country\": \"Monaco\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Monaco.\", \"prediction\": 0.9971835017204285, \"seed\": \"alternative\"}, {\"Country\": \"Tuvalu\", \"Continent\": \"Oceania\", \"text\": \"This film was filmed in Tuvalu.\", \"prediction\": 0.9912257790565491, \"seed\": \"alternative\"}, {\"Country\": \"Philippines\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Philippines.\", \"prediction\": 0.9892238974571228, \"seed\": \"alternative\"}, {\"Country\": \"Trinidad and Tobago\", \"Continent\": \"North America\", \"text\": \"This film was filmed in Trinidad and Tobago.\", \"prediction\": 0.9884806871414185, \"seed\": \"alternative\"}, {\"Country\": \"Albania\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in Albania.\", \"prediction\": 0.9874222278594971, \"seed\": \"alternative\"}, {\"Country\": \"Iraq\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Iraq.\", \"prediction\": -0.9768388867378235, \"seed\": \"seed\"}, {\"Country\": \"CZ\", \"Continent\": \"Europe\", \"text\": \"This film was filmed in CZ.\", \"prediction\": -0.9620359539985657, \"seed\": \"alternative\"}, {\"Country\": \"Vietnam\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Vietnam.\", \"prediction\": -0.9427406191825867, \"seed\": \"alternative\"}, {\"Country\": \"Sudan\", \"Continent\": \"Africa\", \"text\": \"This film was filmed in Sudan.\", \"prediction\": -0.8910807967185974, \"seed\": \"alternative\"}, {\"Country\": \"Syria\", \"Continent\": \"Asia\", \"text\": \"This film was filmed in Syria.\", \"prediction\": -0.8887014985084534, \"seed\": \"alternative\"}]}}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.Chart(...)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bar = alt.Chart(results).encode(  \n",
    "    alt.X('prediction:Q'), \n",
    "    alt.Y('Country:N', sort=\"-x\"),\n",
    "    color=alt.Color('seed:N', legend=alt.Legend(title=\"Seed or Alternative\")),\n",
    "    size='seed:N',\n",
    "    tooltip=('Country','prediction')\n",
    ").mark_circle().properties(width=300).add_selection(single_nearest)\n",
    "\n",
    "bar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "96cd0798-5ac5-4ede-8373-e8ed71ab07b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def critical_words(document, options=False):\n",
    "    '''This function is meant to select the critical part of a sentence. Critical, in this context means\n",
    "    the part of the sentence that is either: A) a PROPN from the correct entity group; B) an ADJ associated with a NOUN;\n",
    "    C) a NOUN that represents gender. It also checks this against what the model thinks is important if the user defines \"options\" as \"LIME\" or True.'''\n",
    "    if type(document) is not spacy.tokens.doc.Doc:\n",
    "        document = nlp(document)\n",
    "    chunks = list(document.noun_chunks)\n",
    "    pos_options = []\n",
    "    lime_options = []\n",
    "    \n",
    "    #Identify what the model cares about.\n",
    "    if options:\n",
    "        exp = explainer.explain_instance(document.text, predictor, num_features=15, num_samples=2000)\n",
    "        lime_results = exp.as_list()\n",
    "        for feature in lime_results:\n",
    "            lime_options.append(feature[0])\n",
    "        lime_results = pd.DataFrame(lime_results, columns=[\"Word\",\"Weight\"])\n",
    "    \n",
    "    #Identify what we care about \"parts of speech\". The first section focuses on NOUNs and related ADJ.\n",
    "    for chunk in chunks:\n",
    "        #The use of chunk[-1] is due to testing that it appears to always match the root\n",
    "        root = chunk[-1]\n",
    "        #This currently matches to a list I've created. I don't know the best way to deal with this so I'm leaving it as is for the moment.\n",
    "        if root.ent_type_:\n",
    "            cur_values = []\n",
    "            if (len(chunk) > 1) and (chunk[-2].dep_ == \"compound\"):\n",
    "                #creates the compound element of the noun\n",
    "                compound = [x.text for x in chunk if x.dep_ == \"compound\"]\n",
    "                print(f\"This is the contents of {compound} and it is {all(elem in lime_options for elem in compound)} that all elements are present in {lime_options}.\") #for QA\n",
    "                #checks to see all elements in the compound are important to the model or use the compound if not checking importance.\n",
    "                if (all(elem in lime_options for elem in cur_values) and (options is True)) or ((options is False)):\n",
    "                    #creates a span for the entirety of the compound noun and adds it to the list.\n",
    "                    span = -1 * (1 + len(compound))\n",
    "                    pos_options.append(chunk[span:].text)\n",
    "                    cur_values + [token.text for token in chunk if token.pos_ == \"ADJ\"]\n",
    "                else:\n",
    "                    print(f\"The elmenents in {compound} could not be added to the final list because they are not all relevant to the model.\")\n",
    "            else: \n",
    "                cur_values = [token.text for token in chunk if (token.ent_type_) or (token.pos_ == \"ADJ\")]\n",
    "            if (all(elem in lime_options for elem in cur_values) and (options is True)) or ((options is False)):\n",
    "                pos_options.extend(cur_values)\n",
    "                print(f\"From {chunk.text}, {cur_values} added to pos_options due to entity recognition.\") #for QA\n",
    "        elif len(chunk) >= 1:\n",
    "            cur_values = [token.text for token in chunk if token.pos_ in [\"NOUN\",\"ADJ\"]]\n",
    "            if (all(elem in lime_options for elem in cur_values) and (options is True)) or ((options is False)):\n",
    "                pos_options.extend(cur_values)\n",
    "                print(f\"From {chunk.text}, {cur_values} added to pos_options due to wildcard.\") #for QA\n",
    "        else:\n",
    "            print(f\"No options added for \\'{chunk.text}\\' \")\n",
    "    # Here I am going to try to pick up pronouns, which are people, and Adjectival Compliments.\n",
    "    for token in document:\n",
    "        if (token.text not in pos_options) and ((token.text in lime_options) or (options == False)):\n",
    "            #print(f\"executed {token.text} with {token.pos_} and {token.dep_}\") #QA\n",
    "            if (token.pos_ == \"ADJ\") and (token.dep_ in [\"acomp\",\"conj\"]):\n",
    "                pos_options.append(token.text)            \n",
    "            elif (token.pos_ == \"PRON\") and (token.morph.get(\"PronType\")[0] == \"Prs\"):\n",
    "                pos_options.append(token.text)\n",
    "    \n",
    "    #Return the correct set of options based on user input, defaults to POS for simplicity.\n",
    "    if options:\n",
    "        return pos_options, lime_results\n",
    "    else:\n",
    "        return pos_options"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "b04e7783-e51b-49b0-8165-afe1d5a1c576",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Testing new code\n",
    "a = \"People are fat and lazy.\"\n",
    "b = \"I think she is beautiful.\"\n",
    "doca = nlp(a)\n",
    "docb = nlp(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "0a6bc521-9282-41ad-82c9-29e447d77635",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "No options added for 'People' \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['fat', 'lazy']"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "optsa, limea = critical_words(doca, True)\n",
    "optsa"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "042e94d3-65a5-4a20-b69a-96ec3296d7d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def lime_viz(df):\n",
    "    single_nearest = alt.selection_single(on='mouseover', nearest=True)\n",
    "    viz = alt.Chart(df).encode(\n",
    "        alt.X('Weight:Q', scale=alt.Scale(domain=(-1, 1))),\n",
    "        alt.Y('Word:N', sort='x', axis=None),\n",
    "        color=alt.Color(\"Weight\", scale=alt.Scale(scheme='blueorange', domain=[0], type=\"threshold\", range='diverging'), legend=None),\n",
    "        tooltip = (\"Word\",\"Weight\")\n",
    "    ).mark_bar().properties(title =\"Importance of individual words\")\n",
    "\n",
    "    text = viz.mark_text(\n",
    "        fill=\"black\",\n",
    "        align='right',\n",
    "        baseline='middle'\n",
    "    ).encode(\n",
    "        text='Word:N'\n",
    "    )\n",
    "    limeplot = alt.LayerChart(layer=[viz,text], width = 300).configure_axis(grid=False).configure_view(strokeWidth=0)\n",
    "    return limeplot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "924eeea8-1d5d-4fe7-8308-164521919269",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "No options added for 'I' \n",
      "From a white woman, ['white', 'woman'] added to pos_options due to wildcard.\n",
      "From the street, ['street'] added to pos_options due to wildcard.\n",
      "From an asian man, ['asian', 'man'] added to pos_options due to wildcard.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['white', 'woman', 'street', 'asian', 'man', 'I']"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test8 = \"I saw a white woman walking down the street with an asian man.\"\n",
    "opts8, lime8 = critical_words(test8,True)\n",
    "opts8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "734366df-ad99-4d80-87e1-51793e150681",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"altair-viz-adaa380d0d924bb594dd3aaee854acfd\"></div>\n",
       "<script type=\"text/javascript\">\n",
       "  var VEGA_DEBUG = (typeof VEGA_DEBUG == \"undefined\") ? {} : VEGA_DEBUG;\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-adaa380d0d924bb594dd3aaee854acfd\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-adaa380d0d924bb594dd3aaee854acfd\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.17.0?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function maybeLoadScript(lib, version) {\n",
       "      var key = `${lib.replace(\"-\", \"\")}_version`;\n",
       "      return (VEGA_DEBUG[key] == version) ?\n",
       "        Promise.resolve(paths[lib]) :\n",
       "        new Promise(function(resolve, reject) {\n",
       "          var s = document.createElement('script');\n",
       "          document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "          s.async = true;\n",
       "          s.onload = () => {\n",
       "            VEGA_DEBUG[key] = version;\n",
       "            return resolve(paths[lib]);\n",
       "          };\n",
       "          s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "          s.src = paths[lib];\n",
       "        });\n",
       "    }\n",
       "\n",
       "    function showError(err) {\n",
       "      outputDiv.innerHTML = `<div class=\"error\" style=\"color:red;\">${err}</div>`;\n",
       "      throw err;\n",
       "    }\n",
       "\n",
       "    function displayChart(vegaEmbed) {\n",
       "      vegaEmbed(outputDiv, spec, embedOpt)\n",
       "        .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));\n",
       "    }\n",
       "\n",
       "    if(typeof define === \"function\" && define.amd) {\n",
       "      requirejs.config({paths});\n",
       "      require([\"vega-embed\"], displayChart, err => showError(`Error loading script: ${err.message}`));\n",
       "    } else {\n",
       "      maybeLoadScript(\"vega\", \"5\")\n",
       "        .then(() => maybeLoadScript(\"vega-lite\", \"4.17.0\"))\n",
       "        .then(() => maybeLoadScript(\"vega-embed\", \"6\"))\n",
       "        .catch(showError)\n",
       "        .then(() => displayChart(vegaEmbed));\n",
       "    }\n",
       "  })({\"config\": {\"view\": {\"continuousWidth\": 400, \"continuousHeight\": 300, \"strokeWidth\": 0}, \"axis\": {\"grid\": false}}, \"layer\": [{\"mark\": \"bar\", \"encoding\": {\"color\": {\"field\": \"Weight\", \"legend\": null, \"scale\": {\"domain\": [0], \"range\": \"diverging\", \"scheme\": \"blueorange\", \"type\": \"threshold\"}, \"type\": \"quantitative\"}, \"tooltip\": [{\"field\": \"Word\", \"type\": \"nominal\"}, {\"field\": \"Weight\", \"type\": \"quantitative\"}], \"x\": {\"field\": \"Weight\", \"scale\": {\"domain\": [-1, 1]}, \"type\": \"quantitative\"}, \"y\": {\"axis\": null, \"field\": \"Word\", \"sort\": \"x\", \"type\": \"nominal\"}}, \"title\": \"Importance of individual words\"}, {\"mark\": {\"type\": \"text\", \"align\": \"right\", \"baseline\": \"middle\", \"fill\": \"black\"}, \"encoding\": {\"color\": {\"field\": \"Weight\", \"legend\": null, \"scale\": {\"domain\": [0], \"range\": \"diverging\", \"scheme\": \"blueorange\", \"type\": \"threshold\"}, \"type\": \"quantitative\"}, \"text\": {\"field\": \"Word\", \"type\": \"nominal\"}, \"tooltip\": [{\"field\": \"Word\", \"type\": \"nominal\"}, {\"field\": \"Weight\", \"type\": \"quantitative\"}], \"x\": {\"field\": \"Weight\", \"scale\": {\"domain\": [-1, 1]}, \"type\": \"quantitative\"}, \"y\": {\"axis\": null, \"field\": \"Word\", \"sort\": \"x\", \"type\": \"nominal\"}}, \"title\": \"Importance of individual words\"}], \"data\": {\"name\": \"data-d686d7fc533c26b0bdc6066e4351f840\"}, \"width\": 300, \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.17.0.json\", \"datasets\": {\"data-d686d7fc533c26b0bdc6066e4351f840\": [{\"Word\": \"with\", \"Weight\": 0.3289028288853927}, {\"Word\": \"woman\", \"Weight\": -0.26094440033196564}, {\"Word\": \"asian\", \"Weight\": 0.24561077002890458}, {\"Word\": \"walking\", \"Weight\": 0.19194218998931795}, {\"Word\": \"white\", \"Weight\": -0.14942503537339621}, {\"Word\": \"down\", \"Weight\": -0.14547403123420313}, {\"Word\": \"the\", \"Weight\": 0.14096934306553166}, {\"Word\": \"I\", \"Weight\": -0.08672932329874143}, {\"Word\": \"street\", \"Weight\": 0.06704680513000527}, {\"Word\": \"a\", \"Weight\": -0.03171807940472653}, {\"Word\": \"an\", \"Weight\": -0.006746730007490843}, {\"Word\": \"saw\", \"Weight\": 0.0019276122088497296}, {\"Word\": \"man\", \"Weight\": -0.0005652423244728638}]}}, {\"mode\": \"vega-lite\"});\n",
       "</script>"
      ],
      "text/plain": [
       "alt.LayerChart(...)"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lime_viz(lime8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "816e1c4b-7f02-41b1-b430-2f3750ae6c4a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "No options added for 'I' \n",
      "From a white woman, ['white', 'woman'] added to pos_options due to wildcard.\n",
      "From the street, ['street'] added to pos_options due to wildcard.\n",
      "From an asian man, ['asian', 'man'] added to pos_options due to wildcard.\n"
     ]
    }
   ],
   "source": [
    "probability, sentiment = eval_pred_test(test8, return_all=True)\n",
    "options, lime = critical_words(test8,options=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "a437a4eb-73b3-4b3c-a719-8dde2ad6dd3c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "From I, [] added to pos_options due to wildcard.\n",
      "From men, ['men'] added to pos_options due to wildcard.\n",
      "From women, ['women'] added to pos_options due to wildcard.\n",
      "From the same respect, ['same', 'respect'] added to pos_options due to wildcard.\n"
     ]
    }
   ],
   "source": [
    "bug = \"I find men and women deserve the same respect.\"\n",
    "options = critical_words(bug)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "8676defd-0908-4218-a1d6-218de3fb7119",
   "metadata": {},
   "outputs": [],
   "source": [
    "bug_doc = nlp(bug)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "21b9e39b-2fcd-4c6f-8fe6-0d571cd79cca",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I\n",
      "PRON\n",
      "a man\n",
      "NOUN\n",
      "woman\n",
      "NOUN\n",
      "the same respect\n",
      "NOUN\n"
     ]
    }
   ],
   "source": [
    "for chunk in bug_doc.noun_chunks:\n",
    "    print(chunk.text)\n",
    "    print(chunk[-1].pos_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38279d2d-e763-4329-a65e-1a67d6f5ebb8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}