-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathslides.Rmd
2210 lines (1518 loc) · 67.2 KB
/
slides.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: "Multilevel Regression and Post-stratification"
author: "Douglas Rivers"
date: "May 15, 2018"
output:
beamer_presentation:
fig_caption: false
includes:
in_header: scripts/header.tex
classoption: "aspectratio=169"
always_allow_html: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
options(width=85)
```
## Course Schedule
| Time | Topics |
|-------------|--------------------------------|
| 2:30 - 3:15 | Overview and Examples |
| 3:15 - 4:00 | Post-stratification |
| 4:00 - 4:45 | Multilevel Regression |
| 4:45 - 5:30 | Bayesian inference |
| 5:30 - 6:00 | Advanced topics and discussion |
## Course materials and basic R setup
Slides, code, and datasets can be downloaded from Github:
<https://github.com/rdrivers/mrp-aapor>
If you wish to run the examples shown in class, you will need to
1. Download R from one of the sites listed at <https://cran.r-project.org/mirrors.html> and install. R is an open source programming environment for statistical computing.
2. (Optional) Download RStudio Desktop from <https://www.rstudio.com//>. RStudio is an integrated development environment for R. The free open source version is recommended.
3. Start R or RStudio and enter the following at the R command prompt:
\footnotesize
```{r, eval=FALSE, echo=TRUE}
install.packages(c("tidyverse", "lme4", "survey", "arm", "maps", "mapproj",
"gridExtra"))
```
# 1. Overview and Examples
## What is MRP?
![](images/mrp-stan-tweet.png)
\centering
\LARGE
Formally, **M**ultilevel **R**egression and **P**ost-stratificaiton
\medskip
\centering
\LARGE
Informally, **Mr. P**
## Who is the ubiquitous Mr. P?
\columnsbegin
\column{.3\textwidth}
```{r, out.width = "1.5in"}
knitr::include_graphics("images/gelman.jpeg")
```
\smallskip
\centering
Andrew Gelman
\column{.6\textwidth}
Gelman is a prolific statistician, political scientist and blogger at Columbia University.
\medskip
Developed MRP in a series of papers starting in 1997. Adapts and extends some techniques for *small area estimation* from survey statistics.
\medskip
Ideas (post-stratification, multilevel models, hierarchical Bayesian estimation) were well known, but the combination has been very effective in polling applications.
\columnsend
## . . . and his mysterious friend Stan?
\columnsbegin
\column{.3\textwidth}
```{r, out.width = "1.5in"}
knitr::include_graphics("images/ulam.jpeg")
```
\medskip
\centering
Stanislav Ulam (1909-1984)
\column{.4\textwidth}
Ulam was a physicist who invented the *Monte Carlo method* while working on the Manhattan Project.
\medskip
Stan is an open source software project developing *Markov chain Monte Carlo* (MCMC) software for statistical inference and other applications.
\column{.3\textwidth}
```{r, out.width = "1.5in"}
knitr::include_graphics("images/stan_logo.png")
```
\smallskip
\centering
<https://mc-stan.org>
\columnsend
## What problems does MRP address?
- **Selection bias.** Flexible and robust method for correcting for imbalances in sample composition, even when these are severe and can involve a large number of variables.
- **Small area estimation.** Can provide good estimates for sub-national units (such as states, Congressional districts, counties, *etc.*)
- **Trend analysis.** Estimate means of survey variables over time with a set of rolling cross-sections
## Selection bias: the Xbox panel
![](images/poll_screenshot.jpg)
* 750,148 interviews with 345,858 Xbox users during the 2012 election campaign
* However, the sample had some problems....
(Gelman, Goel, Rivers, and Rothschild, "The Mythical Swing Voter", *Quarterly Journal of Political Science,* 2016)
## Xbox panel demographics
\centering
![](images/demo_xbox_v_exit.pdf){height=75%}
\centering
93% were male, but there were still over 5,000 women in the sample.
## MRP estimates of 2012 voting from Xbox panel
\centering
![](images/subgroup_predictions.pdf){height=60%}
75,096 cells: 2 gender x 4 race x 4 age x 4 education x 4 party x 3 ideology x 50 states
## Lesson 1
\centering
\LARGE
Under some circumstances, **big data** (large sample sizes) and **modelling** can handle empty cells and correct for severe selection bias.
## Small area estimation: the 2017 UK general election
\centering
![](images/uk17_predictions.png)
## Comparison of MRP forecasts and outcomes
\centering
![](images/uk17_yg_est.png)
## Lesson 2
\centering
\LARGE
It's possible to get pretty good estimates of **small areas** (parliamentary constituencies, congressional districts, even precincts) with effective predictors and multilevel models.
## Why do polls bounce around so much?
\centering
![](images/us16_fig-lead-pid-wgt.pdf)
## Trend analysis: the 2016 US presidential election
\centering
![](images/us16_NationalTimeTrend.pdf)
## Lesson 3
\centering
\LARGE
Large swings in the 2012 and 2016 pre-election polls were methodological artifacts due to inadequate **post-stratification** and **modeling**.
## Ingredients for MRP and running example
**Survey** Pew Research Organization's *October 2016 Political Survey* (2,583 interviews, conducted October 20-25, 2016.)
**Survey variable** 2016 Presidential voting intention
**Covariates** Individual characteristics (from the survey) and group level predictors (2012 state vote)
**Post-strata** Age x Gender x Race x Education x State
**Stratum counts** from the November 2016 Voting and Registration Supplement to the *Current Population Survey*
## Data sources
The file `cleaned.RData` contains four R dataframes:
* `pew` - Pew Research Organization's **October 2016 Political Survey**. The original data can be found at <http://www.people-press.org/dataset/october-2016-political-survey/>.
* `cps` - the November 2016 Voting and Registration Supplement to the **Current Population Survey**. The full dataset can be downloaded from <www.nber.org/cps/>.
* `votes12` and `votes16` - votes cast for major presidential candidates, turnout, and voting age population by state. **Vote counts** are from <https://uselectionatlas.org/> and **population counts** are from <https://www2.census.gov/programs-surveys/cps/>.
Code `clean-data.R` for creating `cleaned.RData` is on the course Github site.
## How MRP works
**Step 1: multilevel regression** Fit a model relating the survey variable (vote) to individual and group level covariates (age, gender, race, education, state, 2012 vote).
**Step 2: imputation** Impute the survey variable (proportion voting Democratic) for all combinations of age x gender x race x education x state.
each cell of post-stratification (2 age x 2 gender x 3 race x 4 education x 51 state).
**Step 3: post-stratification** Average the imputed values in each cell and weight the estimated cell mean by the population count in each of the $2 \times 2 \times 3 \times 4 \times 51 = 2248$ cells.
## Some important concepts we will cover
* Fit **multilevel** regression models for survey variables which are "richly parameterized" and can flexibly adjust for high dimensional selection bias.
* Estimate models using **hierarchical Bayesian priors** to avoid over-fitting.
* Impute using the **posterior predictive distribution** (not the sample average).
* Use **multiple imputations** to accurately reflect the sources of uncertainty in the imputation process.
Don't worry if you don't understand the terminology -- details will follow -- but it's just **regression** and **imputation**.
# 2. Post-stratification
## Review of stratified sampling
In *stratified sampling*, we divide the population into **strata** (*e.g.*, regions) and draw samples within each stratum.
The **stratified estimator** is obtained by weighting the stratum estimates by the population size in each.
A stratified design can be more **efficient** than a simple random sample of the same size because
* Eliminates variability in the proportion of sample coming from each stratum
* Larger sample sizes could be allocated to more heterogeneous strata, less to homogeneous strata
## Notation for stratified sampling
**Population** $U = U_1 \cup \cdots \cup U_H$ partitioned into $H$ strata
**Sample** $S = S_1 \cup \cdots \cup S_H$ where $S_h \subset U_h$.
**Population sizes** $N = N_1 + \cdots + N_H$
**Sample sizes** $n = n_1 + \cdots + n_H$
**Sample means** $\bar y_1,\dots, \bar y_H$
**Stratified estimator** $\bar y_{\text{ST}} = \dfrac{N_1}{N} \bar y_1 + \cdots + \dfrac{N_H}{N} \bar y_H$
The stratified estimator is a **weighted** combination of the stratum means. The weights are **known** -- sampling variation comes from errors in estimating the stratum means.
## Stratification weights
An equivalent way of computing the stratified estimator is to define the **stratum weights**
$$
w_h = \dfrac{\text{population proportion in stratum}}{\text{sample proportion in stratum}}
= \dfrac{N_h/N}{n_h/n}
$$
Each respondent gets the weight associated with their stratum:
$$
\bar y_{\text{ST}} = \text{weighted average of sample values} = \dfrac{ w_{h_1} y_1 + \cdots + w_{h_n} y_n }{ w_{h_1} + \cdots + w_{h_n}}
$$
where $h_i$ and $w_{h_i}$ are the **stratum** and **weight**, respectively, associated with respondent $i$.
## Variance of the stratified estimator
$$
V(\bar y_{\text{ST}}) = \sum_{h=1}^H \left( \dfrac{N_h}{N} \right)^{\!2} \left( 1 - \dfrac{n_h}{N_h} \right) \dfrac{S_h^2}{n_h} = \dfrac{1}{n} \sum_{i=1}^n w_{h_i}^2 (1 - f_h) \dfrac{S_{h_i}^2}{n}
$$
There are three factors that determine the variance of the stratified estimator:
* Size of the **sampling fractions** $f_h = n_h / N_h$ in each stratum. Usually these are close to zero and can be ignored.
* The **within stratum variances** $\sum_{i \in U_h} (y_i - \bar y_h)^2 / (N_h - 1)$.
* Variability of the **stratum weights** $w_h$.
$S_h^2$ can be substantially less than the total variance of $y$, so there are potential large gains in efficiency from stratifying, compared to SRSWOR.
Variation in the weights tends to *increase* the standard error of the estimator, unless it's possible to allocate sample size $n_h$ proportional to $S_h^2$.
## Post-stratification
When the sample design is **not** stratified, it may still be feasible to use the stratified estimator if the sample can be divided into groups (called **post-strata**) whose population sizes are known.
The sample sizes in the post-strata are not fixed by design, so the variance formula only holds conditional upon the realized sample sizes $n_1,\dots,n_H$. (See Holt and Smith, "Post-stratification", *Journal of the Royal Statistical Society, Series A*, 1979.)
Even though the sample may have started with equal selection probabilities, the proportions in the post-strata often differ substantially from the population proportions. Failure to post-stratify results in large bias, but large weights may result in unstable estimates.
Usual advice is to collapse post-strata to have at least 20 respondents per cell.
## Post-stratification in R
**Step 1** Recode survey and population data (usually from a *public use microdata* file) so that the post-stratifying variables are consistent.
**Step 2** Choose the post-strata
**Step 3** Collapse categories to eliminate empty cells
**Step 4** Compute the post-stratification weights
**Step 5** Estimate means and proportions (with standard errors)
## Step 1: recode Pew data...
Variables should be `factor`s (R's version of categorical variables) with the same `levels` (categories) *in the same order*.
\scriptsize
```{r, echo=TRUE, warning=FALSE, message=FALSE}
suppressMessages(library("tidyverse"))
load("data/cleaned.RData")
pew <- pew %>%
filter(
complete.cases(age, raceeth, gender, educ, vote16),
vote16 != "nonvoter") %>%
mutate(
demvote = ifelse(vote16 == "clinton", 1, 0),
age4 = factor(case_when(age < 30 ~ "18-29",
age < 45 ~ "30-44", age < 65 ~ "45-64",
TRUE ~ "65+")),
race3 = fct_collapse(raceeth,
white = c("white", "other")),
educ4 = fct_collapse(educ,
"hs" = c("grades 1-8", "hs dropout", "hs grad"),
"some col" = c("some col", "assoc")))
```
## ...then do the same for CPS
\scriptsize
```{r, echo=TRUE, warning=FALSE, messages=FALSE}
cps <- cps %>%
filter(
complete.cases(age_top_codes,
raceeth, gender, educ, turnout),
turnout == "yes") %>%
mutate(
age4 = factor(case_when(
age_top_codes == "<80" & age < 30 ~ "18-29",
age_top_codes == "<80" & age < 45 ~ "30-44",
age_top_codes == "<80" & age < 65 ~ "45-64",
TRUE ~ "65+")),
race3 = fct_collapse(raceeth,
white = c("white", "other")),
educ4 = fct_collapse(educ,
"hs" = c("grades 1-8", "hs dropout", "hs grad"),
"some col" = c("some col", "assoc")))
```
## Check that the datasets are consistent -- mistakes will be made!
Time spent cleaning the data at this stage is time well spent.
\footnotesize
```{r, echo=TRUE, include=TRUE}
compare_distributions <- function(var, data1, data2, wgt1, wgt2, digits = 1) {
stopifnot(all(levels(data1[[var]]) == levels(data2[[var]])))
formula1 <- as.formula(paste(wgt1, "~", var))
formula2 <- as.formula(paste(wgt2, "~", var))
tbl <- rbind(round(100 * prop.table(xtabs(formula1, data1)), digits),
round(100 * prop.table(xtabs(formula2, data2)), digits))
row.names(tbl) <- c(substitute(data1), substitute(data2))
tbl
}
compare_distributions("race3", pew, cps, "", "weight")
```
## Compare variables in `pew` and `cps`
\scriptsize
```{r, echo=TRUE}
compare_distributions("educ4", pew, cps, "", "weight")
compare_distributions("age4", pew, cps, "", "weight")
compare_distributions("gender", pew, cps, "", "weight")
```
## Step 2: create post-strata
The `survey` package contains useful functions for post-stratification, including `postStratify`, `rake`, and `nonresponse`.
\footnotesize
```{r, echo=TRUE, message = FALSE, warning = FALSE}
suppressMessages(library(survey))
pop.counts <- xtabs(weight ~ age4 + gender + race3 + educ4, data = cps)
sample.counts <- xtabs(~ age4 + gender + race3 + educ4, data = pew)
pew <- mutate(pew,
weight0 = sum(pop.counts) / sum(sample.counts))
sample.weights <- xtabs(weight0 ~ age4 + gender + race3 +
educ4, data = pew)
nr <- nonresponse(sample.weights, sample.counts, pop.counts)
```
\normalsize
\centering
`nr` is an object which keeps track of the cells (post-strata).
## Check for empty cells and/or large weights
\tiny
```{r, echo=TRUE}
sparseCells(nr, nrweight = 4)
```
## Look for categories adjacent to empty cells
\scriptsize
```{r, echo = TRUE, include=TRUE}
neighbours(14, nr) # use nr$index to get cell index
```
## Step 3: collapse cells
Cells 10, 11, 14 and 15 contain blacks aged 30-64 with a high school education.
\scriptsize
```{r echo=TRUE}
nr$index[,,"black","hs"]
nr <- joinCells(nr, 10, 11, 14, 15) # update the nr object
nr$index[,,"black","hs"]
```
## Eliminate remaining empty cells
Combine males and females and collapse age and education categories for minorities. Each call to `joinCells` collapses some cells and stores the result in `nr`.
\scriptsize
```{r echo=TRUE, include=TRUE}
nr <- joinCells(nr, 18, 19, 21, 22) # hisp 30-64 hs
nr <- joinCells(nr, 44, 48, 68, 72, 92, 96) # hisp 65+ >hs
nr <- joinCells(nr, 57, 61, 81, 85) # black 18-29 col+
sparseCells(nr, nrweight = 4) # no more bad cells
```
\normalsize
`NULL` means that, after collapsing, there are no empty cells or weights > 4.
## Step 4: compute weights and add to dataframe
`weights(nr)` is a four dimensional (age x gender x race x education) array of **stratum weights**. I created `get_weights` to convert the stratum weights into a vector of **individual weights**.
\footnotesize
```{r echo=TRUE}
get_weights <- function(data, nr) {
wgt_arr <- weights(nr)
var.names <- names(dimnames(wgt_arr))
indexes <- data %>%
select(var.names) %>%
mutate_all(as.integer) %>%
as.matrix()
wgt_arr[indexes]
}
pew$ps.weight <- get_weights(pew, nr)
```
## Check that the post-stratification worked
\scriptsize
```{r, echo=TRUE}
compare_distributions("race3", pew, cps, "ps.weight", "weight")
compare_distributions("educ4", pew, cps, "ps.weight", "weight")
compare_distributions("age4", pew, cps, "ps.weight", "weight")
```
## Step 5: compute estimates using the new weight
Use either `xtabs` (in base R) or the `survey` package
\scriptsize
```{r, echo=TRUE, include=TRUE, warning=FALSE, message=FALSE}
round(100 * prop.table(xtabs(ps.weight ~ vote16, pew)), 1)
design <- svydesign(ids = ~ 1, weights = ~ ps.weight, data = pew)
round(100 * prop.table(svytable(~ vote16, design)), 1)
cv <- function(x) sd(x) / mean(x) # coefficient of variation
cv(pew$ps.weight)^2 # weighting loss
```
## State estimates
\footnotesize
```{r echo=TRUE}
tbl <- 100 * prop.table(xtabs(ps.weight ~ state + vote16, data = pew), 1)
round(tbl, 1)[1:10,]
```
## Plotting the estimates
State estimates are nearly useless, even if approximately unbiased.
\scriptsize
```{r echo=FALSE, warning=FALSE, fig.width=9, fig.height=4.5, fig.align="center"}
estimates <- votes16 %>%
transmute(state, name,
actual = 100 * clinton / turnout) %>%
mutate(post.stratified = tbl[,"clinton"])
suppressMessages(library(ggplot2))
p1 <- ggplot(estimates, aes(actual, post.stratified)) +
geom_abline(slope = 1, intercept = 0, col = "grey") +
geom_point() +
lims(x = c(0, 100), y = c(0, 100)) +
labs(x = "Percent of votes", y = "Post-stratifed estimate") +
theme_minimal()
p2 <- ggplot(estimates, aes(post.stratified - actual)) +
geom_histogram(binwidth = 10, center = 0, fill = "gray") +
labs(x = "Error in estimate") +
theme_minimal()
suppressMessages(library(gridExtra))
grid.arrange(p1, p2, nrow = 1)
```
## Mapping the estimates
*Probably not something you'd want to share with the world.*
```{r, echo=FALSE, include=TRUE, message=FALSE, warning=FALSE}
suppressMessages(library(maps))
suppressMessages(library(mapproj))
us_map <- map_data("state")
estimates %>%
mutate(state_name = tolower(name),
clinton_pct = cut(post.stratified, breaks = c(-Inf, 40, 45, 50, 55, 60, 100),
labels = c("<40", "40-45", "45-50", "50-55", "55-60", ">60"))) %>%
ggplot(aes(map_id = state_name)) +
geom_map(aes(fill = clinton_pct), map = us_map) +
expand_limits(x = us_map$long, y = us_map$lat) +
coord_map("albers", lat0 = 39, lat1 = 45) +
scale_fill_brewer(name = "Clinton %", type = "div", palette = "RdBu") +
theme(axis.line = element_blank()) +
theme_void()
```
## Problems with post-stratification
**Empty cells**
* Collapsing cells increases bias
* Alternative is _raking_ (works if no empty cells in marginals)
\smallskip
**Small cells**
* Even with non-empty cells, mean estimates will be noisy if the cell size is small.
* Recommended cell size is at least 20 -- suggest collapsing cells
\smallskip
**Large weights**
* Common practice is to *trim* large weights.
* Solves the wrong problem: population cell count is ok, sample cell estimate is noisy.
# 3. Multilevel regression
## Key ideas
* Use a regression model to **predict** values of the survey variable for each combination of covariates.
* Use a **richly parameterized model** for the data (the first level)
+ Allow intercepts and possibly slopes to vary across groups in the data ("deep interactions").
+ Use variables with many categories (such as counties or states), some of which may not be present in the data.
* Introduce a second level model for the **parameters** in the first level.
+ The parameters of the second level model are sometimes called *hyperparameters*.
+ The second level model is used to avoid overfitting. Results in *shrinkage* or *regularization*.
* Also known as hierarchical models, mixed models, random effects, variance components, repeated measures, longitudinal analysis, *etc.*
## Stein's paradox
\columnsbegin
\column{.3\textwidth}
```{r, out.width = "1.5in"}
knitr::include_graphics("images/stein.jpg")
```
\smallskip
\centering
Charles Stein (1920-2016)
\column{.5\textwidth}
The **mean square error** (or **risk**) of an estimator $\hat\theta$ of $\theta$ is
$$
\text{MSE}(\hat\theta, \theta) = E_\theta(\hat\theta - \theta)^2
$$
An estimator $\hat\theta$ is **inadmissable** if there exists another estimator $\tilde\theta$ with smaller risk for *all* $\theta$. The estimator $\tilde\theta$ is said to **dominate** $\hat\theta$.
\medskip
When estimating three or more means of independent normal distributions, Stein showed that the sample mean is **inadmissable**.
\columnsend
## A tale of three estimators
To keep things simple, we start with models for vote by state without any covariates.
**No pooling** estimate the model separately for each state (by a regression on 51 state dummies)
**Complete pooling** estimate a single **grand mean** (equivalent to a regression with just an intercept)
**Partial pooling** estimate a *random effects* model (to be explained shortly -- think of it as a compromise between no pooling and complete pooling)
\bigskip
\small
(For pedagogical purposes, we will use *linear* instead of *logistic regression* in this section. The same concepts apply to nonlinear model.)
## Fixed effects (no pooling)
We use `lm` to estimate a model with state dummies and no intercept (so the estimates are the predicted Clinton vote in each state).
\scriptsize
```{r, echo=TRUE}
no.pooling <- lm(demvote ~ state - 1, data = pew)
no.pooling <- data_frame(
state = gsub("state", "", names(coef(no.pooling))),
no.pooling = 100 * coef(no.pooling)) %>%
mutate(state = factor(state, levels = levels(pew$state)))
head(no.pooling)
```
## Grand mean (complete pooling)
The grand mean can be computed in **three equivalent ways**:
\scriptsize
```{r, echo=TRUE}
round(100 * mean(pew$demvote), 1) # 1. mean of dichotomous indicator
round(100 * prop.table(xtabs(~ demvote, data = pew)), 1) # 2. cross-tabulation
complete.pooling <- lm(demvote ~ 1, data = pew) # 3. intercept in regression
complete.pooling <- 100 * coef(complete.pooling)
round(complete.pooling, 1)
```
## Random effects (partial pooling)
Estimate a model with one **fixed effect** (the grand mean) plus **random effects** for each state,
$$
\text{vote} = \text{grand mean} + \text{state effect} + \text{individual error}
$$
or, in symbols,
$$
y_i = \mu + \alpha_{j_i} + \epsilon_i \qquad (j_i = \text{state of respondent})
$$
where
$$
\alpha_1,\dots,\alpha_J \stackrel{\text{iid}}{\sim} \text{Normal}(0, \sigma_\alpha) \qquad
\epsilon_1,\dots,\epsilon_n \stackrel{\text{iid}}{\sim} \text{Normal}(0, \sigma_\epsilon)
$$
The grand mean $\mu_i$ is a **fixed effect** while the state effects $\alpha_j$ are **random effects** (assumed to be $\text{Normal}(0, \sigma_\alpha)$).
In classical statistics, parameters (like $\mu$, $\sigma_\epsilon$ and $\sigma_\alpha$) are **estimated** while random effects are **predicted**.
## What's the difference between fixed and random effects models?
In both models,
$$
y_i = \mu + \alpha_{j_i} + \epsilon_i
$$
with the only difference being
* **Fixed effects** $\alpha_1,\dots,\alpha_J$ are *unknown* parameters to be estimated.
+ $E(y_i) = \mu + \alpha_{j_i}$ and $V(y_i) = \sigma_\epsilon^2$
* **Random effects** $\alpha_1,\dots,\alpha_J$ are *unknown* random variables to be predicted.
+ $E(y_i) = \mu$ and $V(y_i) = \sigma_\alpha^2 + \sigma_\epsilon^2$
+ But $E(y_i | \alpha_{j_i}) = \mu + \alpha_{j_i}$ and $V(y_i | \alpha_{j_i}) = \sigma_\epsilon^2$
If you find this confusing, you are not alone. Gelman and Hill argue that the only meaningful difference is that the $\alpha_j$ are modelled in one and not in the other.
## Predicting random effects
The default method for R's `lmer` function (in the `lme4` package) is *REML* (residualized or restricted maximum likelihood), which is unbiased for linear models.
\scriptsize
```{r, echo=TRUE}
suppressMessages(library(lme4))
partial.pooling <- lmer(demvote ~ 1 + (1 | state), data = pew)
partial.pooling
```
## Extracting predictions
\scriptsize
```{r, echo=TRUE}
fixef(partial.pooling) # grand mean
ranef(partial.pooling)$state %>% head(4) # state effects
coef(partial.pooling)$state %>% head(4) # state predictions
```
## Which is better?
\scriptsize
```{r echo=FALSE}
partial.pooling <- coef(partial.pooling)$state %>%
as_data_frame(rownames = "state") %>%
transmute(state = factor(state, levels = levels(pew$state)),
partial.pooling = 100 * `(Intercept)`)
estimates <- estimates %>%
left_join(no.pooling, by = "state") %>%
left_join(partial.pooling, by = "state") %>%
mutate(n = as.integer(xtabs(~ state, data = pew)))
estimates
```
```{r echo=FALSE, include=FALSE}
rmse <- function(est, act) sqrt(mean((est - act)^2, na.rm = TRUE))
RMSE <- estimates %>%
summarize(complete.pooling = rmse(complete.pooling, actual),
no.pooling = rmse(no.pooling, actual),
partial.pooling = rmse(partial.pooling, actual)) %>%
unlist()
RMSE
```
\normalsize
The RMSE is about the same for *no pooling* (`r round(RMSE["no.pooling"], 1)`%) and *complete pooling* (`r round(RMSE[
"complete.pooling"], 1)`%), but substantially smaller for *partial pooling* (`r round(RMSE["partial.pooling"], 1)`%).
## 2016 U.S. election: estimates *vs.* actuals
```{r echo=FALSE, message=FALSE, warning=FALSE, fig.height=4.5, fig.width=9, fig.align="center"}
p1 <- ggplot(estimates, aes(actual, no.pooling)) +
geom_point() +
labs(title = "No pooling", x = "Percent of voters",
y = "Percent of voters") +
lims(x = c(0,100), y = c(0,100)) +
theme_minimal()
p2 <- ggplot(estimates, aes(actual, partial.pooling)) +
geom_point() +
labs(title = "Partial pooling", x = "Percent of voters",
y = "Percent of voters") +
lims(x = c(0,100), y = c(0,100)) +
theme_minimal()
suppressMessages(library(gridExtra))
grid.arrange(p1, p2, nrow = 1)
```
## Shrinkage
```{r echo=FALSE, fig.align="center"}
na.omit(estimates) %>%
select(-post.stratified) %>%
rename("Actual" = actual, "No pooling" = no.pooling,
"Partial pooling" = partial.pooling) %>%
gather(Estimator, Percentage, -state, -name, -n) %>%
mutate(Estimator = factor(Estimator, levels = c("Post-stratified",
"No pooling", "Partial pooling", "Actual"))) %>%
ggplot(aes(Estimator, Percentage, group = state, color = n)) +
geom_line(size = 0.7) +
scale_color_gradientn(colors = blues9[-1]) +
lims(y = c(0, 100)) +
theme_minimal()
```
## What *exactly* is a random effects estimator?
The random effects/partial pooling estimate of a group mean is a weighted average of the fixed effects/no pooling estimate and the grand mean/complete pooling estimate.
$$
\hat\theta_j^{\text{RE}} = w_j \, \bar y_j + (1 - w_j) \, \bar y
$$
* The weight on the no pooling estimator $\bar y_j$ is proportional to sample size $n_j$ in group $j$ and inversely proportional to the **within group variance**.
* The weight on the complete pooling is inversely proportional to the **between group variance**.
* Sometimes referred to as an **empirical Bayesian estimator**. The amount of shrinkage is data dependent.
## Adding individual covariates: fixed effects
To get better predictions, let's add a covariate -- **gender** -- to the model. There are now three *fixed effects* estimators:
**Complete pooling** estimate a single slope and single intercept for all states
**No pooling** estimate separate intercepts and slopes for each state
**Complete pooling of slopes, no pooling of intercepts** estimate separate intercepts for each state and a common slope
*(It rarely makes sense to estimate separate slopes and a common intercept, so we ignore this possibility.)*
## Complete pooling: common intercepts and slopes
$$
y_i = \alpha + \beta x_i + \epsilon_i \qquad \epsilon_i \stackrel{\text{iid}}{\sim} \text{Normal}(0, \sigma_\epsilon)
$$
\scriptsize
```{r, echo=TRUE}
pew <- mutate(pew, female = ifelse(gender == "female", 1, 0))
fit1 <- lm(demvote ~ 1 + female, data = pew)
arm::display(fit1)
```
\normalsize
$\hat\beta = 0.14$ implies a 14% gender gap (42% of men voted for Clinton *vs.* 56% of women).
## No pooling: separate intercepts and slopes
$$
y_i = \alpha_{j_i} + \beta_{j_i} x_i + \epsilon_i
$$
\tiny
```{r, echo=TRUE}
fit2 <- lm(demvote ~ 0 + state + state:female, data = pew)
coef.fit2 <- as.matrix(coef(fit2))
round(coef(fit2)[c(1:5, 90:98)], 2)
```
\normalsize
It's impossible to estimate the slope in Wyoming:
\tiny
```{r, echo=FALSE}
options(width = 100)
xtabs(~ gender + state, data = pew) # no men in WY
options(width = 85)
```
```{r echo=FALSE, include=FALSE}
coef.fit2 <- coef(fit2)
coef.fit2 <- as.matrix(data.frame(intercept = coef.fit2[1:48],
slope = coef.fit2[50:97], row.names =
gsub("state", "", names(coef.fit2)[1:48])))
```
## Separate intercepts with common slope
$$
y_i = \alpha_{j_i} + \beta x_i + \epsilon_i
$$
\scriptsize
```{r echo=TRUE}
fit3 <- lm(demvote ~ state + female - 1, data = pew)
coef.fit3 <- coef(fit3)
names(coef.fit3) <- gsub("state", "", names(coef.fit3))
round(coef.fit3, 2)
```
## Which should you believe?
```{r, echo=FALSE, fig.align="center"}
par(mfrow=c(1,2))
plot.gender.by.state <- function(main, coefs, fixef) {
n <- nrow(coefs)
x <- rep(c(0,1), rep(n, 2))
y <- 100 * c(coefs[[1]], coefs[[1]] + coefs[[2]])
plot(x = x, y = y, pch = 19, cex = 0.5, xlim = c(0, 1),
ylim = c(0, 100), main = main,xlab = "Gender",
ylab = "Percent voting for Clinton", axes = FALSE)
axis(1, at = c(0, 1), labels = c("Male", "Female"))
axis(2, at = seq(0, 100, 20))
for (i in seq_len(n)) lines(x = c(0, 1),
y = c(y[i], y[i+n]), col = "grey", lwd = 0.5)
abline(100 * fixef, col = "red3", lwd = 2)
}
plot.gender.by.state("No pooling", as_data_frame(coef.fit2)[-49,],
coef(fit1))
coef.fit3.df <- data_frame(Intercept = coef.fit3[-length(coef.fit3)],
Slope = coef.fit3[length(coef.fit3)])
plot.gender.by.state("Common slope", coef.fit3.df, coef(fit1))
par(mfrow=c(1,1))
```
## Gender gaps in 2016 Exit poll
\centering
![](images/gender-gap-xp.pdf)
## Multilevel models with a single covariate
**Varying intercepts, common slope**
$$
y_i = \mu + \alpha_{j_i} + \beta x_i + \epsilon_i
$$
* The intercept for state $j$ is $\mu + \alpha_j$.
* The slope (gender gap) is $\beta$ (same for all states).
**Varying intercepts and slopes**
$$
y_i = \mu + \alpha_{j_i} + \beta x_i + \gamma_{j_i} x_i + \epsilon_i
$$
* The intercept for state $j$ is $\mu + \alpha_j$.
* The slope (gender gap) for state $j$ is $\beta + \gamma_j$ (varies).
## Random effects: varying intercepts, common slopes
\scriptsize
```{r echo=TRUE}
# Varying intercept and common slope
fit4 <- lmer(demvote ~ 1 + female + (1 | state), data = pew)
fit4
```
## Random effects: varying intercepts and slopes (first try)
\tiny
```{r, echo=TRUE}
(fit5 <- lmer(demvote ~ 1 + female + (1 + female | state),
data = pew)) # fails to converge
```
## Fixing the convergence failure (by centering covariates)