-
Notifications
You must be signed in to change notification settings - Fork 3
/
ate_replication.Rmd
282 lines (214 loc) · 9.25 KB
/
ate_replication.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
---
title: "AEA Annual Meeting 2018 Tutorial Replication"
author: "Shota Yasui"
date: "04/23/2018"
output: github_document
---
```{r setup, include=FALSE, message=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## About this document
This document is the replication of [this R tutorial](https://drive.google.com/open?id=1JS223q7LKHciEnysrBGzfD6uWk5_xlgz) in Machine Learning and Econometrics tutorial in AEA Annual Meeting 2018.
In addition to the original implementation, I added standard error to the result.
## read some packages and some functions
```{r library, warning = FALSE, message = FALSE}
library(tidyverse)
library(glmnet)
library(randomForest)
library(balanceHD)
library(grf)
source("ate_functions.R")
```
## Read data
You can download the data from [here](https://github.com/gsbDBI/ExperimentData/blob/master/Social/ProcessedData/socialpresswgeooneperhh_NEIGH.csv), which is publicly available on [this repository](https://github.com/gsbDBI/ExperimentData/tree/master/Social).
```{r read_data}
data_raw <- read.csv("socialpresswgeooneperhh_NEIGH.csv")
```
## Prepare Dataset
This part is just copied from the original document.
The order of code is slightly differenct.
### Set seed and number of observation
```{r set_seed}
set.seed(1991)
n_obs <- 50000
```
### These are the covariates we'll use
```{r covariate_select}
cts_variables_names <- c("yob", "city", "hh_size", "totalpopulation_estimate",
"percent_male", "median_age",
"percent_62yearsandover",
"percent_white", "percent_black",
"percent_asian", "median_income",
"employ_20to64", "highschool", "bach_orhigher",
"percent_hispanicorlatino")
binary_variables_names <- c("sex","g2000", "g2002", "p2000", "p2002", "p2004")
covariates <- c(cts_variables_names, binary_variables_names)
all_variables_names <- c(covariates, "outcome_voted", "treat_neighbors")
```
### Scaling
```{r scaling}
# Selecting only desired covariates
data_subset <- data_raw %>%
sample_n(size = n_obs) %>%
dplyr::select(all_variables_names)
# Extracting and scaling continuous variables
scaled_cts_covariates <- data_subset %>%
dplyr::select(cts_variables_names) %>%
scale()
# Extracting indicator variables
binary_covariates <- data_subset %>%
dplyr::select(binary_variables_names)
# Extracting outcome and treatment
outcome <- data_subset %>% dplyr::select(outcome_voted)
treatment <- data_subset %>% dplyr::select(treat_neighbors)
```
### Setting up the data, renaming columns and discarding rows with NA (if any)
```{r data_setup}
df <- data.frame(scaled_cts_covariates, binary_covariates, outcome, treatment) %>%
plyr::rename(c(treat_neighbors = "W",
outcome_voted = "Y")) %>%
na.omit()
```
### Introduce sampling bias
```{r intro_sampling_bias}
#introduce sampling bias
pt <- .85 # Drop p% of voters who satisfy the following condition
pc <- .85
# These individuals are likely TO GO voting: drop from TREATMENT
drop_from_treat <- (df[,"g2000"]==1 | df[,"g2002"]==1) |
(df[,"p2000"]==1 | df[,"p2002"]==1 | df[,"p2002"] == 1) |
(df[,"city"] > 2) | (df[,"yob"] > 2)
# These individuals are likely NOT TO GO voting: drop from CONTROL
drop_from_control <-(df[,"g2000"]==0 | df[,"g2002"] == 0) |
(df[,"p2000"]==0 | df[,"p2002"]==0 | df[,"p2004"]==0) |
(df[,"city"] < -2 | df[,"yob"] < -2)
drop_treat_idx <- which(df[,"W"] == 1 & drop_from_treat)
drop_control_idx <- which(df[,"W"] == 0 & drop_from_control)
drop_idx <- unique(c(drop_treat_idx[1:round(pt*length(drop_treat_idx))],
drop_control_idx[1:round(pc*length(drop_control_idx))]))
print(length(drop_idx))
df_mod <- df[-drop_idx,]
```
As we see people who voted before were droppoed from treatment group and people who did not vote before were dropped, the scinario of this sampling bias is the treatment was assigned to people less likely to vote.
## RCT result as oracle
```{r rct_result}
result_df <- data.frame()
ate_oracle <- naive_ate(dataset = df, treatment_var = "W", outcome_var = "Y", method = "oracle")
result_df <- result_df %>% rbind(ate_oracle)
```
The result of RCT is the best result what we are able to obtain from this dataset.
Therefore, the main interest of this document is what method can produce the closest result with RCT in this dataset.
## Naive Method
```{r naive_result}
naive_ate <- naive_ate(dataset = df_mod, treatment_var = "W", outcome_var = "Y")
result_df <- result_df %>% rbind(naive_ate)
```
This is the easiest way to estimate the effect of W. This result is correct if the W is randomly assigned. However, the current data set is not in such case.
## RCT vs Naive
```{r rct_naive_plot}
ggplot(result_df, aes(y = ATE, x = Method, color = Method)) +
geom_pointrange(aes(ymax = upper_ci, ymin = lower_ci)) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
```
The result of Naive is far away from the result of RCT. This gap is made by sampling bias.
Since W is assigned to people who less likely to go to vote, so that the effect of W offset such sampling bias effect. As a result we observed zero effect by Naive approach.
## OLS
```{r lm_result}
tauhat_lm <- ate_condmean_ols(df_mod, treatment_var = "W", outcome_var = "Y")
result_df <- result_df %>% rbind(tauhat_lm)
```
Now we try to control some covariate which may produce the sampling bias.
## Propensity Score
### Weighting
```{r psw_result}
# Computing the propensity score by logistic regression of W on X.
p_logistic <- df_mod %>%
dplyr::select(covariates, W) %>%
glm(W ~ ., data = ., family = binomial(link = "logit")) %>%
predict(type= "response")
tauhat_psw <- prop_score_weight(dataset = df_mod, p = p_logistic, treatment_var = "W", outcome_var = "Y")
result_df <- result_df %>% rbind(tauhat_psw)
```
### Regression
```{r psols_result}
tauhat_psols <- prop_score_ols(dataset = df_mod, p = p_logistic, treatment_var = "W", outcome_var = "Y")
result_df <- result_df %>% rbind(tauhat_psols)
```
### Propensity Score by LASSO then weighting
```{r psw_lasso}
p_lasso <- prop_score_lasso(df_mod, treatment_var = "W")
tauhat_ps_lasso <- prop_score_weight(dataset = df_mod,
p = p_lasso[,1],
treatment_var = "W",
outcome_var = "Y",
method = "Propensity_Weighting_LASSOPS")
result_df <- result_df %>% rbind(tauhat_ps_lasso)
```
## LASSO application
### Single equation LASSO
```{r seq_lasso}
tauhat_lasso_seq <- ate_condmean_lasso(df_mod, treatment_var = "W", outcome_var = "Y")
result_df <- result_df %>% rbind(tauhat_lasso_seq)
```
### Usual LASSO
```{r usual_LASSO}
tauhat_lasso_all <- ate_lasso(df_mod, treatment_var = "W", outcome_var = "Y")
result_df <- result_df %>% rbind(tauhat_lasso_all)
```
## Compare Regression Extentions
```{r compare_regression}
ggplot(result_df, aes(y = ATE, x = Method, color = Method)) +
geom_pointrange(aes(ymax = upper_ci, ymin = lower_ci)) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
```
## Doubly Robust
```{r doubly_robust}
tauhat_doubly <- doubly_robust(df_mod, treatment_var = "W", outcome_var = "Y", 2500)
tauhat_doubly_glm <- doubly_robust_glm(df_mod, treatment_var = "W", outcome_var = "Y")
result_df <- result_df %>% rbind(tauhat_doubly, tauhat_doubly_glm)
```
## Belloni et.al(2013)
```{r belloni_2013}
tauhat_belloni <- belloni(df_mod, treatment_var = "W", outcome_var = "Y")
result_df <- result_df %>% rbind(tauhat_belloni)
```
## Doubly Machine Learning
```{r double_machine_learning}
tauhat_double_ml <- double_ml(df_mod, treatment_var = "W", outcome_var = "Y", num_tree = 2000)
result_df <- result_df %>% rbind(tauhat_double_ml)
```
## Approximate Residual Balancing
```{r residual_balancing}
tauhat_balancdHD <- residual_balance_ATE(dataset,
treatment_var = "W",
outcome_var = "Y",
optimizer = "pogs")
result_df <- result_df %>% rbind(tauhat_balancdHD)
```
## causal forest
```{r causal_forest}
forest <- grf::causal_forest(X=as.matrix(df_mod[,covariates]),
Y=as.matrix(df_mod[,"Y"]),
W=as.matrix(df_mod[,"W"]),
num.trees = 2000,
honesty=TRUE,
seed=12345)
# Incorrect way to derive ATE and its standard errors
pred <- predict(forest, estimate.variance = TRUE)
ate_bad <- mean(pred$predictions)
se_bad <- sqrt(mean(pred$variance.estimates))
cat(sprintf("Incorrect ATE: %1.3f (SE: %1.3f)", ate_bad, se_bad))
# Doubly-robust ATE
ate_cf_robust <- grf::estimate_average_effect(forest)
tauhat_cf <- data.frame(Method = "Causal Forest(GRF)",
ATE = ate_cf_robust["estimate"],
lower_ci = ate_cf_robust["estimate"] - (ate_cf_robust["std.err"]*1.96),
upper_ci = ate_cf_robust["estimate"] + (ate_cf_robust["std.err"]*1.96))
result_df <- result_df %>% rbind(tauhat_cf)
```
## Compare CausalML Methods
```{r compare_CausalML}
ggplot(result_df, aes(y = ATE, x = Method, color = Method)) +
geom_pointrange(aes(ymax = upper_ci, ymin = lower_ci)) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
```