-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmake_figures.qmd
1473 lines (1299 loc) · 50.5 KB
/
make_figures.qmd
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
---
title: "Plots"
description: "For _The plausibility of sampling as an algorithmic theory of sentence processing_, Open Mind, 2023"
author: "Jacob Louis Hoover"
date: 2023-05-15
toc: true
format:
html:
code-fold: true
code-tools: true
pdf:
fontsize: 10pt
monofont: Latin Modern Mono
monofontoptions:
- Scale=0.75
---
# GAM plots
::: {.callout-important icon="false" collapse="false"}
### Dependencies
- external dependencies (R files, will be sourced)
./utils/prepare_data.R
./utils/my_pacf_plot.R
- data files
./data/surprisal_densities.csv
./data/surprisal_means.csv
./data/GAM_predictions/data_to_plot_NEW_var0_gauss_wprev_N200.csv
./data/GAM_predictions/data_to_plot_NEW_var0_gauss_w3prev_N200.csv
./data/GAM_predictions/data_to_plot_NEW_lin0var_wprev_N200.csv
./data/GAM_predictions/data_to_plot_NEW_linear_wprevm_N200.csv
./data/GAM_predictions/data_to_plot_NEW_wprevm_N200.csv
./data/GAM_predictions/data_to_plot_NEW_datasubsetless6_wprevm_N200.csv
./data/GAM_predictions/data_to_plot_NEW_datasubsetless12_wprevm_N200.csv
./data/model-summaries-NEW-linear-wprevm.rds
- model training data
./data/surps_lms.RTs.perword.rds
./data/surps_lms.RTs.rds
- model file
./data/GAM_models/GPT3-davinci.rds
:::
```{r global_options}
#| code-fold: show
#| code-summary: options
# Where data lives (plot data from GAM fits, etc)
datadir <- "./data/"
# Where to put generated plots
figsdir <- "./figures/"
```
## Setup
```{r setup}
#| message: false
#| code-fold: true
#| code-summary: Setup
# knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
library(dplyr)
library(magrittr)
library(stringr)
library(ggplot2)
library(patchwork)
theme_set(theme_minimal())
theme_update(plot.title.position = "plot")
## Names
context_len_labs <- c(
max = "maximum",
`80` = "80 words",
bysent = "within sent."
)
est_type_labs <- c(
mean = "mean",
var = "variance"
)
term_labs <- c(
surprisal = "surprisal (on mean)",
`surprisal.1` = "surprisal (on log sd)"
)
model_labs <- c(
boyce_ngram = "n-gram",
boyce_grnn = "LSTM",
"TXL" = "TXL",
"GPT2" = "GPT2",
"GPT2-large" = "GPT2-large",
"GPT2-xl" = "GPT2-xl",
"GPT-Neo" = "GPT-Neo",
"GPT-J" = "GPT-J",
"GPT3-ada" = "GPT3-ada",
"GPT3-curie" = "GPT3-curie",
"GPT3-davinci" = "GPT3-davinci"
)
lm_names <- list(
"boyce_ngram", "boyce_grnn",
"TXL",
"GPT2",
"GPT2-large",
"GPT2-xl",
"GPT-Neo",
"GPT-J",
"GPT3-ada",
"GPT3-curie",
"GPT3-davinci"
) %>% set_names(., .)
## Utils
separate_modelnames <- function(df, modelnames_colname = model, names = lm_names) {
df %>%
tidyr::separate({{modelnames_colname}},
into = c("model", "by"), sep = "_", extra = "merge") %>%
mutate(model = ifelse(model == "boyce", paste0("boyce_", by), model)) %>%
mutate(context_len = ifelse(
is.na(by), "max", ifelse(stringr::str_starts(model, "boyce"), "bysent", by))
) %>% select(-by) %>%
mutate(context_len = forcats::fct_relevel(context_len, c("max")),
model = forcats::fct_relevel(model, lm_names))
}
# for nicer plot labels
my_labeller <- labeller(
context_len = context_len_labs,
term = term_labs,
model = model_labs,
est_type=c(mean="mean RT", var=glue::glue("log(sd RT)")))
```
```{r}
#| code-fold: show
#| code-summary: Options#|
# Whether to only plot two context lengths or all three
twocontexts <- TRUE # (re-run notebook after modifying)
if (twocontexts) {
context_lens <- c("max", "bysent")
context_pref <- "2"
} else {
context_lens <- c("max", "80", "bysent")
context_pref <- ""
}
```
## GAM smooths
Plotting the fits of GAM smooths for effect of surprisal on mean and variance in RT.
### Load data
```{r load_data_to_plot}
#| warning: false
#| code-fold: true
load_in_data<- function(f, with_est_types = TRUE) {
d <- readr::read_csv(f,
col_names = TRUE, show_col_types = FALSE) %>%
mutate(context_len = forcats::fct_relevel(context_len, c("max")),
model = forcats::fct_relevel(model, lm_names))
if (with_est_types) d <- d %>% mutate(est_type = factor(est_type))
return(d)
}
# get surprisal means and densities
# (from natural-stories-surprisals/EDA_surps_SPRT.Rmd)
surprisal_densities <- load_in_data(
paste0(datadir, "surprisal_densities.csv"), with_est_types = F) %>%
# there is some odd point at ~37 this makes an unnecessarily long tail
filter(model %in% lm_names, surprisal < 25)
surprisal_means <- load_in_data(
paste0(datadir, "surprisal_means.csv"), with_est_types = F) %>%
filter(model %in% lm_names)
models_in_desc_PPL_order <- surprisal_means %>%
filter(context_len == "max" | model %>% stringr::str_starts("boyce")) %>%
arrange(desc(mean_surprisal)) %>% pull(model) %>% as.vector
# GAMs fit for paper (using fitdata=surps_lms.RTs.rds, and correct lagging)
# smooth0var: nonlinear gaussian models with constant variance
data_to_plot_var0_gauss_wprev <- load_in_data(
paste0(datadir, "GAM_predictions/data_to_plot_NEW_var0_gauss_wprev_N200.csv"))
data_to_plot_var0_gauss_w3prev <- load_in_data(
paste0(datadir, "GAM_predictions/data_to_plot_NEW_var0_gauss_w3prev_N200.csv"))
##### Linear control with constant variance, with previous, with family=gaulss()
data_to_plot_lin0var_wprev <- load_in_data(
paste0(datadir, "GAM_predictions/data_to_plot_NEW_lin0var_wprev_N200.csv"))
##### Linear control with constant variance, with previous, with family=gaulss()
data_to_plot_linear_wprevm <- load_in_data(
paste0(datadir, "GAM_predictions/data_to_plot_NEW_linear_wprevm_N200.csv"))
##### Main models: Smooth GAMs with previous surprisal predictors for mean only
data_to_plot_smooth_wprevm <- load_in_data(
paste0(datadir, "GAM_predictions/data_to_plot_NEW_wprevm_N200.csv"))
#### As above (Smooth GAMs with previous surprisal for mean),
#### but removing most surprising items
# Note, only for GPT-3 Davinci full-context.
data_to_plot_datasubsetless6_smooth_wprevm <- load_in_data(
paste0(datadir, "GAM_predictions/data_to_plot_NEW_datasubsetless6_wprevm_N200.csv")) %>%
mutate(cutoff = 6)
data_to_plot_datasubsetless12_smooth_wprevm <- load_in_data(
paste0(datadir, "GAM_predictions/data_to_plot_NEW_datasubsetless12_wprevm_N200.csv")) %>%
mutate(cutoff = 12)
```
### Plot smooths
```{r}
#| code-fold: true
#| warning: false
plot_data <- function(
data_to_plot, use_shifted_est=TRUE,
se.mult=1.96, # use approx qnorm(1 - 0.05/2)
trans = I, #transform function to apply to the yvalues
controls = NULL,
surp_units = "nats",
density_df = surprisal_densities,
static_lty = NULL,
additional_controls = NULL,
ylab = "fitted effect\nestimate (+ intercept) ±2*SE",
...) {
if (surp_units == "bits") {
data_to_plot <- data_to_plot %>% mutate(surprisal = surprisal / log(2))
if (!is.null(controls)) {
controls <- controls %>% mutate(surprisal = surprisal / log(2))
}
xlab <- "surprisal (bits)"; xbreaks <- seq(0, 50, 15)
} else if (surp_units == "nats") {
xlab <- "surprisal (nats)"; xbreaks <- seq(0, 30, 10)
}
if (use_shifted_est) data_to_plot <- mutate(data_to_plot, est = est_shifted)
p <- data_to_plot %>%
ggplot(aes(x = surprisal, y = trans(est),
ymin = trans(est - se.mult*se), ymax = trans(est + se.mult*se),
fill = context_len))
if (!is.null(controls)) {
# Add in linear data
if (use_shifted_est) controls <- mutate(controls, est = est_shifted)
p <- p +
geom_ribbon(data = controls, aes(y=NULL),
fill = linear_control_color, size = 0, alpha = 0.1) +
geom_line(data = controls,
lty= linear_control_lty, color = linear_control_color,
size = linear_control_lsize, alpha= 1.0)
}
if (!is.null(additional_controls)) {
# Add in other data
if (use_shifted_est) additional_controls <- mutate(
additional_controls, est = est_shifted)
p <- p +
geom_ribbon(data = additional_controls, aes(y=NULL),
# fill = additional_control_color,
size = 0, alpha = 0.1) +
geom_line(data = additional_controls, aes(color = context_len),
lty = additional_control_lty, #color = additional_control_color,
size = additional_control_lsize, alpha= 1.0)
}
if (!is.null(density_df)) {
max_surps = data_to_plot %>% group_by(model, context_len) %>%
summarise(max_surp=max(surprisal), .groups="drop")
density_df <- density_df %>%
full_join(max_surps, by = c("model", "context_len")) %>%
filter(surprisal <= max_surp)
density_ymin <- if (use_shifted_est) 312 else -10
density_df <- mutate(density_df, density = 120 * density + density_ymin)
p <- p +
geom_line(
data = density_df %>% mutate(est_type = "mean"),
aes(ymin = NULL, ymax = NULL, y = density, x = surprisal, linetype = NULL),
linetype = "solid",
color = density_color, alpha=.35)
p <- p +
geom_ribbon(data = density_df %>% mutate(est_type = "mean"),
aes(x = surprisal, y = NULL, # forget the y aesthetic
ymin = density_ymin, ymax = density),
fill = density_color, alpha = 0.2)
}
p <- p + geom_ribbon(aes(y=NULL), alpha = 0.2, size=0)
p <- if (!is.null(static_lty)) {
p + geom_line(aes(color=context_len), linetype = static_lty)
} else {
p + geom_line(aes(color=context_len, linetype = est_type))
}
p <- p +
scale_fill_discrete(name = "context amount", labels = context_len_labs) +
scale_color_discrete(name = "context amount", labels = context_len_labs) +
scale_linetype_discrete(name = "effect", labels = est_type_labs) +
facet_grid(..., labeller = my_labeller) +
scale_x_continuous(breaks = xbreaks) +
labs(x = xlab, y=ylab)
}
plot_easy_mean_patch <- function(
data_to_plot, data_to_plot_control,
order_models_by_PPL = TRUE,
ctx_lens = context_lens, density_df = surprisal_densities,
meanbreaks = seq(-25, 500, 25), ...){
if (order_models_by_PPL) {
data_to_plot$model <- factor(
data_to_plot$model, levels = models_in_desc_PPL_order)
data_to_plot_control$model <- factor(data_to_plot_control$model, levels = models_in_desc_PPL_order)
}
which_descr <- "mean RT"
data_to_plot <- data_to_plot %>% filter(est_type=="mean")
data_to_plot_control <- data_to_plot_control %>% filter(est_type=="mean")
space <- "free"; ybreaks <- meanbreaks
static_lty = "solid"; ltyguide <- "none"
data_to_plot %>%
filter(context_len %in% ctx_lens) %>%
plot_data(controls = data_to_plot_control %>%
filter(context_len %in% ctx_lens),
density_df = density_df %>% filter(context_len %in% ctx_lens),
static_lty = static_lty,
rows =
context_len #+ est_type
~ model,
scales="free", space=space,
switch="y",
ylab = "mean RT ±2*SE",
...) +
labs(#title = "GAM fits of the effect of surprisal on reading time",
subtitle = glue::glue("Partial effect of surprisal on {which_descr}")) +
theme(
strip.placement='outside',
# axis.title.x = element_blank(), axis.text.x = element_blank(),
legend.position = c(.08,.7),
legend.background = element_rect(size = 0, color = "white")) +
# guides(linetype = ltyguide) +
scale_y_continuous(breaks = ybreaks, position = "right")
}
plot_easy_var_patch <- function(
data_to_plot, data_to_plot_control,
order_models_by_PPL = TRUE,
ctx_lens = context_lens, density_df = surprisal_densities, ...){
if (order_models_by_PPL) {
data_to_plot$model <- factor(
data_to_plot$model, levels = models_in_desc_PPL_order)
data_to_plot_control$model <- factor(
data_to_plot_control$model, levels = models_in_desc_PPL_order)
}
varbreaks <- function(x) {if (max(x)<5.3) seq(4,6,.2) else seq(3,7, .5)}
which_descr <- "log standard deviation in RT"
data_to_plot <- data_to_plot %>% filter(est_type=="var")
data_to_plot_control <- data_to_plot_control %>% filter(est_type=="var")
space <- "free"; ybreaks <- varbreaks
static_lty = variance_lty; ltyguide <- "none"
data_to_plot %>%
filter(context_len %in% ctx_lens) %>%
plot_data(controls = data_to_plot_control %>%
filter(context_len %in% ctx_lens),
density_df = NULL,
ylab = "log (sd RT) ±2*SE",
static_lty = static_lty,
rows =
context_len #+ est_type
~ model,
scales="free", space=space,
switch="y",
# trans = \(x){exp(x)^2},
...) +
labs(#title = "GAM fits of the effect of surprisal on reading time",
subtitle = glue::glue("Partial effect of surprisal on {which_descr}")) +
theme(
strip.placement='outside', strip.text.x = element_blank(),
legend.position = c(.08,.7),
legend.background = element_rect(size = 0, color = "white")) +
# guides(linetype = ltyguide) +
scale_y_continuous(breaks = ybreaks, position = "right")
}
plot_easy_both_patch <- function(
data_to_plot, data_to_plot_control,
order_models_by_PPL = TRUE,
ctx_lens = context_lens, density_df = surprisal_densities, ...) {
p_mean <- plot_easy_mean_patch(data_to_plot, data_to_plot_control,
order_models_by_PPL = order_models_by_PPL,
ctx_lens = ctx_lens, density_df = density_df, ...) +
theme(axis.title.x = element_blank(), axis.text.x = element_blank())
p_var <- plot_easy_var_patch(data_to_plot, data_to_plot_control,
order_models_by_PPL = order_models_by_PPL,
ctx_lens = ctx_lens, density_df = density_df, ...)
p_mean + p_var +
patchwork::plot_layout(ncol = 1, nrow = 2, heights = c(4,3)) +
patchwork::plot_annotation(
title = "GAM fits of the effect of surprisal on reading time"
)
}
```
```{r}
#| warning: false
density_color <- "grey"
linear_control_color <- "black"
linear_control_lty <- "13"
linear_control_lsize <- .25
variance_lty <- "31"
additional_control_color <- "grey"
additional_control_lty <- "33"
additional_control_lsize <- .25
plot_easy_mean_patch(data_to_plot_var0_gauss_wprev, data_to_plot_lin0var_wprev,
meanbreaks = seq(-25, 650, 50)) +
labs(y="RT (ms) ±2*SE",
title = "Effect of surprisal on mean RT",
subtitle = "GAMs with constant variance assumption")
### FIG FOR PAPER (3 contexts)
ggsave(
paste0(figsdir, "gauss0var", context_pref, "_wprev", "_wlinear0var_both_patch.pdf"),
width = 10.5, height = ifelse(twocontexts, 3.5, 4.5))
```
```{r}
#| code-fold: true
additional_control_color <- 3
additional_control_lty <- "33"
additional_control_lsize <- .25
plot_easy_mean_patch_3 <- function(
data_to_plot, data_to_plot_control, data_to_plot_control2,
order_models_by_PPL = TRUE,
ctx_lens = context_lens, density_df = surprisal_densities,
meanbreaks = seq(-25, 500, 25), ...){
if (order_models_by_PPL) {
data_to_plot$model <- factor(
data_to_plot$model, levels = models_in_desc_PPL_order)
data_to_plot_control$model <- factor(
data_to_plot_control$model, levels = models_in_desc_PPL_order)
}
which_descr <- "mean RT"
data_to_plot <- data_to_plot %>% filter(est_type=="mean")
data_to_plot_control <- data_to_plot_control %>% filter(est_type=="mean")
data_to_plot_control2 <- data_to_plot_control2 %>% filter(est_type=="mean")
space <- "free"; ybreaks <- meanbreaks
static_lty = "solid"; ltyguide <- "none"
data_to_plot %>%
filter(context_len %in% ctx_lens) %>%
plot_data(controls = data_to_plot_control %>%
filter(context_len %in% ctx_lens),
additional_controls = data_to_plot_control2 %>%
filter(context_len %in% ctx_lens),
density_df = density_df %>% filter(context_len %in% ctx_lens),
static_lty = static_lty,
rows =
context_len #+ est_type
~ model,
scales="free", space=space,
switch="y",
ylab = "mean RT ±2*SE",
...) +
labs(#title = "GAM fits of the effect of surprisal on reading time",
subtitle = glue::glue("Partial effect of surprisal on {which_descr}")) +
theme(
strip.placement='outside',
# axis.title.x = element_blank(), axis.text.x = element_blank(),
legend.position = c(.08,.7),
legend.background = element_rect(size = 0, color = "white")) +
scale_y_continuous(breaks = ybreaks, position = "right") +
guides(linetype = ltyguide)
}
```
```{r}
plot_easy_mean_patch_3(
data_to_plot_var0_gauss_w3prev,
data_to_plot_lin0var_wprev,
data_to_plot_var0_gauss_wprev %>% filter(est_shifted <= 500),
meanbreaks = seq(-25, 650, 50)) +
labs(y="RT (ms) ±2*SE",
title = "Effect of surprisal on mean RT, GAMs with constant variance",
subtitle = "comparing using 3 words for spillover (solid) words to just 1 (dashed)")
### FIG FOR PAPER (3 contexts)
ggsave(
paste0(figsdir, "gauss0var", context_pref, "_wprev_vs_wprev3_lin0var.pdf"),
width = 10.5, height = ifelse(twocontexts, 3.5, 4.5))
```
Main plot figure for paper:
```{r}
plot_easy_both_patch(data_to_plot_smooth_wprevm, data_to_plot_linear_wprevm)
### FIG FOR PAPER (2 and 3 contexts)
ggsave(
paste0(figsdir, "gaulss", context_pref, "_wprevm", "_wlinear_both_patch.pdf"),
width = 10.5, height = ifelse(twocontexts, 6, 7.5))
```
## Superlinearity
```{r}
#| code-fold: true
make_half_linears_dataset <- function(data_to_plot, breakpoint=0.5, se.mult=1.96) {
#" fit simple linear models to the smooth fits before and after the breakpoint
#" breakpoint should be between 0 and 1 (proportion of max surprisal to break at)
data_to_plot %>%
group_by(model, context_len) %>%
mutate(secondhalf = surprisal > max(surprisal) * breakpoint) %>%
group_by(secondhalf, est_type, .add = TRUE) %>%
do(f = broom::tidy(lm(est ~ surprisal, weights = 1/sqrt(se), data = .))) %>%
tidyr::unnest(f) %>%
mutate(lower = estimate - se.mult * std.error,
upper = estimate + se.mult * std.error) %>%
filter(term == "surprisal")
}
# half_linears3 <- make_half_linears_dataset(data_to_plot_smooth_wprevm, breakpoint=1/3)
half_linears2 <- make_half_linears_dataset(data_to_plot_smooth_wprevm, breakpoint=1/2)
# For the datasubset_lessN versions (just GPT3d for now)
half_linears2_less6 <- make_half_linears_dataset(
data_to_plot_datasubsetless6_smooth_wprevm, breakpoint=1/2)
half_linears2_less12 <- make_half_linears_dataset(
data_to_plot_datasubsetless12_smooth_wprevm, breakpoint=1/2)
make_halflinears_diffs_dataset <- function(half_linears_dataset) {
half_linears_dataset %>% group_by(model, context_len, est_type) %>%
do(diff_slope_hi_v_low =
filter(., secondhalf==TRUE)$estimate - filter(., secondhalf==FALSE)$estimate,
sum_std.error =
filter(., secondhalf==TRUE)$std.error + filter(., secondhalf==FALSE)$std.error
) %>%
tidyr::unnest(c(diff_slope_hi_v_low, sum_std.error)) %>%
mutate(upper = diff_slope_hi_v_low + 1.96 * sum_std.error,
lower = diff_slope_hi_v_low - 1.96 * sum_std.error)
}
halflinear_diffs2 <- make_halflinears_diffs_dataset(half_linears2)
# halflinear_diffs3 <- make_halflinears_diffs_dataset(half_linears3)
## Save halflinear data
# halflinear_diffs2 %>% readr::write_csv("natural-stories-surprisals/gaulss_halflinear_diffs2.csv")
# halflinear_diffs3 %>% readr::write_csv("natural-stories-surprisals/gaulss_halflinear_diffs3.csv")
```
```{r}
#| code-fold: true
## Read in halflinear data
# halflinear_diffs2 <- load_in_data("natural-stories-surprisals/gaulss_halflinear_diffs2.csv")
# halflinear_diffs3 <- load_in_data("natural-stories-surprisals/gaulss_halflinear_diffs3.csv")
halflinear_diffs2 %>% filter(context_len %in% context_lens) %>%
ggplot(aes(x = model, y = diff_slope_hi_v_low, shape = est_type,
ymin = lower, ymax = upper, color = context_len)) +
geom_hline(yintercept=0, color="gray") +
geom_errorbar(width = .25) + geom_point(size=3, alpha = .4) +
facet_grid(context_len +est_type~ model, labeller = my_labeller, scales = "free") +
scale_fill_discrete(name = "context amount", labels = context_len_labs) +
scale_color_discrete(name = "context amount", labels = context_len_labs) +
scale_shape_discrete(name = "", labels = est_type_labs) +
theme(
legend.position = c(0.08, 0.7),
axis.text.x = element_blank(),
legend.background = element_rect(size = 0, color = "white")) +
labs(
x = "model",
y = "slope at high surprisal - slope at low surprisal",
title = "Superlinearity by LM",
subtitle = "Difference in slope of smooth predictions for high vs. low surprisal")
# ggsave(
# paste0(
# figsdir, "", context_pref, "gaulss_halflinear_diffs3.pdf"),
# width = 5, height = 4)
```
#### Cutoffs most surprising words
```{r}
#| code-fold: true
#| warning: false
data_to_plot_multicutoffs <- bind_rows(
data_to_plot_smooth_wprevm, # cutoff=NA for these rows
data_to_plot_datasubsetless6_smooth_wprevm,
data_to_plot_datasubsetless12_smooth_wprevm
) %>%
mutate(cutoff = forcats::fct_rev(forcats::as_factor(cutoff)))
compare_one_model_multi_cutoffs_surprisal<-function(
data_to_plot_multicutoffs,
use_shifted_est = T, trans = I, se.mult = 1.96,
ctx_lens = context_lens, density_df = surprisal_densities,
ylab = "fitted effect\nestimate (+ intercept) ±2*SE",...) {
d <- data_to_plot_multicutoffs %>%
filter(model=="GPT3-davinci", context_len=="max", est_type == "mean")
l<- levels(d$cutoff) %>% as.numeric()
if (use_shifted_est) d <- mutate(d, est = est_shifted)
p <- d %>%
ggplot(aes(x = surprisal, y = trans(est),
color=cutoff, #linetype = !is.na(cutoff),
ymin = trans(est - se.mult*se), ymax = trans(est + se.mult*se)))
max_surps <- d %>%
group_by(model, context_len, cutoff) %>%
summarise(max_surp=max(surprisal), .groups="drop")
density_df <- density_df %>%
right_join(max_surps, by = c("model", "context_len")) %>%
filter(surprisal <= max_surp)
density_ymin <- if (use_shifted_est) 312 else -10
density_df <- mutate(density_df, density = 120 * density + density_ymin)
p <- p +
geom_line(data = density_df %>% mutate(est_type = "mean"),
aes(ymin = NULL, ymax = NULL, color = cutoff,
y = density, x = surprisal),
linetype = "solid",
alpha=.25
)
p <- p +
geom_ribbon(data = density_df %>% mutate(est_type = "mean"), inherit.aes = F,
aes(x = surprisal,
lty = NULL,
ymin = density_ymin, ymax = density),
fill = density_color, size = 2,
alpha = 0.35 / length(l))
p <- p +
# ggplot2::annotate(
# geom="text", x=l+0.1, y=312+10,
# label=glue::glue("surprisal cutoff = {l}"),
# color= "grey", size=3, vjust=1, hjust=0) +
ggplot2::annotate(
geom="segment", x=l, xend=l, y=-Inf, yend=322, color="grey")
p +
geom_line(alpha = 0.5) +
geom_ribbon(aes(y=NULL, color = NULL, fill = cutoff), alpha = 0.2, size = 0) +
# scale_fill_discrete(name = "cutoff", breaks = c(NA, l), labels = c("none", l)) +
# scale_color_discrete(name = "cutoff", breaks = c(NA, l), labels = c("none", l)) +
scale_fill_manual(name = "cutoff", values=rev(scales::hue_pal()(14)),
breaks = c(5:18,NA),
labels = c(5:18,"none")) +
scale_color_manual(name = "cutoff", values=rev(scales::hue_pal()(14)),
breaks = c(5:18,NA),
labels = c(5:18,"none")) +
scale_linetype_manual(name = "whether cutoff", values = c(`TRUE`=1, `FALSE`=3)) +
guides(linetype = "none", size = "none") +
labs(x = "surprisal (nats)", y = ylab)
}
p_gpt3_cutoffs_meaneffect <- compare_one_model_multi_cutoffs_surprisal(data_to_plot_multicutoffs) +
facet_grid( ~ model, labeller = my_labeller, scales = "free_y") +
theme(
legend.position = c(.24,.68),
legend.background = element_rect(size = 0, fill = alpha("white", 0.5), color = alpha("white", 0.5))
) +
labs(
y = "effect on mean RT ±2*SE",
subtitle="Effect of surprisal on RT",
# title="GAMs refit without highest surprisal items"
)
# ggsave(p_gpt3_cutoffs_meaneffect,
# filename = paste0(figsdir, "gpt3d_surprisal_cutoffs_effect_on_mean", ".pdf"),
# width = 3, height = 3.5)
```
### Superlinearity vs perplexity
```{r}
#| code-fold: true
#| warning: false
d <- full_join(halflinear_diffs2, surprisal_means, by = c("model", "context_len")) %>%
filter(context_len %in% context_lens, est_type == "mean") %>%
rename(diff = diff_slope_hi_v_low, sem = sum_std.error)
d %>%
filter(model %>% str_starts("GPT")) %>%
# note: `weight` aesthetic will be passed on to lm's `weights`` in geom_smooth/geom_line
ggplot(aes(x = -mean_surprisal, y = diff, color = context_len,
ymax = upper, ymin = lower, shape = context_len,
weight= 1/sqrt(sem))) +
# facet_grid(est_type ~ ., labeller = my_labeller, scales = "free_y") +
# ggpubr::stat_regline_equation(label.x.npc = .8, label.y.npc = .8,
# aes(label = after_stat(eq.label))) +
ggpubr::stat_regline_equation(
label.x.npc = .6, label.y.npc = .95,
aes(color=NULL, shape =NULL, label = after_stat(rr.label)),
color="grey", size=4, show.legend = FALSE) +
geom_smooth(
aes(color=NULL,shape =NULL),
method = "lm", formula = 'y~x', size = 0, alpha = .1, color="#f1f1f1") + # SE ribbon, no line
geom_line(
aes(color=NULL, shape =NULL), stat = "smooth",
method = "lm", formula = 'y~x', alpha = .66, lty="dotted", color="grey") + # just line
geom_errorbar(data = d, width = .03) +
geom_point(data = d, aes(fill = str_starts(model,"GPT")), size=3, alpha = .6) +
ggrepel::geom_text_repel(data = d,
aes(label = model_labs[model]),
max.overlaps = Inf, min.segment.length = 0.2, size = 3, segment.alpha = .2,
force_pull = .5, hjust = .9, box.padding = .5, color = "black", alpha = 0.4) +
theme(legend.position="top") +
scale_color_discrete(name = "context amount", labels = context_len_labs) +
scale_fill_manual(name = "GPT", values = c(`TRUE`="grey", `FALSE`="white")) +
scale_shape_manual(
values=if (twocontexts) c(21, 23) else c(21,22,23),
name = "context amount", labels = context_len_labs) +
labs(
x = "LM quality (negative log perplexity)",
y = "superlinearity",
title = "Superlinearity vs. LM quality") +
guides(fill = "none")
```
```{r}
#| warning: false
### FIG FOR PAPER
ggsave(
paste0(
figsdir, context_pref,
"gaulss_halflinear_diffs2_justFitGPTs_mean_v_mean_surprisal_lengthstogether.pdf"),
width = 7, height = 4.25)
```
#### Cutoffs superlinearity
```{r}
#| code-fold: true
halflinear_diffs2_less6 <- make_halflinears_diffs_dataset(half_linears2_less6)
halflinear_diffs2_less12 <- make_halflinears_diffs_dataset(half_linears2_less12)
p_gpt3d_cutoffs_superlinearity <- bind_rows(
halflinear_diffs2 %>% mutate(cutoff = NA) %>%
filter(model == "GPT3-davinci", context_len == "max"),
halflinear_diffs2_less6 %>% mutate(cutoff = 6),
halflinear_diffs2_less12 %>% mutate(cutoff = 12)
) %>%
filter(est_type == "mean") %>%
mutate(cutoff = factor(cutoff)) %>%
filter(context_len %in% context_lens) %>%
rename(diff = diff_slope_hi_v_low, sem = sum_std.error) %>%
ggplot(aes(x = cutoff, y = diff, color = cutoff,
ymax = upper, ymin = lower)) +
geom_errorbar(width = .03) + geom_point(size=3, alpha = .6) +
facet_grid( ~ model, labeller = my_labeller, scales = "free_y") +
scale_color_manual(name = "cutoff", values=rev(scales::hue_pal()(14)),
breaks = c(5:18,NA),
labels = c(5:18,"none")) +
scale_x_discrete(name = "cutoff",
breaks = c(5:18,NA),
labels = c(5:18,"none")) +
expand_limits(y=c(0, NA)) +
theme(legend.position = "none") +
labs(
# x = "Cutoff",
y = "superlinearity\nof effect on mean RT",
subtitle = "Superlinearity"
# title = "GAMs refit without highest surprisal items"
)
#
# ggsave(p_gpt3d_cutoffs_superlinearity,
# filename = paste0(figsdir, "gpt3d_surprisal_cutoffs", ".pdf"),
# width = 3, height = 3.5)
wrap_plots(
p_gpt3_cutoffs_meaneffect,
p_gpt3d_cutoffs_superlinearity, guides = "collect", widths = c(1.2,1)) +
plot_annotation(
title="GAMs refit without highest surprisal items")
### FIG FOR PAPER
ggsave(
filename = paste0(figsdir, "gpt3d_surprisal_cutoffs", ".pdf"),
width = 6, height = 3.5)
```
## Linear model coefficients
```{r}
#| warning: false
summaries_linear <- readr::read_rds(
paste0(datadir, "model-summaries-NEW-linear-wprevm.rds"))
linear_coefs<-purrr::map_df(
summaries_linear,
\(s) {s$p.table %>% as_tibble() %>% mutate(term=names(s$p.pv))},
.id = "model")
linear_coefs %>%
separate_modelnames() %>%
filter(context_len %in% context_lens) %>%
ggplot(aes(x=model,y=Estimate,#y=`Pr(>|z|)`,
color=context_len)) +
geom_point() + facet_wrap(~term, scales = "free", labeller=my_labeller) +
theme(axis.text.x = element_text(angle = 30, hjust = 1)) +
scale_color_discrete(name = "context amount", labels = context_len_labs)
# Whether to include both mean and variance
which_terms <- "both" # specify either "surprisal", "surprisal.1", or "both"
terms_included <- if (which_terms=="both") c("surprisal", "surprisal.1") else which_terms
linear_coefs %>%
separate_modelnames() %>%
mutate(model = dplyr::recode(model, !!!model_labs)) %>%
filter(context_len %in% context_lens) %>%
filter(term %in% terms_included) %>%
ggplot(aes(x=model,y=Estimate,
ymin=Estimate-1.96*`Std. Error`,
ymax=Estimate+1.96*`Std. Error`,
color=context_len)) +
geom_point(aes(shape=context_len)) +
geom_errorbar(width = .25, alpha=0.75) +
facet_grid(term~., scales = "free", labeller=my_labeller) +
scale_color_discrete(name = "context amount", labels = context_len_labs) +
scale_shape_manual(
values=if (twocontexts) c(1, 5) else c(1,0,5), name = "context amount",
labels = context_len_labs) +
theme(axis.text.x = element_text(angle = 30, hjust = 1),
legend.position="top") +
labs(x = "LM", y = "coefficient estimate",
title = paste0("Effect of surprisal",
" on RT and variance in RT"), #<- hardcoded for which_terms="both"
subtitle="from linear control GAMs")
### FIG FOR PAPER (2 contexts)
ggsave(
paste0(figsdir, context_pref, "gaulss_linear_coefs_", which_terms, ".pdf"),
width = 5, height = if (which_terms == "both") 4.5 else 3)
```
## Autocorrelation plots
```{r}
#| message: false
# Load a model to inspect (P)ACF of
m_wprevmk6_gpt3d <- readr::read_rds(
paste0(datadir, "GAM_models/GPT3-davinci.rds"))
# Get the data on which the model was trained:
fitdata_perword <- readr::read_rds(
paste0(datadir, "surps_lms.RTs.perword.rds"))
fitdata <- readr::read_rds(
paste0(datadir, "surps_lms.RTs.rds"))
# file prepare_data.R defines functions
# - `prepare_data_with_perword`
# - `sort_data_for_tokenization_type`
source("utils/prepare_data.R")
# prepare data as it was prepared for model when trained
data_prepared_gpt3d <- prepare_data_with_perword(
data = fitdata, data.perword = fitdata_perword,
modelname = "GPT3-davinci", how_many_prevs = 1)
```
Make function to (gg)plot ACF
```{r}
#| code-fold: true
get_clim <- function(x, ci=0.95, ci.type="white"){
#' Gets confidence limit data from acf object `x`
if (!ci.type %in% c("white", "ma")) stop('`ci.type` must be "white" or "ma"')
if (class(x) != "acf") stop('pass in object of class "acf"')
clim0 <- qnorm((1 + ci)/2) / sqrt(x$n.used)
if (ci.type == "ma") {
clim <- clim0 * sqrt(cumsum(c(1, 2 * x$acf[-1]^2)))
return(clim[-length(clim)])
} else {
return(clim0)
}
}
ggplot_acf <- function(
x,
ci=0.95, ci.type="white", ci.col = "blue"){
#' Replicates plot.acf() but using ggplot by default instead of base R plot
#' `x` must be an object of class "acf" such as that outputted by `acf()`
#' `ci.type` must be "white" or "ma"
if (!ci.type %in% c("white", "ma")) stop('`ci.type` must be "white" or "ma"')
if (class(x) != "acf") stop('pass in object of class "acf"')
with.ci <- ci > 0 && x$type != "covariance"
with.ci.ma <- with.ci && ci.type == "ma" && x$type == "correlation"
if(with.ci.ma && x$lag[1L, 1L, 1L] != 0L) {
warning("can use ci.type=\"ma\" only if first lag is 0")
with.ci.ma <- FALSE
}
clim <- get_clim(x, ci=ci, ci.type=ci.type)
df <- data.frame(lag = x$lag, acf=x$acf)
p <- ggplot(df, aes(x=lag)) +
geom_linerange(aes(ymax=acf, ymin=0)) +
labs(y="ACF", x="Lag")
if (with.ci) {
if (ci.type == "white") {
p <- p +
geom_hline(yintercept = 0-clim, lty = 2, col = ci.col) +
geom_hline(yintercept = 0+clim, lty = 2, col = ci.col)
} else if (with.ci.ma && ci.type == "ma") { # ci.type="ma" not allowed for pacf
dfclim <- df[-1,]
dfclim$clim <- clim
p <- p +
geom_line(data = dfclim, aes(y = 0-clim), lty = 2, col = ci.col) +
geom_line(data = dfclim, aes(y = 0+clim), lty = 2, col = ci.col)
}
}
return(p)
}
```
```{r acf_resid_gg}
acf_resid_gg <- function(
x, split_pred, dat, plot_sd=F, sig=F, series_length=NULL, ...){
#' x should be either a model, that is: class(x) = "bam" "gam" "glm" "lm"
#' or a numeric vector (of residuals, say)
#' sig is the significance upper and lower lines (+- 1.96)
#' series_length is the length of the series needed for sig
if(is(x,"lm")){
x <- resid(x)
} else {
if (!is(x,"numeric")) {
stop(glue::glue("Don't know what to do with input object of class {class(x)}"))
}
}
if(is.null(dat))
dat <-tibble(x=x,response=NaN)
dat$x <- NA
dat[!is.na(dat$response),]$x <- x
acf <- itsadug::acf_plot(dat$x, plot=F, split_by = split_pred, ...)
df <- tibble(acf=acf,lag=seq(0,length(acf)-1))
p <- df %>%
ggplot(aes(x=lag,y=acf)) +
geom_col(width=0.1, alpha=0.9) +
geom_point()
if(plot_sd){
df <- df %>%
mutate(sd=itsadug::acf_plot(dat$x, fun=sd, plot=F, split_by = split_pred, ...))
p <- df %>%
ggplot(aes(x=lag,y=acf)) +
geom_col(width=0.4, alpha=0.5) +
geom_errorbar(aes(ymin=acf-1.96*sd,ymax=acf+1.96*sd), width=0.3, color="red")
}
if(sig){
if(is.null(series_length)) { stop(glue::glue("You must specify series length")) }
sig <- qnorm(1 - 0.05 / 2) / sqrt(series_length)
p <- p +
geom_hline(yintercept = 0 - sig, lty = 2, color = "blue") +
geom_hline(yintercept = 0 + sig, lty = 2, color = "blue")
}
return(p)
}
```
Data ordering
: When plotting GAM fits (with `plot.gam()` for example) it doesn't matter what order the data is in but when plotting ACF of residuals the order of the data does matter. So be careful (note, for `itsadug::acf_resid`, with the right `split_pred` selected, it will work).
```{r add_resids}
# Let's get the residuals and then put them in the right order,
# that is, sort by subject > story_num > word_num_in_story.
assertthat::are_equal( # note: already removed NAs so nothing to worry about there
data_prepared_gpt3d %>% nrow,
resid(m_wprevmk6_gpt3d) %>% length)
data_prepared_gpt3d_withresids <- data_prepared_gpt3d
data_prepared_gpt3d_withresids$resids <- resid(m_wprevmk6_gpt3d)
data_resorted <- arrange(
data_prepared_gpt3d_withresids, subject, story_num, word_num_in_story)
```
Thee dataframe `data_resorted` will now work for getting ACF of resids. Just one more thing: We just need to subset the data to remove the handful of observations from workers who only started stories, but didn't get far (this messes up getting ACF plots for reasons I'm unsure of). Since it's only a very small number of items, this won't affect the autocorrelation results much.
```{r subset_workers}
subset_workers<-function(nItems_threshold_productive = 1000, data=fitdata){
how_many_stories_per_worker <- data %>% group_by(WorkerId) %>%
summarise(n_stories=n_distinct(story_num)) %>% arrange(desc(n_stories))
how_many_items_per_worker <- data %>% group_by(WorkerId) %>%