-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbehav_exp_analysis.py
3235 lines (2861 loc) · 114 KB
/
behav_exp_analysis.py
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
from collections import OrderedDict
import random
import re
import itertools
import copy
import os, pathlib
import string
import inspect
from contextlib import contextmanager
import textwrap
import numpy as np
import pandas as pd
from tqdm import tqdm
import pandas as pd
import scipy.stats
import statsmodels.stats.multitest
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib
import seaborn as sns
from matplotlib.gridspec import GridSpec
import matplotlib.patches as mpatches
from metroplot import metroplot
from model_functions import model_factory
from signed_rank_cosine_similarity import (
calc_signed_rank_cosine_similarity_analytical_RAE,
calc_expected_normalized_RAE_signed_rank_response_pattern,
calc_semi_signed_rank_cosine_similarity_analytical_RAE,
)
model_order = {
"exp1": [
"gpt2",
"roberta",
"electra",
"bert",
"xlm",
"lstm",
"rnn",
"trigram",
"bigram",
],
"exp2": [
"roberta",
"roberta_has_a_mouth",
"electra",
"electra_has_a_mouth",
"bert",
"bert_has_a_mouth",
],
}
# define model colors
# color pallete from colorbrewer2 : https://colorbrewer2.org/?type=qualitative&scheme=Paired&n=9#type=qualitative&scheme=Accent&n=3
model_palette = {
"gpt2": "#a6cee3",
"roberta": "#1f78b4",
"roberta_has_a_mouth": "#1f78b4",
"electra": "#b2df8a",
"electra_has_a_mouth": "#b2df8a",
"bert": "#33a02c",
"bert_has_a_mouth": "#33a02c",
"xlm": "#fb9a99",
"lstm": "#e31a1c",
"rnn": "#fdbf6f",
"trigram": "#ff7f00",
"bigram": "#cab2d6",
}
# nice labels for the models
model_name_dict = {
"gpt2": "GPT-2",
"roberta": "RoBERTa",
"roberta_has_a_mouth": "RoBERTa (PLL)",
"electra": "ELECTRA",
"electra_has_a_mouth": "ELECTRA (PLL)",
"bert": "BERT",
"bert_has_a_mouth": "BERT (PLL)",
"xlm": "XLM",
"lstm": "LSTM",
"rnn": "RNN",
"trigram": "3-gram",
"bigram": "2-gram",
}
panel_letter_fontsize = 12
# colors for scatter plot:
# https://www.visualisingdata.com/2019/08/five-ways-to-design-for-red-green-colour-blindness/
natural_sentence_color = "#FFFFFF"
synthetic_sentence_color = "#AAAAAA"
shuffled_sentence_color = "#000000"
selected_trial_color = "#000000"
unselected_trial_color = "#AAAAAA"
# https://stackoverflow.com/questions/38629830/how-to-turn-off-autoscaling-in-matplotlib-pyplot
@contextmanager
def autoscale_turned_off(ax=None):
ax = ax or plt.gca()
lims = [ax.get_xlim(), ax.get_ylim()]
yield
ax.set_xlim(*lims[0])
ax.set_ylim(*lims[1])
def niceify(x):
"""transform lists and dicts of string to use nice model labels"""
if isinstance(x, list):
return [model_name_dict[m] for m in x]
elif isinstance(x, pd.core.series.Series):
return x.apply(lambda model: model_name_dict[model])
elif isinstance(x, dict):
return {model_name_dict[k]: v for k, v in x.items()}
elif isinstance(x, str):
return model_name_dict[x]
else:
raise ValueError
def _save_or_display_fig(save_folder, filename, fig, dpi=600):
if save_folder is not None:
pathlib.Path(save_folder).mkdir(parents=True, exist_ok=True)
fig.savefig(
os.path.join(save_folder, filename),
dpi=dpi,
)
print(
f"saved {save_folder}/{filename}', {fig.get_size_inches()[0]:.2f} x {fig.get_size_inches()[1]:.2f} inch."
)
if filename.endswith(".pdf"):
# also save a high res PNG
fig.savefig(
os.path.join(save_folder, filename.replace(".pdf", ".png")),
dpi=600,
)
else:
plt.show()
def align_sentences(df):
"""To ease analysis, we align all trials so the order of sentences
within each sentence pair is lexicographical rather than based on display position.
This ensures that different subjects can be directly compared to each other.
This script also changes creates a numerical "rating" column, with 1 = strong preference for sentence1, 6 = strong preference for sentence2.
"""
fields_to_del = ["Unnamed: 0", "Zone Type"]
df2 = []
for i_trial, old_trial in df.iterrows():
new_trial = OrderedDict()
flip_required = old_trial.sentence1 > old_trial.sentence2
for col in df.columns:
if col in fields_to_del:
continue
elif col == "Zone Name":
rating = float(old_trial["Zone Name"].replace("resp", ""))
if flip_required:
rating = 7 - rating
new_trial["rating"] = rating
else:
reference_col = col
if flip_required:
if "sentence1" in col.lower():
reference_col = col.replace("sentence1", "sentence2").replace(
"Sentence1", "Sentence2"
)
elif "sentence2" in col.lower():
reference_col = col.replace("sentence2", "sentence1").replace(
"Sentence2", "Sentence1"
)
new_trial[col] = old_trial[reference_col]
if flip_required:
new_trial["sentence1_location"] = "right"
else:
new_trial["sentence1_location"] = "left"
df2.append(new_trial)
df2 = pd.DataFrame(df2)
return df2
def recode_model_targeting(
df,
natural_controversial_sentences_fname,
synthetic_controversial_sentences_fname,
):
"""create readable model targeting labels.
The follow fields are added to df:
sentence1_model_targeted_to_accept - the model that was optimized to view sentence1 as at least as likely as a natural sentence
sentence1_model_targeted_to_reject - the model that was optimized to view sentence1 as unlikely
(+the equivalent fields for sentence2)
returns:
modified datafrate
"""
df = df.copy()
if natural_controversial_sentences_fname is not None:
natural_controversial_sentences_df = pd.read_csv(
natural_controversial_sentences_fname
)
else:
natural_controversial_sentences_df = None
if synthetic_controversial_sentences_fname is not None:
synthetic_controversial_sentences_df = pd.read_csv(
synthetic_controversial_sentences_fname
)
else:
synthetic_controversial_sentences_df = None
def get_natural_controversial_sentence_targeting(
sentence, natural_controversial_sentences_df
):
match_sentence1 = natural_controversial_sentences_df[
natural_controversial_sentences_df.sentence1 == sentence
]
match_sentence2 = natural_controversial_sentences_df[
natural_controversial_sentences_df.sentence2 == sentence
]
if len(match_sentence1) == 1 and len(match_sentence2) == 0:
sentence_model_targeted_to_accept = match_sentence1["model_2"].item()
sentence_model_targeted_to_reject = match_sentence1["model_1"].item()
elif len(match_sentence1) == 0 and len(match_sentence2) == 1:
sentence_model_targeted_to_accept = match_sentence2["model_1"].item()
sentence_model_targeted_to_reject = match_sentence2["model_2"].item()
else:
raise Exception
return sentence_model_targeted_to_accept, sentence_model_targeted_to_reject
def get_synthetic_controversial_sentence_targeting(
sentence, synthetic_controversial_sentences_df
):
match_sentence1 = synthetic_controversial_sentences_df[
synthetic_controversial_sentences_df.S1 == sentence
]
match_sentence2 = synthetic_controversial_sentences_df[
synthetic_controversial_sentences_df.S2 == sentence
]
if len(match_sentence1) == 1 and len(match_sentence2) == 0:
sentence_model_targeted_to_accept = match_sentence1["m1"].item()
sentence_model_targeted_to_reject = match_sentence1["m2"].item()
elif len(match_sentence1) == 0 and len(match_sentence2) == 1:
sentence_model_targeted_to_accept = match_sentence2["m2"].item()
sentence_model_targeted_to_reject = match_sentence2["m1"].item()
else:
raise Exception
return sentence_model_targeted_to_accept, sentence_model_targeted_to_reject
for idx_trial, trial in tqdm(
df.iterrows(), total=len(df), desc="recoding model targeting"
):
if {trial.sentence1_type, trial.sentence2_type} == {"N1", "N2"}:
# Natural controversial sentences. Here we make sure the model predictions are fully crossed.
df.loc[idx_trial, "trial_type"] = "natural_controversial"
# go back to original CSV and grab model targeting info
for s in [1, 2]:
(
df.loc[idx_trial, f"sentence{s}_model_targeted_to_accept"],
df.loc[idx_trial, f"sentence{s}_model_targeted_to_reject"],
) = get_natural_controversial_sentence_targeting(
getattr(trial, f"sentence{s}"), natural_controversial_sentences_df
)
# sanity check for model predictions
model_A_s1 = df.loc[idx_trial, "sentence1_model_targeted_to_accept"]
model_R_s1 = df.loc[idx_trial, "sentence1_model_targeted_to_reject"]
model_A_s2 = df.loc[idx_trial, "sentence2_model_targeted_to_accept"]
model_R_s2 = df.loc[idx_trial, "sentence2_model_targeted_to_reject"]
assert (model_A_s1 == model_R_s2) and (model_R_s1 == model_A_s2)
p_A_s1 = getattr(trial, f"sentence1_{model_A_s1}_prob")
p_R_s1 = getattr(trial, f"sentence1_{model_R_s1}_prob")
p_A_s2 = getattr(trial, f"sentence2_{model_A_s2}_prob")
p_R_s2 = getattr(trial, f"sentence2_{model_R_s2}_prob")
assert (p_A_s1 > p_R_s2) & (p_A_s2 > p_R_s1)
elif {trial.sentence1_type, trial.sentence2_type} == {"N", "S1"} or {
trial.sentence1_type,
trial.sentence2_type,
} == {"N", "S2"}:
# A synthetic controversial sentence vs. a natural sentence.
df.loc[idx_trial, "trial_type"] = "natural_vs_synthetic"
n = [1, 2][[trial.sentence1_type, trial.sentence2_type].index("N")]
s = [2, 1][[trial.sentence1_type, trial.sentence2_type].index("N")]
# go back to original CSV and grab model targeting info
(
df.loc[idx_trial, f"sentence{s}_model_targeted_to_accept"],
df.loc[idx_trial, f"sentence{s}_model_targeted_to_reject"],
) = get_synthetic_controversial_sentence_targeting(
getattr(trial, f"sentence{s}"), synthetic_controversial_sentences_df
)
# sanity check for model predictions
model_A_s = df.loc[idx_trial, f"sentence{s}_model_targeted_to_accept"]
model_R_s = df.loc[idx_trial, f"sentence{s}_model_targeted_to_reject"]
p_A_s = getattr(trial, f"sentence{s}_{model_A_s}_prob")
p_R_s = getattr(trial, f"sentence{s}_{model_R_s}_prob")
p_A_n = getattr(trial, f"sentence{n}_{model_A_s}_prob")
p_R_n = getattr(trial, f"sentence{n}_{model_R_s}_prob")
assert (p_A_s >= p_A_n) and (p_R_s < p_R_n)
elif {trial.sentence1_type, trial.sentence2_type} == {"S1", "S2"}:
# Synthetic controversial sentence vs. Synthetic controversial sentence
df.loc[idx_trial, "trial_type"] = "synthetic_vs_synthetic"
# go back to original CSV and grab model targeting info
for s in [1, 2]:
(
df.loc[idx_trial, f"sentence{s}_model_targeted_to_accept"],
df.loc[idx_trial, f"sentence{s}_model_targeted_to_reject"],
) = get_synthetic_controversial_sentence_targeting(
getattr(trial, f"sentence{s}"), synthetic_controversial_sentences_df
)
# sanity check for model predictions
model_A_s1 = df.loc[idx_trial, "sentence1_model_targeted_to_accept"]
model_R_s1 = df.loc[idx_trial, "sentence1_model_targeted_to_reject"]
model_A_s2 = df.loc[idx_trial, "sentence2_model_targeted_to_accept"]
model_R_s2 = df.loc[idx_trial, "sentence2_model_targeted_to_reject"]
assert (model_A_s1 == model_R_s2) and (model_R_s1 == model_A_s2)
p_A_s1 = getattr(trial, f"sentence1_{model_A_s1}_prob")
p_R_s1 = getattr(trial, f"sentence1_{model_R_s1}_prob")
p_A_s2 = getattr(trial, f"sentence2_{model_A_s2}_prob")
p_R_s2 = getattr(trial, f"sentence2_{model_R_s2}_prob")
assert (p_A_s1 > p_R_s2) & (p_A_s2 > p_R_s1)
elif {trial.sentence1_type, trial.sentence2_type} == {"C1", "C2"}:
# Catch trials (natural sentences and their shuffled version)
df.loc[
idx_trial, "trial_type"
] = "natural_vs_shuffled" # C1-> N (natural), C2-> C (catch)
df.loc[idx_trial, "sentence1_type"] = trial.sentence1_type.replace(
"C1", "N"
).replace("C2", "C")
df.loc[idx_trial, "sentence2_type"] = trial.sentence2_type.replace(
"C1", "N"
).replace("C2", "C")
elif {trial.sentence1_type, trial.sentence2_type} == {"R1", "R2"}:
# randomly sampled natural sentences
df.loc[idx_trial, "trial_type"] = "randomly_sampled_natural"
else:
raise ValueError
# remove 1 and 2 from sentence type
df.loc[idx_trial, "sentence1_type"] = (
df.loc[idx_trial, "sentence1_type"].replace("1", "").replace("2", "")
)
df.loc[idx_trial, "sentence2_type"] = (
df.loc[idx_trial, "sentence2_type"].replace("1", "").replace("2", "")
)
return df
def add_leave_one_subject_predictions(df):
"""Leave one subject out noise ceiling
All of the following measures are lower bounds on the noise ceiling.
In other words, an ideal model should be at least as good as these measures.
"""
# The LOOSO loop.
df2 = df.copy()
df2["binarized_choice_probability_NC_LB"] = np.nan
df2["binarized_choice_probability_NC_UB"] = np.nan
df2["majority_vote_NC_LB"] = np.nan
df2["majority_vote_NC_UB"] = np.nan
df2["mean_rating_NC_LB"] = np.nan
df2["mean_rating_NC_UB"] = np.nan
# def assign(df, index, field,val):
# df.iloc[index,df.columns.get_loc(field)]=val
# print(df.iloc[index,df.columns.get_loc(field)])
for trial_idx, trial in tqdm(
df.iterrows(), total=len(df), desc="leave one subject out NC calculation."
):
# choose all trials with the same sentence pair in OTHER subjects.
mask = (df["sentence_pair"] == trial["sentence_pair"]) & (
df["subject"] != trial["subject"]
)
reduced_df = df[mask]
# we add three kinds of noise ceiling:
# 1. binarized choice probability:
# the predicted probability that a subject will prefer sentence2
# (to be used for binomial likelihood evaluation)
df2.loc[trial_idx, "binarized_choice_probability_NC_LB"] = (
reduced_df["rating"] >= 4
).mean()
# 2. simple majority vote (1: sentence2, 0: sentence1)
# to be used for accuracy evaluation)
if df2.loc[trial_idx, "binarized_choice_probability_NC_LB"] > 0.5:
df2.loc[trial_idx, "majority_vote_NC_LB"] = 1
elif df2.loc[trial_idx, "binarized_choice_probability_NC_LB"] < 0.5:
df2.loc[trial_idx, "majority_vote_NC_LB"] = 0
else:
raise Warning(
f"Tied predictions for trial {trial_idx}. Randomzing prediction."
)
df2.loc[trial_idx, "majority_vote_NC_LB"] = random.choice([0, 1])
# 3. And last, we simply average the ratings
# to be used for correlation based measures
df2.loc[trial_idx, "mean_rating_NC_LB"] = (reduced_df["rating"]).mean()
for trial_idx, trial in tqdm(
df.iterrows(), total=len(df), desc="upper bound NC calculation."
):
# choose all trials with the same sentence pair in ALL subjects.
mask = df["sentence_pair"] == trial["sentence_pair"]
reduced_df = df[mask]
# 1. binarized choice probability:
# the predicted probability that a subject will prefer sentence2
# (to be used for binomial likelihood evaluation)
df2.loc[trial_idx, "binarized_choice_probability_NC_UB"] = (
reduced_df["rating"] >= 4
).mean()
# 2. simple majority vote (1: sentence2, 0: sentence1)
# to be used for accuracy evaluation)
if df2.loc[trial_idx, "binarized_choice_probability_NC_UB"] > 0.5:
df2.loc[trial_idx, "majority_vote_NC_UB"] = 1
elif df2.loc[trial_idx, "binarized_choice_probability_NC_UB"] < 0.5:
df2.loc[trial_idx, "majority_vote_NC_UB"] = 0
else:
# print(f'Tied predictions for trial {trial_idx}. Randomizing prediction.')
df2.loc[trial_idx, "majority_vote_NC_UB"] = random.choice([0, 1])
# 3. And last, we simply average the ratings
# to be used for correlation based measures
df2.loc[trial_idx, "mean_rating_NC_UB"] = (reduced_df["rating"]).mean()
# (note - this is not a true upper bound on the noise ceiling for average model-subject correlation coefficient)
return df2
def filter_trials(df, targeted_model=None, targeting=None, trial_type=None):
"""subsets a trial dataframe.
one can filter by trial type, as well as by the targeted model.
for trial_type='natural_vs_synthetic', we can also specify targeting='accept'|'reject',
to select only trials in which the synthetic sentence was optimized to be accepted/rejected
by targeted_model.
args:
targeted_model (str) which model was targeted
targeting (str) 'accept'|'reject'|None for all. what kind of targeting.
trial_type (str) 'natural_controversial'|'natural_vs_synthetic'|'synthetic_vs_synthetic'|'natural_vs_shuffled'|'randomly_sampled_natural'| None for all
returns reduced df
"""
mask = df["subject"] == df["subject"] # all True series
if trial_type is not None:
mask = mask & (df["trial_type"] == trial_type)
if targeted_model is None:
assert (
targeting is None
), "targeting should only be specified when targeted_model is specified"
elif targeting is None:
# we keep the trial if one of the sentences targeted the model
mask = mask & (
(df["sentence1_model_targeted_to_accept"] == targeted_model)
| (df["sentence1_model_targeted_to_reject"] == targeted_model)
| (df["sentence2_model_targeted_to_accept"] == targeted_model)
| (df["sentence2_model_targeted_to_reject"] == targeted_model)
)
elif targeting is "accept":
assert (
trial_type == "natural_vs_synthetic"
), "filtering trials by accept/reject targeting only makes sense for N vs S trials."
mask = mask & (
(df["sentence1_model_targeted_to_accept"] == targeted_model)
| (df["sentence2_model_targeted_to_accept"] == targeted_model)
)
elif targeting is "reject":
assert (
trial_type == "natural_vs_synthetic"
), "filtering trials by accept/reject targeting only makes sense for N vs S trials."
mask = mask & (
(df["sentence1_model_targeted_to_reject"] == targeted_model)
| (df["sentence2_model_targeted_to_reject"] == targeted_model)
)
else:
raise ValueError
return df.copy()[mask]
def get_models(df):
"""a helper function for extracting model names from column names"""
models = [
re.findall("sentence1_(.+)_prob", col)[0]
for col in df.columns
if re.search("sentence1_(.+)_prob", col)
]
return models
def group_level_signed_ranked_test(
reduced_df,
models,
grouping_variable="subject_group",
model_combinations_to_contrast=None,
):
"""calculate FDR-controlled Wilcoxon rank sum test between models and between each model and its noise ceiling."""
group_level_df = reduced_df.groupby(grouping_variable).mean()
results = []
if model_combinations_to_contrast is None:
model_combinations_to_contrast = list(itertools.combinations(models, 2))
for model1, model2 in model_combinations_to_contrast:
s, p = scipy.stats.wilcoxon(
group_level_df[model1], group_level_df[model2], zero_method="zsplit"
)
results.append(
{
"model1": model1,
"model2": model2,
"p-value": p,
"avg_model1_minus_avg_model2": (
group_level_df[model1] - group_level_df[model2]
).mean(),
}
)
# noise ceiling comparisons
for model1 in models:
if "NC_LB" in group_level_df.columns:
model2 = "NC_LB"
elif ("NC_LB_" + model1) in group_level_df.columns:
model2 = "NC_LB_" + model1
s, p = scipy.stats.wilcoxon(
group_level_df[model1], group_level_df[model2], zero_method="zsplit"
)
results.append(
{
"model1": model1,
"model2": model2,
"p-value": p,
"avg_model1_minus_avg_model2": (
group_level_df[model1] - group_level_df[model2]
).mean(),
}
)
results = pd.DataFrame(results)
_, results["FDR_corrected_p-value"] = statsmodels.stats.multitest.fdrcorrection(
results["p-value"]
)
return results
def calc_binarized_accuracy(df, drop_model_prob=True):
"""binarizes model and human predictions and returns 1 or 0 for prediction correctness"""
df2 = df.copy()
models = get_models(df)
for model in models:
assert not (
df["sentence2_" + model + "_prob"] == df["sentence1_" + model + "_prob"]
).any(), f"found tied prediction for model {model}"
model_predicts_sent2 = (
df["sentence2_" + model + "_prob"] > df["sentence1_" + model + "_prob"]
)
human_chose_sent2 = df["rating"] >= 4
# store trial-level accuracy
df2[model] = (model_predicts_sent2 == human_chose_sent2).astype("float")
# drop probability
if drop_model_prob:
df2 = df2.drop(
columns=["sentence1_" + model + "_prob", "sentence2_" + model + "_prob"]
)
df2["NC_LB"] = (df2["majority_vote_NC_LB"] == human_chose_sent2).astype(float)
df2["NC_UB"] = (df2["majority_vote_NC_UB"] == human_chose_sent2).astype(float)
return df2
def get_normalized_mean_RAE_signed_ranked_response(
df, subject_group, excluded_subject=None
):
"""for a given subject group, calculate the expected normalized RAE signed-rank responses for each subject,
and then average across subjects.
the response pattern is returned as a new normalized_expected_RAE_signed_rank_response_pattern
(used for noise ceiling bounds)
"""
df_subject_group = df[df["subject_group"] == subject_group]
assert len(df_subject_group) > 0
if excluded_subject is not None:
df_subject_group = df_subject_group[
df_subject_group["subject"] != excluded_subject
]
if not "zero_centered_rating" in df_subject_group.columns:
df_subject_group["zero_centered_rating"] = df_subject_group["rating"] - 3.5
def add_expected_normalized_RAE_signed_rank_response_pattern(df):
"""calculate the expected normalized random-among-equals signed-rank responses for each subject"""
x = df["zero_centered_rating"]
r = calc_expected_normalized_RAE_signed_rank_response_pattern(x)
df2 = df.copy()
df2["normalized_expected_RAE_signed_rank_response_pattern"] = r
return df2
df_subject_group = df_subject_group.groupby("subject").apply(
add_expected_normalized_RAE_signed_rank_response_pattern
)
# now reduce subjects
df_subject_group = df_subject_group.groupby(["sentence_pair"], dropna=True).mean()
df_subject_group = df_subject_group.drop(
columns=set(df_subject_group.columns)
- {"normalized_expected_RAE_signed_rank_response_pattern"}
)
return df_subject_group
def RAE_signed_rank_cosine_similarity(df):
"""signed-ranked cosine similarity log (p(s1|m)/p(s2|m)) and human ratings"""
df = df.copy()
df["zero_centered_rating"] = df["rating"] - 3.5
models = get_models(df)
subjects = df["subject"].unique()
results = []
for subject in tqdm(subjects):
df_subject = df[df["subject"] == subject]
subject_group = df_subject["subject_group"].unique().item()
cur_result = {}
cur_result["subject"] = subject
cur_result["subject_group"] = subject_group
# calculate human-model correlations
for model in models:
model_log_prob_diff = (
df_subject["sentence2_" + model + "_prob"]
- df_subject["sentence1_" + model + "_prob"]
)
cur_result[model] = calc_signed_rank_cosine_similarity_analytical_RAE(
model_log_prob_diff, df_subject["zero_centered_rating"]
)
# and now for the noise ceiling bounds:
def calculate_lower_bound_on_RAE_signed_rank_cosine_similarity_noise_ceiling(
df, df_subject, subject, subject_group
):
df_subject = pd.concat(
[
df_subject.set_index("sentence_pair"),
get_normalized_mean_RAE_signed_ranked_response(
df, subject_group, excluded_subject=subject
),
],
axis=1,
)
return calc_signed_rank_cosine_similarity_analytical_RAE(
df_subject["zero_centered_rating"],
df_subject["normalized_expected_RAE_signed_rank_response_pattern"],
)
cur_result[
"NC_LB"
] = calculate_lower_bound_on_RAE_signed_rank_cosine_similarity_noise_ceiling(
df, df_subject, subject, subject_group
)
def calculate_upper_bound_on_RAE_signed_rank_cosine_similarity_noise_ceiling(
df, df_subject, subject_group
):
df_subject = pd.concat(
[
df_subject.set_index("sentence_pair"),
get_normalized_mean_RAE_signed_ranked_response(df, subject_group),
],
axis=1,
)
return calc_semi_signed_rank_cosine_similarity_analytical_RAE(
df_subject["zero_centered_rating"],
df_subject["normalized_expected_RAE_signed_rank_response_pattern"],
)
cur_result[
"NC_UB"
] = calculate_upper_bound_on_RAE_signed_rank_cosine_similarity_noise_ceiling(
df, df_subject, subject_group
)
results.append(cur_result)
return pd.DataFrame(results)
def build_all_html_files(df):
models = get_models(df)
for model1 in models:
for model2 in models:
if model1 == model2:
continue
build_html_file(
df,
os.path.join("result_htmls", model1 + "_vs_" + model2 + ".html"),
model1,
model2,
)
def build_html_file(df, filepath, model1, model2):
"""Generate HTML files with trials organized by sentence triplets"""
triplets = organize_pairwise_data_into_triplets(df, model1, model2)
# for sorting the triplets, we calcuate triplet-level accuracy for model 1
triplet_level_accuracy = (
triplets["h_N_NS1"] / (triplets["h_N_NS1"] + triplets["h_S1_NS1"])
+ triplets["h_S2_NS2"] / (triplets["h_N_NS2"] + triplets["h_S2_NS2"])
+ triplets["h_S2_S1S2"] / (triplets["h_S1_S1S2"] + triplets["h_S2_S1S2"])
) / 3
triplets["model_1_accuracy"] = triplet_level_accuracy
ind = (-triplet_level_accuracy).argsort()
triplets = triplets.loc[ind]
with open(os.path.join("resources", "triplet_html_table_template.html"), "r") as f:
template = f.read()
html = '\
<!DOCTYPE html>\n\
<html>\n\
<head>\n\
\t<meta name="viewport" content="width=device-width, initial-scale=1">\n\
</head>\n\
<body>\n'
for i_triplet, triplet in triplets.iterrows():
new_entry = copy.copy(template)
for k, v in triplet.items():
if k.startswith("p_") and isinstance(v, float):
str_v = f"{v:.1f}"
elif k.startswith("h_") and k.endswith("_NS1"):
total = triplet["h_N_NS1"] + triplet["h_S1_NS1"]
str_v = f"{round(v):d}/{round(total):d}"
elif k.startswith("h_") and k.endswith("_NS2"):
total = triplet["h_N_NS2"] + triplet["h_S2_NS2"]
str_v = f"{round(v):d}/{round(total):d}"
elif k.startswith("h_") and k.endswith("_S1S2"):
total = triplet["h_S1_S1S2"] + triplet["h_S2_S1S2"]
str_v = f"{round(v):d}/{round(total):d}"
elif k.startswith("model") and k.endswith("_name"):
str_v = niceify(v)
else:
str_v = f"{v}"
new_entry = new_entry.replace(k, str_v)
html += new_entry
html += "\n<br>\n"
html += "\n</body>\n</head>\n"
pathlib.Path(os.path.dirname(filepath)).mkdir(parents=True, exist_ok=True)
with open(filepath, "w") as f:
template = f.write(html)
print(f"saved {filepath}")
def organize_pairwise_data_into_triplets(df, model1, model2):
"""for a pair of model, return all N vs. S and S vs. S trials organized in triplets"""
models = get_models(df)
# get only N-vs-S or S-vs-S trials in which the two models were targeted
df2 = df[
(
(
((df["sentence1_model"] == model1) & (df["sentence2_model"] == model2))
| (
(df["sentence1_model"] == model2)
& (df["sentence2_model"] == model1)
)
)
& (
df["trial_type"].isin(
["natural_vs_synthetic", "synthetic_vs_synthetic"]
)
)
)
]
# reduce subjects
df2 = df2.assign(humans_chose_sentence2=(df2["rating"] >= 4).astype(float))
df2 = df2.assign(humans_chose_sentence1=(df2["rating"] <= 3).astype(float))
df2 = df2.drop(
columns=[f"sentence1_{m}_prob" for m in models if (m not in {model1, model2})]
)
df2 = df2.drop(
columns=[f"sentence2_{m}_prob" for m in models if (m not in {model1, model2})]
)
df2 = df2.drop(columns=["subject", "Trial Number", "Reaction Time"])
df2 = (
df2.groupby(
[
"sentence_pair",
"sentence1",
"sentence2",
"sentence1_model",
"sentence2_model",
"sentence1_model_targeted_to_accept",
"sentence2_model_targeted_to_accept",
"sentence1_model_targeted_to_reject",
"sentence2_model_targeted_to_reject",
"sentence1_type",
"sentence2_type",
"trial_type",
],
dropna=False,
)
.sum()
.reset_index()
)
# further split trials to sub-types
df3_N_vs_S_model1_targeted_to_reject = df2[
(
(df2["sentence1_model_targeted_to_reject"] == model1)
& (df2["sentence2_type"] == "N")
)
| (
(df2["sentence2_model_targeted_to_reject"] == model1)
& (df2["sentence1_type"] == "N")
)
]
df3_N_vs_S_model2_targeted_to_reject = df2[
(
(df2["sentence1_model_targeted_to_reject"] == model2)
& (df2["sentence2_type"] == "N")
)
| (
(df2["sentence2_model_targeted_to_reject"] == model2)
& (df2["sentence1_type"] == "N")
)
]
df3_S_vs_S = df2[df2["trial_type"] == "synthetic_vs_synthetic"]
# these three groups should togheter consist the original set of trials
assert len(
pd.concat(
[
df3_N_vs_S_model1_targeted_to_reject,
df3_N_vs_S_model2_targeted_to_reject,
df3_S_vs_S,
]
)
) == len(df2)
# build triplets dataframe
triplets = []
for i_trial, trial in df3_N_vs_S_model1_targeted_to_reject.iterrows():
cur_triplet = dict()
cur_triplet["model1_name"] = model1
cur_triplet["model2_name"] = model2
if trial["sentence1_type"] == "N":
cur_triplet["NATURAL_SENTENCE"] = trial["sentence1"]
cur_triplet["SYNTHETIC_SENTENCE_1"] = trial["sentence2"]
cur_triplet["p_N_m1"] = trial["sentence1_" + model1 + "_prob"]
cur_triplet["p_N_m2"] = trial["sentence1_" + model2 + "_prob"]
cur_triplet["p_S1_m1"] = trial["sentence2_" + model1 + "_prob"]
cur_triplet["p_S1_m2"] = trial["sentence2_" + model2 + "_prob"]
cur_triplet["h_N_NS1"] = trial["humans_chose_sentence1"]
cur_triplet["h_S1_NS1"] = trial["humans_chose_sentence2"]
elif trial["sentence2_type"] == "N":
cur_triplet["NATURAL_SENTENCE"] = trial["sentence2"]
cur_triplet["SYNTHETIC_SENTENCE_1"] = trial["sentence1"]
cur_triplet["p_N_m1"] = trial["sentence2_" + model1 + "_prob"]
cur_triplet["p_N_m2"] = trial["sentence2_" + model2 + "_prob"]
cur_triplet["p_S1_m1"] = trial["sentence1_" + model1 + "_prob"]
cur_triplet["p_S1_m2"] = trial["sentence1_" + model2 + "_prob"]
cur_triplet["h_N_NS1"] = trial["humans_chose_sentence2"]
cur_triplet["h_S1_NS1"] = trial["humans_chose_sentence1"]
else:
raise ValueError
# find the other S vs N trial (with the model roles flipped)
other_trial = df3_N_vs_S_model2_targeted_to_reject[
(
(
df3_N_vs_S_model2_targeted_to_reject["sentence1"]
== cur_triplet["NATURAL_SENTENCE"]
)
| (
df3_N_vs_S_model2_targeted_to_reject["sentence2"]
== cur_triplet["NATURAL_SENTENCE"]
)
)
]
assert len(other_trial) == 1
other_trial = other_trial.iloc[0]
if other_trial["sentence1_type"] == "N":
cur_triplet["SYNTHETIC_SENTENCE_2"] = other_trial["sentence2"]
cur_triplet["p_S2_m1"] = other_trial["sentence2_" + model1 + "_prob"]
cur_triplet["p_S2_m2"] = other_trial["sentence2_" + model2 + "_prob"]
cur_triplet["h_N_NS2"] = other_trial["humans_chose_sentence1"]
cur_triplet["h_S2_NS2"] = other_trial["humans_chose_sentence2"]
elif other_trial["sentence2_type"] == "N":
cur_triplet["SYNTHETIC_SENTENCE_2"] = other_trial["sentence1"]
cur_triplet["p_S2_m1"] = other_trial["sentence1_" + model1 + "_prob"]
cur_triplet["p_S2_m2"] = other_trial["sentence1_" + model2 + "_prob"]
cur_triplet["h_N_NS2"] = other_trial["humans_chose_sentence2"]
cur_triplet["h_S2_NS2"] = other_trial["humans_chose_sentence1"]
else:
raise ValueError
# and now the corresponding S vs S trial
other_trial = df3_S_vs_S[
(
(
(df3_S_vs_S["sentence1"] == cur_triplet["SYNTHETIC_SENTENCE_1"])
& (df3_S_vs_S["sentence2"] == cur_triplet["SYNTHETIC_SENTENCE_2"])
)
| (
(df3_S_vs_S["sentence1"] == cur_triplet["SYNTHETIC_SENTENCE_2"])
& (df3_S_vs_S["sentence2"] == cur_triplet["SYNTHETIC_SENTENCE_1"])
)
)
]
assert len(other_trial) == 1
other_trial = other_trial.iloc[0]
if other_trial["sentence1"] == cur_triplet["SYNTHETIC_SENTENCE_1"]:
cur_triplet["h_S1_S1S2"] = other_trial["humans_chose_sentence1"]
cur_triplet["h_S2_S1S2"] = other_trial["humans_chose_sentence2"]
elif other_trial["sentence2"] == cur_triplet["SYNTHETIC_SENTENCE_1"]:
cur_triplet["h_S1_S1S2"] = other_trial["humans_chose_sentence2"]
cur_triplet["h_S2_S1S2"] = other_trial["humans_chose_sentence1"]
else:
raise ValueError
triplets.append(cur_triplet)
return pd.DataFrame(triplets)
def reduce_within_model(
df, reduction_func, models=None, trial_type=None, targeting=None
):
"""group data by targeted model and then apply reduction_func within each group"""
if models is None:
models = get_models(df)
results = []
for model in models:
# drop trials in which the model was not targeted
filtered_df = filter_trials(
df, targeted_model=model, targeting=targeting, trial_type=trial_type
)
# drop the probabilities of the other models
filtered_df = filtered_df.drop(
columns=[f"sentence1_{m}_prob" for m in models if (m != model)]
)
filtered_df = filtered_df.drop(
columns=[f"sentence2_{m}_prob" for m in models if (m != model)]
)
# reduce (e.g., calculate accuracy, correlation)
reduced_df = reduction_func(filtered_df)
if "NC_LB" in reduced_df.columns:
reduced_df = reduced_df.rename(columns={"NC_LB": "NC_LB_" + model})
if "NC_UB" in reduced_df.columns:
reduced_df = reduced_df.rename(columns={"NC_UB": "NC_UB_" + model})
results.append(reduced_df)
results = pd.concat(results)
return results
def model_specific_performace_dot_plot(
df,