generated from jtr13/bookdown-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
26-DML-for-ATE-and-Late.Rmd
2099 lines (1521 loc) · 57.6 KB
/
26-DML-for-ATE-and-Late.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
# Inference on Predictive and Causal Effects in High-Dimensional Nonlinear Models
## Impact of 401(k) on Financial Wealth
As a practical illustration of the methods developed in this lecture, we consider estimation of the effect of 401(k) eligibility and participation
One can argue that eligibility for enrolling in a 401(k) plan in this data can be taken as exogenous after conditioning on a few observables of which the most important for their argument is income. The basic idea is that, at least around the time 401(k)’s initially became available, people were unlikely to be basing their employment decisions on whether an employer offered a 401(k) but would instead focus on income and other aspects of the job.
<style>
.col2 {
columns: 2 200px; /* number of columns and width in pixels*/
-webkit-columns: 2 200px; /* chrome, safari */
-moz-columns: 2 200px; /* firefox */
}
.col3 {
columns: 3 100px;
-webkit-columns: 3 100px;
-moz-columns: 3 100px;
}
</style>
### Data
The data set can be loaded from the `hdm` package for R and hdmpy for Python by typing
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE }
library(hdm)
library(ggplot2)
data(pension)
data <- pension
dim(data)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
import numpy as np
import pandas as pd
from doubleml.datasets import fetch_401K
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
import seaborn as sns
import hdmpy
import pyreadr
import urllib.request
import os
import warnings
warnings.filterwarnings("ignore")
rdata_read = pyreadr.read_r("./data/pension.Rdata")
# Extracting the data frame from rdata_read
data = rdata_read[ 'pension' ]
pension = data.copy()
data.shape
```
:::
::::::
\newline
See the "Details" section on the description of the data set, which can be accessed by
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
help(pension)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
os.system("start \"\" https://search.r-project.org/CRAN/refmans/hdm/html/pension.html")
```
:::
::::::
\newline
The data consist of 9,915 observations at the household level drawn from the 1991 Survey of Income and Program Participation (SIPP). All the variables are referred to 1990. We use net financial assets (*net\_tfa*) as the outcome variable, $Y$, in our analysis. The net financial assets are computed as the sum of IRA balances, 401(k) balances, checking accounts, saving bonds, other interest-earning accounts, other interest-earning assets, stocks, and mutual funds less non mortgage debts.
Among the $9915$ individuals, $3682$ are eligible to participate in the program. The variable *e401* indicates eligibility and *p401* indicates participation, respectively.
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
hist_e401 = ggplot(data, aes(x = e401, fill = factor(e401))) +
geom_bar()
hist_e401
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
sns.set()
colors = sns.color_palette()
sns.countplot(x="e401", hue = "e401" , data=data)
```
:::
::::::
\newline
Eligibility is highly associated with financial wealth:
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}" }
```{r message=FALSE, warning=FALSE, fig.height=5, fig.width=15}
dens_net_tfa = ggplot(data, aes(x = net_tfa, color = factor(e401), fill = factor(e401)) ) +
geom_density() + xlim(c(-20000, 150000)) +
facet_wrap(.~e401)
dens_net_tfa
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python fig.height=5, fig.width=15}
from matplotlib.pyplot import figure
figure(figsize=(8, 10), dpi=100)
sns.displot(data, x="net_tfa", hue="e401", col="e401",
kind="kde", fill=True)
```
:::
::::::
\newline
The unconditional APE of e401 is about $19559$:
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
e1 <- data[data$e401==1,]
e0 <- data[data$e401==0,]
round(mean(e1$net_tfa)-mean(e0$net_tfa),0)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
int(np.round( data[['e401', 'net_tfa']].groupby('e401').mean().diff().iloc[1, 0] ) )
```
:::
::::::
\newline
Among the $3682$ individuals that are eligible, $2594$ decided to participate in the program. The unconditional APE of p401 is about $27372$:
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
p1 <- data[data$p401==1,]
p0 <- data[data$p401==0,]
round(mean(p1$net_tfa)-mean(p0$net_tfa),0)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
int(np.round( data[['p401', 'net_tfa']].groupby('p401').mean().diff().iloc[1, 0]))
```
:::
::::::
\newline
As discussed, these estimates are biased since they do not account for saver heterogeneity and endogeneity of participation.
## Double ML package
We are interested in valid estimators of the average treatment effect of `e401` and `p401` on `net_tfa`. To get those estimators, we use the `DoubleML` package that internally builds on mlr3. You find additional information on the package on the package website https://docs.doubleml.org/ and the R documentation page https://docs.doubleml.org/r/stable/.
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# installing Double ML
#remotes::install_github("DoubleML/doubleml-for-r",quiet=TRUE)
# loading the packages
library(DoubleML)
library(mlr3learners)
library(mlr3)
library(data.table)
library(randomForest)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
import doubleml as dml
from sklearn.linear_model import LassoCV, LogisticRegressionCV
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from xgboost import XGBClassifier, XGBRegressor
```
:::
::::::
\newline
As mentioned, in the tutorial we use the meta package `mlr3` to generate predictions with machine learning methods. A comprehensive introduction and description of the `mlr3` package is provided in the [mlr3book](https://mlr3book.mlr-org.com/). A list of all learners that you can use in `mlr3` can be found [here](https://mlr3extralearners.mlr-org.com/articles/learners/list_learners.html). The entry in the columns *mlr3 Package* and *Packages* indicate which packages must be installed/loaded in your R session.
## Estimating the ATE of 401(k) Eligibility on Net Financial Assets
We first look at the treatment effect of e401 on net total financial assets. We give estimates of the ATE and ATT that corresponds to the linear model
\begin{equation*}
Y = D \alpha + f(X)'\beta+ \epsilon,
\end{equation*}
where $f(X)$ includes indicators of marital status, two-earner status, defined benefit pension status, IRA participation status, and home ownership status, and orthogonal polynomials of degrees 2, 4, 6 and 8 in family size, education, age and income, respectively. The dimensions of $f(X)$ is 25.
In the first step, we report estimates of the average treatment effect (ATE) of 401(k) eligibility on net financial assets both in the partially linear regression (PLR) model and in the interactive regression model (IRM) allowing for heterogeneous treatment effects.
I decided to low down the degree of the income variable from **8** to **6** since sklearn has some problems with values greater than `float32`. I can not use `np.log` in `inc` variable since it has negative values. As a result, we got a column with some `None` values. For more information about this problem, check this [link](https://github.com/scikit-learn/scikit-learn/issues/15628).
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# Constructing the data (as DoubleMLData)
formula_flex = "net_tfa ~ e401 + poly(age, 6, raw=TRUE) + poly(inc, 6, raw=TRUE) + poly(educ, 4, raw=TRUE) + poly(fsize, 2, raw=TRUE) + marr + twoearn + db + pira + hown"
model_flex = as.data.table(model.frame(formula_flex, pension))
x_cols = colnames(model_flex)[-c(1,2)]
data_ml_aux = DoubleMLData$new(model_flex,
y_col = "net_tfa",
d_cols = "e401",
x_cols=x_cols)
p <- dim(model_flex)[2]-2
p
# complex model with two-way interactions
#data_interactions = fetch_401k(polynomial_features = TRUE, instrument = FALSE)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
# Constructing the data (as DoubleMLData)
features = data.copy()[['marr', 'twoearn', 'db', 'pira', 'hown']]
poly_dict = {'age': 6,
'inc': 6,
'educ': 4,
'fsize': 2}
for key, degree in poly_dict.items():
poly = PolynomialFeatures(degree, include_bias=False)
data_transf = poly.fit_transform(data[[key]])
x_cols = poly.get_feature_names([key])
data_transf = pd.DataFrame(data_transf, columns=x_cols)
features = pd.concat((features, data_transf),
axis=1, sort=False)
model_flex = pd.concat((data.copy()[['net_tfa', 'e401']], features.copy()),
axis=1, sort=False)
x_cols = model_flex.columns.to_list()[2:]
# Initialize DoubleMLData (data-backend of DoubleML)
data_ml_aux = dml.DoubleMLData(model_flex, y_col='net_tfa', \
d_cols ='e401' , x_cols = x_cols)
# complex model with two-way interactions
# data_interactions
# fetch_401K( return_type = 'DataFrame' , polynomial_features = True )
p = model_flex.shape[1] - 2
print(p)
p = model_flex.shape[1] - 2
print(p)
```
:::
::::::
\newline
## Partially Linear Regression Models (PLR)
We start using lasso to estimate the function $g_0$ and $m_0$ in the following PLR model:
\begin{eqnarray}
& Y = D\theta_0 + g_0(X) + \zeta, & E[\zeta \mid D,X]= 0,\\
& D = m_0(X) + V, & E[V \mid X] = 0.
\end{eqnarray}
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# Estimating the PLR
lgr::get_logger("mlr3")$set_threshold("warn")
set.seed(123)
lasso <- lrn("regr.cv_glmnet",nfolds = 5, s = "lambda.min")
lasso_class <- lrn("classif.cv_glmnet", nfolds = 5, s = "lambda.min")
dml_plr <- DoubleMLPLR$new(data_ml_aux, ml_g = lasso, ml_m = lasso_class, n_folds=3)
dml_plr$fit(store_predictions=TRUE)
dml_plr$summary()
lasso_plr <- dml_plr$coef
lasso_std_plr <- dml_plr$se
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
# Estimating the PLR
# Initialize learners
Cs = 0.0001*np.logspace(0, 4, 10)
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, max_iter=10000))
lasso_class = make_pipeline(StandardScaler(),
LogisticRegressionCV(cv=5, penalty='l1', solver='liblinear',
Cs = Cs, max_iter=1000))
np.random.seed(123)
# Initialize DoubleMLPLR model
dml_plr = dml.DoubleMLPLR(data_ml_aux,
ml_g = lasso,
ml_m = lasso_class,
n_folds = 3)
dml_plr.fit(store_predictions=True)
lasso_plr = dml_plr.summary.coef[0]
lasso_std_plr = dml_plr.summary['std err'][0]
dml_plr.summary
```
:::
::::::
\newline
Let us check the predictive performance of this model.
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
dml_plr$params_names()
g_hat <- as.matrix(dml_plr$predictions$ml_g) # predictions of g_o
m_hat <- as.matrix(dml_plr$predictions$ml_m) # predictions of m_o
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
g_hat = dml_plr.predictions['ml_g'].flatten() # predictions of g_o
m_hat = dml_plr.predictions['ml_m'].flatten() # predictions of m_o
print(dml_plr.params_names)
```
:::
::::::
\newline
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# cross-fitted RMSE: outcome
y <- as.matrix(pension$net_tfa) # true observations
theta <- as.numeric(dml_plr$coef) # estimated regression coefficient
d <- as.matrix(pension$e401)
predictions_y <- as.matrix(d*theta)+g_hat # predictions for y
lasso_y_rmse <- sqrt(mean((y-predictions_y)^2))
lasso_y_rmse
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
# cross-fitted RMSE: outcome
y = pension.net_tfa.to_numpy() # true observations
theta = dml_plr.coef[ 0 ] # estimated regression coefficient
d = pension.e401.to_numpy()
predictions_y = d*theta + g_hat # predictions for y
lasso_y_rmse = np.sqrt( np.mean( ( y - predictions_y ) ** 2 ) )
lasso_y_rmse
```
:::
::::::
\newline
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# cross-fitted RMSE: treatment
d <- as.matrix(pension$e401)
lasso_d_rmse <- sqrt(mean((d-m_hat)^2))
lasso_d_rmse
# cross-fitted ce: treatment
mean(ifelse(m_hat > 0.5, 1, 0) != d)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
# cross-fitted RMSE: treatment
d = pension.e401.to_numpy()
lasso_d_rmse = np.sqrt( np.mean( ( d - m_hat ) ** 2 ) )
print( lasso_d_rmse )
# cross-fitted ce: treatment
print(np.mean( ( m_hat > 0.5 ) * 1 != d ))
```
:::
::::::
\newline
Then, we repeat this procedure for various machine learning methods.
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# Random Forest
lgr::get_logger("mlr3")$set_threshold("warn")
randomForest <- lrn("regr.ranger")
randomForest_class <- lrn("classif.ranger")
dml_plr <- DoubleMLPLR$new(data_ml_aux,
ml_g = randomForest,
ml_m = randomForest_class,
n_folds=3)
dml_plr$fit(store_predictions=TRUE) # set store_predictions=TRUE to evaluate the model
forest_plr <- dml_plr$coef
forest_std_plr <- dml_plr$se
dml_plr$summary()
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python message=FALSE, warning=FALSE}
# Random Forest
randomForest = RandomForestRegressor(
n_estimators = 500 )
randomForest_class = RandomForestClassifier(
n_estimators = 500 )
dml_plr = dml.DoubleMLPLR(data_ml_aux, ml_g = randomForest, \
ml_m = randomForest_class, n_folds = 3)
dml_plr.fit(store_predictions=True) # set store_predictions=TRUE to evaluate the model
forest_plr = dml_plr.coef
forest_std_plr = dml_plr.summary[ 'std err' ]
dml_plr.summary
```
:::
::::::
\newline
We can compare the accuracy of this model to the model that has been estimated with lasso.
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# Evaluation predictions
g_hat <- as.matrix(dml_plr$predictions$ml_g) # predictions of g_o
m_hat <- as.matrix(dml_plr$predictions$ml_m) # predictions of m_o
theta <- as.numeric(dml_plr$coef) # estimated regression coefficient
predictions_y <- as.matrix(d*theta)+g_hat # predictions for y
forest_y_rmse <- sqrt(mean((y-predictions_y)^2))
# cross-fitted RMSE: treatment
forest_d_rmse <- sqrt(mean((d-m_hat)^2))
#### Results
forest_y_rmse
forest_d_rmse
# cross-fitted ce: treatment
mean(ifelse(m_hat > 0.5, 1, 0) != d)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python message=FALSE, warning=FALSE}
# Evaluation predictions
g_hat = dml_plr.predictions['ml_g'].flatten() # predictions of g_o
m_hat = dml_plr.predictions['ml_m'].flatten() # predictions of m_o
y = pension.net_tfa.to_numpy()
theta = dml_plr.coef[ 0 ] # estimated regression coefficient
predictions_y = d*theta + g_hat # predictions for y
forest_y_rmse = np.sqrt( np.mean( ( y - predictions_y ) ** 2 ) )
# cross-fitted RMSE: treatment
forest_d_rmse = np.sqrt( np.mean( ( d - m_hat ) ** 2 ) )
#### Results
print( forest_y_rmse )
print( forest_d_rmse )
# cross-fitted ce: treatment
np.mean( ( m_hat > 0.5 ) * 1 != d )
```
:::
::::::
\newline
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# Trees
lgr::get_logger("mlr3")$set_threshold("warn")
trees <- lrn("regr.rpart")
trees_class <- lrn("classif.rpart")
dml_plr <- DoubleMLPLR$new(data_ml_aux, ml_g = trees, ml_m = trees_class, n_folds=3)
dml_plr$fit(store_predictions=TRUE)
dml_plr$summary()
tree_plr <- dml_plr$coef
tree_std_plr <- dml_plr$se
# Evaluation predictions
g_hat <- as.matrix(dml_plr$predictions$ml_g) # predictions of g_o
m_hat <- as.matrix(dml_plr$predictions$ml_m) # predictions of m_o
theta <- as.numeric(dml_plr$coef) # estimated regression coefficient
predictions_y <- as.matrix(d*theta)+g_hat # predictions for y
tree_y_rmse <- sqrt(mean((y-predictions_y)^2))
tree_y_rmse
# cross-fitted RMSE: treatment
tree_d_rmse <- sqrt(mean((d-m_hat)^2))
tree_d_rmse
# cross-fitted ce: treatment
mean(ifelse(m_hat > 0.5, 1, 0) != d)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
# Trees
trees = DecisionTreeRegressor(
max_depth=30, ccp_alpha=0.01, min_samples_split=20, \
min_samples_leaf= np.round(20/3).astype(int))
trees_class = DecisionTreeClassifier( max_depth=30, ccp_alpha=0.01, \
min_samples_split=20, \
min_samples_leaf= np.round(20/3).astype(int) )
np.random.seed(123)
dml_plr = dml.DoubleMLPLR(data_ml_aux,
ml_g = trees,
ml_m = trees_class,
n_folds = 3)
dml_plr.fit(store_predictions=True)
tree_summary = dml_plr.summary
print(tree_summary)
dml_plr.fit(store_predictions=True)
dml_plr.summary
tree_plr = dml_plr.coef
tree_std_plr = dml_plr.summary[ 'std err' ]
# Evaluation predictions
g_hat = dml_plr.predictions['ml_g'].flatten() # predictions of g_o
m_hat = dml_plr.predictions['ml_m'].flatten() # predictions of m_o
y = pension.net_tfa.to_numpy()
theta = dml_plr.coef[ 0 ] # estimated regression coefficient
predictions_y = d*theta + g_hat # predictions for y
tree_y_rmse = np.sqrt( np.mean( ( y - predictions_y ) ** 2 ) )
print( tree_y_rmse )
# cross-fitted RMSE: treatment
tree_d_rmse = np.sqrt( np.mean( ( d - m_hat ) ** 2 ) )
print( tree_d_rmse )
# cross-fitted ce: treatment
np.mean( ( m_hat > 0.5 ) * 1 != d )
```
:::
::::::
\newline
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
# Boosting
lgr::get_logger("mlr3")$set_threshold("warn")
boost<- lrn("regr.xgboost",objective="reg:squarederror")
boost_class <- lrn("classif.xgboost",objective = "binary:logistic",eval_metric ="logloss")
dml_plr <- DoubleMLPLR$new(data_ml_aux, ml_g = boost, ml_m = boost_class, n_folds=3)
dml_plr$fit(store_predictions=TRUE)
dml_plr$summary()
boost_plr <- dml_plr$coef
boost_std_plr <- dml_plr$se
# Evaluation predictions
g_hat <- as.matrix(dml_plr$predictions$ml_g) # predictions of g_o
m_hat <- as.matrix(dml_plr$predictions$ml_m) # predictions of m_o
theta <- as.numeric(dml_plr$coef) # estimated regression coefficient
predictions_y <- as.matrix(d*theta)+g_hat # predictions for y
boost_y_rmse <- sqrt(mean((y-predictions_y)^2))
boost_y_rmse
# cross-fitted RMSE: treatment
boost_d_rmse <- sqrt(mean((d-m_hat)^2))
boost_d_rmse
# cross-fitted ce: treatment
mean(ifelse(m_hat > 0.5, 1, 0) != d)
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
# Boosted Trees
boost = XGBRegressor(n_jobs=1, objective = "reg:squarederror" )
boost_class = XGBClassifier(use_label_encoder=False, n_jobs=1,
objective = "binary:logistic", \
eval_metric = "logloss" )
np.random.seed(123)
dml_plr = dml.DoubleMLPLR( data_ml_aux ,
ml_g = boost,
ml_m = boost_class,
n_folds = 3)
dml_plr.fit(store_predictions=True)
boost_summary = dml_plr.summary
print( boost_summary )
boost_plr = dml_plr.coef
boost_std_plr = dml_plr.summary[ 'std err' ]
# Evaluation predictions
g_hat = dml_plr.predictions['ml_g'].flatten() # predictions of g_o
m_hat = dml_plr.predictions['ml_m'].flatten() # predictions of m_o
y = pension.net_tfa.to_numpy()
theta = dml_plr.coef[ 0 ] # estimated regression coefficient
predictions_y = d*theta + g_hat # predictions for y
boost_y_rmse = np.sqrt( np.mean( ( y - predictions_y ) ** 2 ) )
print( boost_y_rmse )
# cross-fitted RMSE: treatment
boost_d_rmse = np.sqrt( np.mean( ( d - m_hat ) ** 2 ) )
print( boost_d_rmse )
# cross-fitted ce: treatment
np.mean( ( m_hat > 0.5 ) * 1 != d )
```
:::
::::::
\newline
Let's sum up the results:
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
library(xtable)
table <- matrix(0, 4, 4)
table[1,1:4] <- c(lasso_plr,forest_plr,tree_plr,boost_plr)
table[2,1:4] <- c(lasso_std_plr,forest_std_plr,tree_std_plr,boost_std_plr)
table[3,1:4] <- c(lasso_y_rmse,forest_y_rmse,tree_y_rmse,boost_y_rmse)
table[4,1:4] <- c(lasso_d_rmse,forest_d_rmse,tree_d_rmse,boost_d_rmse)
rownames(table) <- c("Estimate","Std.Error","RMSE Y","RMSE D")
colnames(table) <- c("Lasso","Random Forest","Trees","Boosting")
tab<- xtable(table, digits = 2)
tab
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
table = np.zeros( (4, 4) )
table[0,0:4] = lasso_plr,forest_plr[0],tree_plr[0],boost_plr[0]
table[1,0:4] = lasso_std_plr,forest_std_plr,tree_std_plr,boost_std_plr
table[2,0:4] = lasso_y_rmse,forest_y_rmse,tree_y_rmse,boost_y_rmse
table[3,0:4] = lasso_d_rmse,forest_d_rmse,tree_d_rmse,boost_d_rmse
table_pd = pd.DataFrame( table , index = ["Estimate","Std.Error","RMSE Y","RMSE D" ], \
columns = [ "Lasso","Random Forest","Trees","Boosting"])
table_pd.to_latex()
```
:::
::::::
\newline
The best model with lowest RMSE in both equation is the PLR model estimated via lasso. It gives the following estimate:
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
lasso_plr
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
lasso_plr
```
:::
::::::
\newline
## Interactive Regression Model (IRM)
Next, we consider estimation of average treatment effects when treatment effects are fully heterogeneous:
\begin{eqnarray}\label{eq: HetPL1}
& Y = g_0(D, X) + U, & \quad E[U \mid X, D]= 0,\\
& D = m_0(X) + V, & \quad E[V\mid X] = 0.
\end{eqnarray}
To reduce the disproportionate impact of extreme propensity score weights in the interactive model
we trim the propensity scores which are close to the bounds.
:::::: {.columns}
::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{r message=FALSE, warning=FALSE}
set.seed(123)
lgr::get_logger("mlr3")$set_threshold("warn")
dml_irm = DoubleMLIRM$new(data_ml_aux,
ml_g = lasso,
ml_m = lasso_class,
trimming_threshold = 0.01,
n_folds=3)
dml_irm$fit(store_predictions=TRUE)
dml_irm$summary()
lasso_irm <- dml_irm$coef
lasso_std_irm <- dml_irm$se
# predictions
dml_irm$params_names()
g0_hat <- as.matrix(dml_irm$predictions$ml_g0) # predictions of g_0(D=0, X)
g1_hat <- as.matrix(dml_irm$predictions$ml_g1) # predictions of g_0(D=1, X)
g_hat <- d*g1_hat+(1-d)*g0_hat # predictions of g_0
m_hat <- as.matrix(dml_irm$predictions$ml_m) # predictions of m_o
```
:::
::: {.column width="1%" data-latex="{0.04\textwidth}"}
\
<!-- an empty Div (with a white space), serving as
a column separator -->
:::
:::::: {.column width="49.5%" data-latex="{0.48\textwidth}"}
```{python}
# Lasso
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, max_iter=20000))
# Initialize DoubleMLIRM model
np.random.seed(123)
dml_irm = dml.DoubleMLIRM(data_ml_aux, ml_g = lasso, ml_m = lasso_class, trimming_threshold = 0.01, n_folds = 3)
dml_irm.fit(store_predictions=True)
lasso_summary = dml_irm.summary
print(dml_irm.summary)
lasso_irm = dml_irm.coef[0]
lasso_std_irm = dml_irm.se[0]
# predictions
print(dml_irm.params_names)
g0_hat = dml_irm.predictions['ml_g0'].flatten() # predictions of g_0(D=0, X)
g1_hat = dml_irm.predictions['ml_g1'].flatten() # predictions of g_0(D=1, X)