forked from gavinsimpson/intro-gam-webinar-2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gam-intro.Rmd
1990 lines (1364 loc) · 51.7 KB
/
gam-intro.Rmd
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: "Introduction to Generalized Additive Models with R and mgcv"
author: "Gavin Simpson"
date: "1000–1230 CST (1600–1830 UTC) July 30th, 2020"
output:
xaringan::moon_reader:
css: ['default', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', 'slides.css']
lib_dir: libs
nature:
titleSlideClass: ['inverse','middle','left',my-title-slide]
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
beforeInit: "macros.js"
ratio: '16:9'
---
class: inverse middle center big-subsection
```{r setup, include=FALSE, cache=FALSE}
options(htmltools.dir.version = FALSE)
knitr::opts_chunk$set(cache = TRUE, dev = 'svg', echo = TRUE, message = FALSE, warning = FALSE,
fig.height=6, fig.width = 1.777777*6)
library('here')
library('mgcv')
library('gratia')
library('gamair')
library('ggplot2')
library('purrr')
library('mvnfast')
library("tibble")
library('gganimate')
library('cowplot')
library('tidyr')
library("knitr")
library("viridis")
library('readr')
library('dplyr')
library('gganimate')
## plot defaults
theme_set(theme_minimal(base_size = 16, base_family = 'Fira Sans'))
## constants
anim_width <- 1000
anim_height <- anim_width / 1.77777777
anim_dev <- 'png'
anim_res <- 200
```
# Welcome
???
I'm live streaming today from Treaty 4 lands. These are the territories of the nêhiyawak (nay-hi-yuh-wuk, Cree), Anihšināpēk (uh-nish-i-naa-payk, Saulteaux), Dakota, Lakota, Nakoda, and the homeland of the Métis/Michif Nation. Today, these lands continue to be the shared territory of many diverse peoples.
---
# Logistics
## Slides
Slidedeck: [bit.ly/gam-webinar](https://bit.ly/gam-webinar)
Sources: [bit.ly/gam-webinar-git](https://bit.ly/gam-webinar-git)
Direct download a ZIP of everything: [bit.ly/gam-webinar-zip](https://bit.ly/gam-webinar-zip)
Unpack the zip & remember where you put it
## Q & A
Add questions to Google Doc: [bit.ly/gam-webinar-qa](https://bit.ly/gam-webinar-qa)
## Recording
Livestream will be recorded — [youtu.be/sgw4cu8hrZM](https://youtu.be/sgw4cu8hrZM)
---
# Donation
In lieu of not charging for this webinar, if you are able to, financially, please make a donation to the University of Regina's **Student Emergency Fund**
<https://giving.uregina.ca/student-emergency-fund>
---
# Today's topics
* What are GAMs?
* How to fit GAMs in R with **mgcv**
* Model Checking
* Model Diagnostics
* Examples
---
class: inverse middle center subsection
# Motivating example
---
# HadCRUT4 time series
```{r hadcrut-temp-example, echo = FALSE}
library('readr')
library('dplyr')
URL <- "https://bit.ly/hadcrutv4"
gtemp <- read_delim(URL, delim = ' ', col_types = 'nnnnnnnnnnnn', col_names = FALSE) %>%
select(num_range('X', 1:2)) %>% setNames(nm = c('Year', 'Temperature'))
## Plot
gtemp_plt <- ggplot(gtemp, aes(x = Year, y = Temperature)) +
geom_line() +
geom_point() +
labs(x = 'Year', y = expression(Temeprature ~ degree*C))
gtemp_plt
```
???
Hadley Centre NH temperature record ensemble
How would you model the trend in these data?
---
# Linear Models
$$y_i \sim \mathcal{N}(\mu_i, \sigma^2)$$
$$\mu_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + \cdots + \beta_j x_{ji}$$
Assumptions
1. linear effects of covariates are good approximation of the true effects
2. conditional on the values of covariates, $y_i | \mathbf{X} \sim \mathcal{N}(0, \sigma^2)$
3. this implies all observations have the same *variance*
4. $y_i | \mathbf{X}$ are *independent*
An **additive** model address the first of these
---
class: inverse center middle subsection
# Why bother with anything more complex?
---
# Is this linear?
```{r hadcrut-temp-example, echo = FALSE}
```
---
# Polynomials perhaps…
```{r hadcrut-temp-polynomial, echo = FALSE}
p <- c(1,3,8,15)
N <- 300
newd <- with(gtemp, data.frame(Year = seq(min(Year), max(Year), length = N)))
polyFun <- function(i, data = data) {
lm(Temperature ~ poly(Year, degree = i), data = data)
}
mods <- lapply(p, polyFun, data = gtemp)
pred <- vapply(mods, predict, numeric(N), newdata = newd)
colnames(pred) <- p
newd <- cbind(newd, pred)
polyDat <- gather(newd, Degree, Fitted, - Year)
polyDat <- mutate(polyDat, Degree = ordered(Degree, levels = p))
gtemp_plt + geom_line(data = polyDat, mapping = aes(x = Year, y = Fitted, colour = Degree),
size = 1.5, alpha = 0.9) +
scale_color_brewer(name = "Degree", palette = "PuOr") +
theme(legend.position = "right")
```
---
# Polynomials perhaps…
We can keep on adding ever more powers of $\boldsymbol{x}$ to the model — model selection problem
**Runge phenomenon** — oscillations at the edges of an interval — means simply moving to higher-order polynomials doesn't always improve accuracy
---
class: inverse middle center subsection
# GAMs offer a solution
---
# HadCRUT data set
```{r read-hadcrut, echo = TRUE}
library('readr')
library('dplyr')
URL <- "https://bit.ly/hadcrutv4"
gtemp <- read_delim(URL, delim = ' ', col_types = 'nnnnnnnnnnnn', col_names = FALSE) %>%
select(num_range('X', 1:2)) %>% setNames(nm = c('Year', 'Temperature'))
```
[File format](https://www.metoffice.gov.uk/hadobs/hadcrut4/data/current/series_format.html)
---
# HadCRUT data set
```{r show-hadcrut, echo = TRUE}
gtemp
```
---
# Fitting a GAM
```{r hadcrutemp-fitted-gam, echo = TRUE, results = 'hide'}
library('mgcv')
m <- gam(Temperature ~ s(Year), data = gtemp, method = 'REML')
summary(m)
```
.smaller[
```{r hadcrutemp-fitted-gam, echo = FALSE}
```
]
---
# Fitted GAM
```{r hadcrtemp-plot-gam, echo = FALSE}
N <- 300
newd <- as_tibble(with(gtemp, data.frame(Year = seq(min(Year), max(Year), length = N))))
pred <- as_tibble(as.data.frame(predict(m, newdata = newd, se.fit = TRUE,
unconditional = TRUE)))
pred <- bind_cols(newd, pred) %>%
mutate(upr = fit + 2 * se.fit, lwr = fit - 2*se.fit)
ggplot(gtemp, aes(x = Year, y = Temperature)) +
geom_point() +
geom_ribbon(data = pred,
mapping = aes(ymin = lwr, ymax = upr, x = Year), alpha = 0.4, inherit.aes = FALSE,
fill = "#fdb338") +
geom_line(data = pred,
mapping = aes(y = fit, x = Year), inherit.aes = FALSE, size = 1, colour = "#025196") +
labs(x = 'Year', y = expression(Temeprature ~ degree*C))
```
---
class: inverse middle center big-subsection
# GAMs
---
# Generalized Additive Models
<br />
![](resources/tradeoff-slider.png)
.references[Source: [GAMs in R by Noam Ross](https://noamross.github.io/gams-in-r-course/)]
???
GAMs are an intermediate-complexity model
* can learn from data without needing to be informed by the user
* remain interpretable because we can visualize the fitted features
---
# How is a GAM different?
In LM we model the mean of data as a sum of linear terms:
$$y_i = \beta_0 +\sum_j \color{red}{ \beta_j x_{ji}} +\epsilon_i$$
A GAM is a sum of _smooth functions_ or _smooths_
$$y_i = \beta_0 + \sum_j \color{red}{s_j(x_{ji})} + \epsilon_i$$
where $\epsilon_i \sim N(0, \sigma^2)$, $y_i \sim \text{Normal}$ (for now)
Call the above equation the **linear predictor** in both cases
---
# Fitting a GAM in R
```r
model <- gam(y ~ s(x1) + s(x2) + te(x3, x4), # formuala describing model
data = my_data_frame, # your data
method = 'REML', # or 'ML'
family = gaussian) # or something more exotic
```
`s()` terms are smooths of one or more variables
`te()` terms are the smooth equivalent of *main effects + interactions*
---
# How did `gam()` *know*?
```{r hadcrtemp-plot-gam, echo = FALSE}
```
---
class: inverse
background-image: url('./resources/rob-potter-398564.jpg')
background-size: contain
# What magic is this?
.footnote[
<a style="background-color:black;color:white;text-decoration:none;padding:4px 6px;font-family:-apple-system, BlinkMacSystemFont, "San Francisco", "Helvetica Neue", Helvetica, Ubuntu, Roboto, Noto, "Segoe UI", Arial, sans-serif;font-size:12px;font-weight:bold;line-height:1.2;display:inline-block;border-radius:3px;" href="https://unsplash.com/@robpotter?utm_medium=referral&utm_campaign=photographer-credit&utm_content=creditBadge" target="_blank" rel="noopener noreferrer" title="Download free do whatever you want high-resolution photos from Rob Potter"><span style="display:inline-block;padding:2px 3px;"><svg xmlns="http://www.w3.org/2000/svg" style="height:12px;width:auto;position:relative;vertical-align:middle;top:-1px;fill:white;" viewBox="0 0 32 32"><title></title><path d="M20.8 18.1c0 2.7-2.2 4.8-4.8 4.8s-4.8-2.1-4.8-4.8c0-2.7 2.2-4.8 4.8-4.8 2.7.1 4.8 2.2 4.8 4.8zm11.2-7.4v14.9c0 2.3-1.9 4.3-4.3 4.3h-23.4c-2.4 0-4.3-1.9-4.3-4.3v-15c0-2.3 1.9-4.3 4.3-4.3h3.7l.8-2.3c.4-1.1 1.7-2 2.9-2h8.6c1.2 0 2.5.9 2.9 2l.8 2.4h3.7c2.4 0 4.3 1.9 4.3 4.3zm-8.6 7.5c0-4.1-3.3-7.5-7.5-7.5-4.1 0-7.5 3.4-7.5 7.5s3.3 7.5 7.5 7.5c4.2-.1 7.5-3.4 7.5-7.5z"></path></svg></span><span style="display:inline-block;padding:2px 3px;">Rob Potter</span></a>
]
---
class: inverse
background-image: url('resources/wiggly-things.png')
background-size: contain
???
---
```{r smooth-fun-animation, results = FALSE, echo = FALSE}
f <- function(x) {
x^11 * (10 * (1 - x))^6 + ((10 * (10 * x)^3) * (1 - x)^10)
}
draw_beta <- function(n, k, mu = 1, sigma = 1) {
rmvn(n = n, mu = rep(mu, k), sigma = diag(rep(sigma, k)))
}
weight_basis <- function(bf, x, n = 1, k, ...) {
beta <- draw_beta(n = n, k = k, ...)
out <- sweep(bf, 2L, beta, '*')
colnames(out) <- paste0('f', seq_along(beta))
out <- as_tibble(out)
out <- add_column(out, x = x)
out <- pivot_longer(out, -x, names_to = 'bf', values_to = 'y')
out
}
random_bases <- function(bf, x, draws = 10, k, ...) {
out <- rerun(draws, weight_basis(bf, x = x, k = k, ...))
out <- bind_rows(out)
out <- add_column(out, draw = rep(seq_len(draws), each = length(x) * k),
.before = 1L)
class(out) <- c("random_bases", class(out))
out
}
plot.random_bases <- function(x, facet = FALSE) {
plt <- ggplot(x, aes(x = x, y = y, colour = bf)) +
geom_line(lwd = 1, alpha = 0.75) +
guides(colour = FALSE)
if (facet) {
plt + facet_wrap(~ draw)
}
plt
}
normalize <- function(x) {
rx <- range(x)
z <- (x - rx[1]) / (rx[2] - rx[1])
z
}
set.seed(1)
N <- 500
data <- tibble(x = runif(N),
ytrue = f(x),
ycent = ytrue - mean(ytrue),
yobs = ycent + rnorm(N, sd = 0.5))
k <- 10
knots <- with(data, list(x = seq(min(x), max(x), length = k)))
sm <- smoothCon(s(x, k = k, bs = "cr"), data = data, knots = knots)[[1]]$X
colnames(sm) <- levs <- paste0("f", seq_len(k))
basis <- pivot_longer(cbind(sm, data), -(x:yobs), names_to = 'bf')
basis
set.seed(2)
bfuns <- random_bases(sm, data$x, draws = 20, k = k)
smooth <- bfuns %>%
group_by(draw, x) %>%
summarise(spline = sum(y)) %>%
ungroup()
p1 <- ggplot(smooth) +
geom_line(data = smooth, aes(x = x, y = spline), lwd = 1.5) +
labs(y = 'f(x)', x = 'x') +
theme_minimal(base_size = 16, base_family = 'Fira Sans')
smooth_funs <- animate(
p1 + transition_states(draw, transition_length = 4, state_length = 2) +
ease_aes('cubic-in-out'),
nframes = 200, height = anim_height, width = anim_width, res = anim_res, dev = anim_dev)
anim_save('resources/spline-anim.gif', smooth_funs)
```
# Wiggly things
.center[![](resources/spline-anim.gif)]
???
GAMs use splines to represent the non-linear relationships between covariates, here `x`, and the response variable on the `y` axis.
---
# Basis expansions
In the polynomial models we used a polynomial basis expansion of $\boldsymbol{x}$
* $\boldsymbol{x}^0 = \boldsymbol{1}$ — the model constant term
* $\boldsymbol{x}^1 = \boldsymbol{x}$ — linear term
* $\boldsymbol{x}^2$
* $\boldsymbol{x}^3$
* …
---
# Splines
Splines are *functions* composed of simpler functions
Simpler functions are *basis functions* & the set of basis functions is a *basis*
When we model using splines, each basis function $b_k$ has a coefficient $\beta_k$
Resultant spline is a the sum of these weighted basis functions, evaluated at the values of $x$
$$s(x) = \sum_{k = 1}^K \beta_k b_k(x)$$
---
# Splines formed from basis functions
```{r basis-functions, fig.height=6, fig.width = 1.777777*6, echo = FALSE}
ggplot(basis,
aes(x = x, y = value, colour = bf)) +
geom_line(lwd = 2, alpha = 0.5) +
guides(colour = FALSE) +
labs(x = 'x', y = 'b(x)') +
theme_minimal(base_size = 20, base_family = 'Fira Sans')
```
???
Splines are built up from basis functions
Here I'm showing a cubic regression spline basis with 10 knots/functions
We weight each basis function to get a spline. Here all the basisi functions have the same weight so they would fit a horizontal line
---
# Weight basis functions ⇨ spline
```{r basis-function-animation, results = 'hide', echo = FALSE}
bfun_plt <- plot(bfuns) +
geom_line(data = smooth, aes(x = x, y = spline),
inherit.aes = FALSE, lwd = 1.5) +
labs(x = 'x', y = 'f(x)') +
theme_minimal(base_size = 14, base_family = 'Fira Sans')
bfun_anim <- animate(
bfun_plt + transition_states(draw, transition_length = 4, state_length = 2) +
ease_aes('cubic-in-out'),
nframes = 200, height = anim_height, width = anim_width, res = anim_res, dev = anim_dev)
anim_save('resources/basis-fun-anim.gif', bfun_anim)
```
.center[![](resources/basis-fun-anim.gif)]
???
But if we choose different weights we get more wiggly spline
Each of the splines I showed you earlier are all generated from the same basis functions but using different weights
---
# How do GAMs learn from data?
```{r example-data-figure, fig.height=6, fig.width = 1.777777*6, echo = FALSE}
data_plt <- ggplot(data, aes(x = x, y = ycent)) +
geom_line(col = 'goldenrod', lwd = 2) +
geom_point(aes(y = yobs), alpha = 0.2, size = 3) +
labs(x = 'x', y = 'f(x)') +
theme_minimal(base_size = 20, base_family = 'Fira Sans')
data_plt
```
???
How does this help us learn from data?
Here I'm showing a simulated data set, where the data are drawn from the orange functions, with noise. We want to learn the orange function from the data
---
# Maximise penalised log-likelihood ⇨ β
```{r basis-functions-anim, results = "hide", echo = FALSE}
sm2 <- smoothCon(s(x, k = k, bs = "cr"), data = data, knots = knots)[[1]]$X
beta <- coef(lm(ycent ~ sm2 - 1, data = data))
wtbasis <- sweep(sm2, 2L, beta, FUN = "*")
colnames(wtbasis) <- colnames(sm2) <- paste0("F", seq_len(k))
## create stacked unweighted and weighted basis
basis <- as_tibble(rbind(sm2, wtbasis)) %>%
add_column(x = rep(data$x, times = 2),
type = rep(c('unweighted', 'weighted'), each = nrow(sm2)),
.before = 1L)
##data <- cbind(data, fitted = rowSums(scbasis))
wtbasis <- as_tibble(rbind(sm2, wtbasis)) %>%
add_column(x = rep(data$x, times = 2),
fitted = rowSums(.),
type = rep(c('unweighted', 'weighted'), each = nrow(sm2))) %>%
pivot_longer(-(x:type), names_to = 'bf')
basis <- pivot_longer(basis, -(x:type), names_to = 'bf')
p3 <- ggplot(data, aes(x = x, y = ycent)) +
geom_point(aes(y = yobs), alpha = 0.2) +
geom_line(data = basis,
mapping = aes(x = x, y = value, colour = bf),
lwd = 1, alpha = 0.5) +
geom_line(data = wtbasis,
mapping = aes(x = x, y = fitted), lwd = 1, colour = 'black', alpha = 0.75) +
guides(colour = FALSE) +
labs(y = 'f(x)', x = 'x') +
theme_minimal(base_size = 16, base_family = 'Fira Sans')
crs_fit <- animate(p3 + transition_states(type, transition_length = 4, state_length = 2) +
ease_aes('cubic-in-out'),
nframes = 100, height = anim_height, width = anim_width, res = anim_res,
dev = anim_dev)
anim_save('./resources/gam-crs-animation.gif', crs_fit)
```
.center[![](resources/gam-crs-animation.gif)]
???
Fitting a GAM involves finding the weights for the basis functions that produce a spline that fits the data best, subject to some constraints
---
class: inverse middle center subsection
# Avoid overfitting our sample
---
class: inverse center middle large-subsection
# How wiggly?
$$
\int_{\mathbb{R}} [f^{\prime\prime}]^2 dx = \boldsymbol{\beta}^{\mathsf{T}}\mathbf{S}\boldsymbol{\beta}
$$
---
class: inverse center middle large-subsection
# Penalised fit
$$
\mathcal{L}_p(\boldsymbol{\beta}) = \mathcal{L}(\boldsymbol{\beta}) - \frac{1}{2} \lambda\boldsymbol{\beta}^{\mathsf{T}}\mathbf{S}\boldsymbol{\beta}
$$
---
# Wiggliness
$$\int_{\mathbb{R}} [f^{\prime\prime}]^2 dx = \boldsymbol{\beta}^{\mathsf{T}}\mathbf{S}\boldsymbol{\beta} = \large{W}$$
(Wiggliness is 100% the right mathy word)
We penalize wiggliness to avoid overfitting
---
# Making wiggliness matter
$W$ measures **wiggliness**
(log) likelihood measures closeness to the data
We use a **smoothing parameter** $\lambda$ to define the trade-off, to find
the spline coefficients $B_k$ that maximize the **penalized** log-likelihood
$$\mathcal{L}_p = \log(\text{Likelihood}) - \lambda W$$
---
# HadCRUT4 time series
```{r hadcrut-temp-penalty, echo = FALSE}
K <- 40
lambda <- c(10000, 1, 0.01, 0.00001)
N <- 300
newd <- with(gtemp, data.frame(Year = seq(min(Year), max(Year), length = N)))
fits <- lapply(lambda, function(lambda) gam(Temperature ~ s(Year, k = K, sp = lambda), data = gtemp))
pred <- vapply(fits, predict, numeric(N), newdata = newd)
op <- options(scipen = 100)
colnames(pred) <- lambda
newd <- cbind(newd, pred)
lambdaDat <- gather(newd, Lambda, Fitted, - Year)
lambdaDat <- transform(lambdaDat, Lambda = factor(paste("lambda ==", as.character(Lambda)),
levels = paste("lambda ==", as.character(lambda))))
gtemp_plt + geom_line(data = lambdaDat, mapping = aes(x = Year, y = Fitted, group = Lambda),
size = 1, colour = "#e66101") +
facet_wrap( ~ Lambda, ncol = 2, labeller = label_parsed)
options(op)
```
---
# Picking the right wiggliness
.pull-left[
Two ways to think about how to optimize $\lambda$:
* Predictive: Minimize out-of-sample error
* Bayesian: Put priors on our basis coefficients
]
.pull-right[
Many methods: AIC, Mallow's $C_p$, GCV, ML, REML
* **Practically**, use **REML**, because of numerical stability
* Hence `gam(..., method='REML')`
]
.center[
![Animation of derivatives](./resources/remlgcv.png)
]
---
# Maximum allowed wiggliness
We set **basis complexity** or "size" $k$
This is _maximum wigglyness_, can be thought of as number of small functions that make up a curve
Once smoothing is applied, curves have fewer **effective degrees of freedom (EDF)**
EDF < $k$
---
# Maximum allowed wiggliness
$k$ must be *large enough*, the $\lambda$ penalty does the rest
*Large enough* — space of functions representable by the basis includes the true function or a close approximation to the tru function
Bigger $k$ increases computational cost
In **mgcv**, default $k$ values are arbitrary — after choosing the model terms, this is the key user choice
**Must be checked!** — `gam.check()`
---
# GAM summary so far
1. GAMs give us a framework to model flexible nonlinear relationships
2. Use little functions (**basis functions**) to make big functions (**smooths**)
3. Use a **penalty** to trade off wiggliness/generality
4. Need to make sure your smooths are **wiggly enough**
---
class: middle center inverse subsection
# Example
---
# Portugese larks
.row[
.col-7[
```{r birds-1, echo = TRUE}
library('gamair')
data(bird)
bird <- transform(bird,
crestlark = factor(crestlark),
linnet = factor(linnet),
e = x / 1000,
n = y / 1000)
head(bird)
```
]
.col-5[
```{r birds-2, fig.width = 5, fig.height = 6, echo = FALSE}
ggplot(bird, aes(x = e, y = n, colour = crestlark)) + geom_point(size = 0.5) + coord_fixed() + scale_colour_discrete(na.value = '#bbbbbb33') + labs(x = NULL, y = NULL)
```
]
]
---
# Portugese larks — binomial GAM
.row[
.col-6[
```{r birds-gam-1, echo = TRUE}
crest <- gam(crestlark ~ s(e, n, k = 100),
data = bird,
family = binomial,
method = 'REML')
```
$s(e, n)$ indicated by `s(e, n)` in the formula
Isotropic thin plate spline
`k` sets size of basis dimension; upper limit on EDF
Smoothness parameters estimated via REML
]
.col-6[
.smaller[
```{r birds-gam-2, echo = TRUE}
summary(crest)
```
]
]
]
---
# Portugese larks — binomial GAM
Model checking with binary data is a pain — residuals look weird
Alternatively we can aggregate data at the `QUADRICULA` level & fit a binomial count model
.smaller[
```{r munge-larks, echo = TRUE}
## convert back to numeric
bird <- transform(bird,
crestlark = as.numeric(as.character(crestlark)),
linnet = as.numeric(as.character(linnet)))
## some variables to help aggregation
bird <- transform(bird, tet.n = rep(1, nrow(bird)),
N = rep(1, nrow(bird)), stringsAsFactors = FALSE)
## set to NA if not surveyed
bird$N[is.na(as.vector(bird$crestlark))] <- NA
## aggregate
bird2 <- aggregate(data.matrix(bird), by = list(bird$QUADRICULA),
FUN = sum, na.rm = TRUE)
## scale by Quads aggregated
bird2 <- transform(bird2, e = e / tet.n, n = n / tet.n)
## fit binomial GAM
crest2 <- gam(cbind(crestlark, N - crestlark) ~ s(e, n, k = 100),
data = bird2, family = binomial, method = 'REML')
```
]
---
# Model checking
.pull-left[
.smaller[
```{r crest-3, echo = TRUE}
crest3 <- gam(cbind(crestlark, N - crestlark) ~
s(e, n, k = 100),
data = bird2, family = quasibinomial,
method = 'REML')
```
]
Model residuals don't look too bad
Bands of points due to integers
Some overdispersion — φ = `r round(crest3$scale,2)`
]
.pull-right[
```{r gam-check-aggregated-lark, echo = TRUE, fig.width = 4.5, fig.height = 4}
ggplot(data.frame(Fitted = fitted(crest2),
Resid = resid(crest2)),
aes(Fitted, Resid)) + geom_point()
```
]
---
class: inverse middle center subsection
# A cornucopia of smooths
---
# A cornucopia of smooths
The type of smoother is controlled by the `bs` argument (think *basis*)
The default is a low-rank thin plate spline `bs = 'tp'`
Many others available
.row[
.col-6[
* Cubic splines `bs = 'cr'`
* P splines `bs = 'ps'`
* Cyclic splines `bs = 'cc'` or `bs = 'cp'`
* Adaptive splines `bs = 'ad'`
* Random effect `bs = 're'`
* Factor smooths `bs = 'fs'`
]
.col-6[
* Duchon splines `bs = 'ds'`
* Spline on the sphere `bs = 'sos'`
* MRFs `bs = 'mrf'`
* Soap-film smooth `bs = 'so'`
* Gaussian process `bs = 'gp'`
]
]
---
# A bestiary of conditional distributions
A GAM is just a fancy GLM
Simon Wood & colleagues (2016) have extended the *mgcv* methods to some non-exponential family distributions
.row[
.col-6[
* `binomial()`
* `poisson()`
* `Gamma()`
* `inverse.gaussian()`
* `nb()`
* `tw()`
* `mvn()`
* `multinom()`
]
.col-6[
* `betar()`
* `scat()`
* `gaulss()`
* `ziplss()`
* `twlss()`
* `cox.ph()`
* `gamals()`
* `ocat()`
]
]
---
# Smooth interactions
Two ways to fit smooth interactions
1. Bivariate (or higher order) thin plate splines
* `s(x, z, bs = 'tp')`
* Isotropic; single smoothness parameter for the smooth
* Sensitive to scales of `x` and `z`
2. Tensor product smooths
* Separate marginal basis for each smooth, separate smoothness parameters
* Invariant to scales of `x` and `z`
* Use for interactions when variables are in different units
* `te(x, z)`
---
# Tensor product smooths
There are multiple ways to build tensor products in *mgcv*
1. `te(x, z)`
2. `t2(x, z)`
3. `s(x) + s(z) + ti(x, z)`
`te()` is the most general form but not usable in `gamm4::gamm4()` or *brms*
`t2()` is an alternative implementation that does work in `gamm4::gamm4()` or *brms*
`ti()` fits pure smooth interactions; where the main effects of `x` and `z` have been removed from the basis
---
# Factor smooth interactions
Two ways for factor smooth interactions
1. `by` variable smooths
* entirely separate smooth function for each level of the factor
* each has it's own smoothness parameter
* centred (no group means) so include factor as a fixed effect
* `y ~ f + s(x, by = f)`
2. `bs = 'fs'` basis
* smooth function for each level of the function
* share a common smoothness parameter
* fully penalized; include group means
* closer to random effects
* `y ~ s(x, f, bs = 'fs')`
---
# Random effects
When fitted with REML or ML, smooths can be viewed as just fancy random effects
Inverse is true too; random effects can be viewed as smooths
If you have simple random effects you can fit those in `gam()` and `bam()` without needing the more complex GAMM functions `gamm()` or `gamm4::gamm4()`
These two models are equivalent
```{r ranefs}
m_nlme <- lme(travel ~ 1, data = Rail, ~ 1 | Rail, method = "REML")
m_gam <- gam(travel ~ s(Rail, bs = "re"), data = Rail, method = "REML")
```
---
# Random effects
The random effect basis `bs = 're'` is not as computationally efficient as *nlme* or *lme4* for fitting
* complex random effects terms, or
* random effects with many levels
Instead see `gamm()` and `gamm4::gamm4()`
* `gamm()` fits using `lme()`
* `gamm4::gamm4()` fits using `lmer()` or `glmer()`
For non Gaussian models use `gamm4::gamm4()`
---
class: inverse center middle subsection
# Model checking
---
# Model checking
So you have a GAM:
- How do you know you have the right degrees of freedom? `gam.check()`
- Diagnosing model issues: `gam.check()` part 2
---
# GAMs are models too
How accurate your predictions will be depends on how good the model is
```{r misspecify, echo = FALSE}
set.seed(15)
model_list = c("right model",
"wrong distribution",
"heteroskedasticity",
"dependent data",
"wrong functional form")
n <- 60
sigma=1
x <- seq(-1,1, length=n)
model_data <- as.data.frame(expand.grid( x=x,model=model_list))
model_data$y <- 5*model_data$x^2 + 2*model_data$x
for(i in model_list){