-
Notifications
You must be signed in to change notification settings - Fork 25
/
double_ml.R
1710 lines (1585 loc) · 59.5 KB
/
double_ml.R
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 Abstract class DoubleML
#'
#' @description
#' Abstract base class that can't be initialized.
#'
#'
#' @format [R6::R6Class] object.
#'
#' @family DoubleML
DoubleML = R6Class("DoubleML",
active = list(
#' @field all_coef (`matrix()`) \cr
#' Estimates of the causal parameter(s) for the `n_rep` different sample
#' splits after calling `fit()`.
all_coef = function(value) {
if (missing(value)) {
return(private$all_coef_)
} else {
stop("can't set field all_coef")
}
},
#' @field all_dml1_coef (`array()`) \cr
#' Estimates of the causal parameter(s) for the `n_rep` different sample
#' splits after calling `fit()` with `dml_procedure = "dml1"`.
all_dml1_coef = function(value) {
if (missing(value)) {
return(private$all_dml1_coef_)
} else {
stop("can't set field all_dml1_coef")
}
},
#' @field all_se (`matrix()`) \cr
#' Standard errors of the causal parameter(s) for the `n_rep` different
#' sample splits after calling `fit()`.
all_se = function(value) {
if (missing(value)) {
return(private$all_se_)
} else {
stop("can't set field all_se")
}
},
#' @field apply_cross_fitting (`logical(1)`) \cr
#' Indicates whether cross-fitting should be applied. Default is `TRUE`.
apply_cross_fitting = function(value) {
if (missing(value)) {
return(private$apply_cross_fitting_)
} else {
stop("can't set field apply_cross_fitting")
}
},
#' @field boot_coef (`matrix()`) \cr
#' Bootstrapped coefficients for the causal parameter(s) after calling
#' `fit()` and `bootstrap()`.
boot_coef = function(value) {
if (missing(value)) {
return(private$boot_coef_)
} else {
stop("can't set field boot_coef")
}
},
#' @field boot_t_stat (`matrix()`) \cr
#' Bootstrapped t-statistics for the causal parameter(s) after calling
#' `fit()` and `bootstrap()`.
boot_t_stat = function(value) {
if (missing(value)) {
return(private$boot_t_stat_)
} else {
stop("can't set field boot_t_stat")
}
},
#' @field coef (`numeric()`) \cr
#' Estimates for the causal parameter(s) after calling `fit()`.
coef = function(value) {
if (missing(value)) {
return(private$coef_)
} else {
stop("can't set field coef")
}
},
#' @field data ([`data.table`][data.table::data.table()])\cr
#' Data object.
data = function(value) {
if (missing(value)) {
return(private$data_)
} else {
stop("can't set field data")
}
},
#' @field dml_procedure (`character(1)`) \cr
#' A `character()` (`"dml1"` or `"dml2"`) specifying the double machine
#' learning algorithm. Default is `"dml2"`.
dml_procedure = function(value) {
if (missing(value)) {
return(private$dml_procedure_)
} else {
stop("can't set field dml_procedure")
}
},
#' @field draw_sample_splitting (`logical(1)`) \cr
#' Indicates whether the sample splitting should be drawn during
#' initialization of the object. Default is `TRUE`.
draw_sample_splitting = function(value) {
if (missing(value)) {
return(private$draw_sample_splitting_)
} else {
stop("can't set field draw_sample_splitting")
}
},
#' @field learner (named `list()`) \cr
#' The machine learners for the nuisance functions.
learner = function(value) {
if (missing(value)) {
return(private$learner_)
} else {
stop("can't set field learner")
}
},
#' @field n_folds (`integer(1)`) \cr
#' Number of folds. Default is `5`.
n_folds = function(value) {
if (missing(value)) {
return(private$n_folds_)
} else {
stop("can't set field n_folds")
}
},
#' @field n_rep (`integer(1)`) \cr
#' Number of repetitions for the sample splitting. Default is `1`.
n_rep = function(value) {
if (missing(value)) {
return(private$n_rep_)
} else {
stop("can't set field n_rep")
}
},
#' @field params (named `list()`) \cr
#' The hyperparameters of the learners.
params = function(value) {
if (missing(value)) {
return(private$params_)
} else {
stop("can't set field params")
}
},
#' @field psi (`array()`) \cr
#' Value of the score function
#' \eqn{\psi(W;\theta, \eta)=\psi_a(W;\eta) \theta + \psi_b (W; \eta)}
#' after calling `fit()`.
psi = function(value) {
if (missing(value)) {
return(private$psi_)
} else {
stop("can't set field psi")
}
},
#' @field psi_a (`array()`) \cr
#' Value of the score function component \eqn{\psi_a(W;\eta)} after
#' calling `fit()`.
psi_a = function(value) {
if (missing(value)) {
return(private$psi_a_)
} else {
stop("can't set field psi_a")
}
},
#' @field psi_b (`array()`) \cr
#' Value of the score function component \eqn{\psi_b(W;\eta)} after
#' calling `fit()`.
psi_b = function(value) {
if (missing(value)) {
return(private$psi_b_)
} else {
stop("can't set field psi_b")
}
},
#' @field predictions (`array()`) \cr
#' Predictions of the nuisance models after calling
#' `fit(store_predictions=TRUE)`.
predictions = function(value) {
if (missing(value)) {
return(private$predictions_)
} else {
stop("can't set field predictions")
}
},
#' @field models (`array()`) \cr
#' The fitted nuisance models after calling
#' `fit(store_models=TRUE)`.
models = function(value) {
if (missing(value)) {
return(private$models_)
} else {
stop("can't set field models")
}
},
#' @field pval (`numeric()`) \cr
#' p-values for the causal parameter(s) after calling `fit()`.
pval = function(value) {
if (missing(value)) {
return(private$pval_)
} else {
stop("can't set field pval")
}
},
#' @field score (`character(1)`, `function()`) \cr
#' A `character(1)` or `function()` specifying the score function.
score = function(value) {
if (missing(value)) {
return(private$score_)
} else {
stop("can't set field score")
}
},
#' @field se (`numeric()`) \cr
#' Standard errors for the causal parameter(s) after calling `fit()`.
se = function(value) {
if (missing(value)) {
return(private$se_)
} else {
stop("can't set field se")
}
},
#' @field smpls (`list()`) \cr
#' The partition used for cross-fitting.
smpls = function(value) {
if (missing(value)) {
return(private$smpls_)
} else {
stop("can't set field smpls")
}
},
#' @field smpls_cluster (`list()`) \cr
#' The partition of clusters used for cross-fitting.
smpls_cluster = function(value) {
if (missing(value)) {
return(private$smpls_cluster_)
} else {
stop("can't set field smpls_cluster")
}
},
#' @field t_stat (`numeric()`) \cr
#' t-statistics for the causal parameter(s) after calling `fit()`.
t_stat = function(value) {
if (missing(value)) {
return(private$t_stat_)
} else {
stop("can't set field t_stat")
}
},
#' @field tuning_res (named `list()`) \cr
#' Results from hyperparameter tuning.
tuning_res = function(value) {
if (missing(value)) {
return(private$tuning_res_)
} else {
stop("can't set field tuning_res")
}
}),
public = list(
#' @description
#' DoubleML is an abstract class that can't be initialized.
initialize = function() {
stop("DoubleML is an abstract class that can't be initialized.")
},
#' @description
#' Print DoubleML objects.
print = function() {
class_name = class(self)[1]
header = paste0(
"================= ", class_name,
" Object ==================\n")
if (private$is_cluster_data) {
cluster_info = paste0(
"Cluster variable(s): ",
paste0(self$data$cluster_cols, collapse = ", "),
"\n")
} else {
cluster_info = ""
}
data_info = paste0(
"Outcome variable: ", self$data$y_col, "\n",
"Treatment variable(s): ", paste0(self$data$d_cols, collapse = ", "),
"\n",
"Covariates: ", paste0(self$data$x_cols, collapse = ", "), "\n",
"Instrument(s): ", paste0(self$data$z_cols, collapse = ", "), "\n",
cluster_info,
"No. Observations: ", self$data$n_obs, "\n")
if (is.character(self$score)) {
score_info = paste0(
"Score function: ", self$score, "\n",
"DML algorithm: ", self$dml_procedure, "\n")
} else if (is.function(self$score)) {
score_info = paste0(
"Score function: User specified score function \n",
"DML algorithm: ", self$dml_procedure, "\n")
}
learner_info = character(length(self$learner))
for (i_lrn in seq_len(length(self$learner))) {
if (any(class(self$learner[[i_lrn]]) == "Learner")) {
learner_info[i_lrn] = paste0(
self$learner_names()[[i_lrn]], ": ",
self$learner[[i_lrn]]$id, "\n")
} else {
learner_info[i_lrn] = paste0(
self$learner_names()[[i_lrn]], ": ",
self$learner[i_lrn], "\n")
}
}
if (private$is_cluster_data) {
resampling_info = paste0(
"No. folds per cluster: ", private$n_folds_per_cluster, "\n",
"No. folds: ", self$n_folds, "\n",
"No. repeated sample splits: ", self$n_rep, "\n",
"Apply cross-fitting: ", self$apply_cross_fitting, "\n")
} else {
resampling_info = paste0(
"No. folds: ", self$n_folds, "\n",
"No. repeated sample splits: ", self$n_rep, "\n",
"Apply cross-fitting: ", self$apply_cross_fitting, "\n")
}
cat(header, "\n",
"\n------------------ Data summary ------------------\n",
data_info,
"\n------------------ Score & algorithm ------------------\n",
score_info,
"\n------------------ Machine learner ------------------\n",
learner_info,
"\n------------------ Resampling ------------------\n",
resampling_info,
"\n------------------ Fit summary ------------------\n ",
sep = "")
self$summary()
invisible(self)
},
#' @description
#' Estimate DoubleML models.
#'
#' @param store_predictions (`logical(1)`) \cr
#' Indicates whether the predictions for the nuisance functions should be
#' stored in field `predictions`. Default is `FALSE`.
#'
#'
#' @param store_models (`logical(1)`) \cr
#' Indicates whether the fitted models for the nuisance functions should be
#' stored in field `models` if you want to analyze the models or extract
#' information like variable importance. Default is `FALSE`.
#'
#' @return self
fit = function(store_predictions = FALSE, store_models = FALSE) {
if (store_predictions) {
private$initialize_predictions()
}
if (store_models) {
private$initialize_models()
}
# TODO: insert check for tuned params
for (i_rep in 1:self$n_rep) {
private$i_rep = i_rep
for (i_treat in 1:self$data$n_treat) {
private$i_treat = i_treat
if (self$data$n_treat > 1) {
self$data$set_data_model(self$data$d_cols[i_treat])
}
# ml estimation of nuisance models and computation of psi elements
res = private$nuisance_est(private$get__smpls())
private$psi_a_[, private$i_rep, private$i_treat] = res$psi_a
private$psi_b_[, private$i_rep, private$i_treat] = res$psi_b
if (store_predictions) {
private$store_predictions(res$preds)
}
if (store_models) {
private$store_models(res$models)
}
# estimate the causal parameter
private$all_coef_[private$i_treat, private$i_rep] = private$est_causal_pars()
# compute score (depends on estimated causal parameter)
private$psi_[, private$i_rep, private$i_treat] = private$compute_score()
# compute standard errors for causal parameter
private$all_se_[private$i_treat, private$i_rep] = private$se_causal_pars()
}
}
private$agg_cross_fit()
private$t_stat_ = self$coef / self$se
private$pval_ = 2 * pnorm(-abs(self$t_stat))
names(private$coef_) = names(private$se_) = names(private$t_stat_) =
names(private$pval_) = self$data$d_cols
invisible(self)
},
#' @description
#' Multiplier bootstrap for DoubleML models.
#'
#' @param method (`character(1)`) \cr
#' A `character(1)` (`"Bayes"`, `"normal"` or `"wild"`) specifying the
#' multiplier bootstrap method.
#'
#' @param n_rep_boot (`integer(1)`) \cr
#' The number of bootstrap replications.
#'
#' @return self
bootstrap = function(method = "normal", n_rep_boot = 500) {
if (all(is.na(self$psi))) {
stop("Apply fit() before bootstrap().")
}
assert_choice(method, c("normal", "Bayes", "wild"))
assert_count(n_rep_boot, positive = TRUE)
if (private$is_cluster_data) {
stop("bootstrap not yet implemented with clustering.")
}
private$initialize_boot_arrays(n_rep_boot)
for (i_rep in 1:self$n_rep) {
private$i_rep = i_rep
if (self$apply_cross_fitting) {
n_obs = self$data$n_obs
} else {
smpls = private$get__smpls()
test_ids = smpls$test_ids
test_index = test_ids[[1]]
n_obs = length(test_index)
}
weights = draw_weights(method, n_rep_boot, n_obs)
for (i_treat in 1:self$data$n_treat) {
private$i_treat = i_treat
boot_res = private$compute_bootstrap(weights, n_rep_boot)
i_start = (private$i_rep - 1) * private$n_rep_boot + 1
i_end = private$i_rep * private$n_rep_boot
private$boot_coef_[private$i_treat, i_start:i_end] = boot_res$boot_coef
private$boot_t_stat_[private$i_treat, i_start:i_end] = boot_res$boot_t_stat
}
}
invisible(self)
},
#' @description
#' Draw sample splitting for DoubleML models.
#'
#' The samples are drawn according to the attributes `n_folds`, `n_rep`
#' and `apply_cross_fitting`.
#'
#' @return self
split_samples = function() {
dummy_task = Task$new("dummy_resampling", "regr", self$data$data)
if (self$apply_cross_fitting) {
if (private$is_cluster_data) {
all_smpls = list()
all_smpls_cluster = list()
for (i_rep in 1:self$n_rep) {
smpls_cluster_vars = list()
for (i_var in 1:self$data$n_cluster_vars) {
clusters = unique(self$data$data_model[[self$data$cluster_cols[i_var]]])
n_clusters = length(clusters)
dummy_task = Task$new(
"dummy_resampling", "regr",
data.table(dummy_var = rep(0, n_clusters)))
dummy_resampling_scheme = rsmp("repeated_cv",
folds = private$n_folds_per_cluster,
repeats = 1)$instantiate(dummy_task)
train_ids = lapply(
1:(private$n_folds_per_cluster),
function(x) clusters[dummy_resampling_scheme$train_set(x)])
test_ids = lapply(
1:(private$n_folds_per_cluster),
function(x) clusters[dummy_resampling_scheme$test_set(x)])
smpls_cluster_vars[[i_var]] = list(
train_ids = train_ids,
test_ids = test_ids)
}
smpls = list(train_ids = list(), test_ids = list())
smpls_cluster = list(train_ids = list(), test_ids = list())
cart = expand.grid(lapply(
1:self$data$n_cluster_vars,
function(x) 1:private$n_folds_per_cluster))
for (i_smpl in 1:(self$n_folds)) {
ind_train = rep(TRUE, self$data$n_obs)
ind_test = rep(TRUE, self$data$n_obs)
this_cluster_smpl_train = list()
this_cluster_smpl_test = list()
for (i_var in 1:self$data$n_cluster_vars) {
i_fold = cart[i_smpl, i_var]
train_clusters = smpls_cluster_vars[[i_var]]$train_ids[[i_fold]]
test_clusters = smpls_cluster_vars[[i_var]]$test_ids[[i_fold]]
this_cluster_smpl_train[[i_var]] = train_clusters
this_cluster_smpl_test[[i_var]] = test_clusters
xx = self$data$data_model[[self$data$cluster_cols[i_var]]] %in% train_clusters
ind_train = ind_train & xx
xx = self$data$data_model[[self$data$cluster_cols[i_var]]] %in% test_clusters
ind_test = ind_test & xx
}
smpls$train_ids[[i_smpl]] = seq(self$data$n_obs)[ind_train]
smpls$test_ids[[i_smpl]] = seq(self$data$n_obs)[ind_test]
smpls_cluster$train_ids[[i_smpl]] = this_cluster_smpl_train
smpls_cluster$test_ids[[i_smpl]] = this_cluster_smpl_test
}
all_smpls[[i_rep]] = smpls
all_smpls_cluster[[i_rep]] = smpls_cluster
}
smpls = all_smpls
private$smpls_cluster_ = all_smpls_cluster
} else {
dummy_resampling_scheme = rsmp("repeated_cv",
folds = self$n_folds,
repeats = self$n_rep)$instantiate(dummy_task)
train_ids = lapply(
1:(self$n_folds * self$n_rep),
function(x) dummy_resampling_scheme$train_set(x))
test_ids = lapply(
1:(self$n_folds * self$n_rep),
function(x) dummy_resampling_scheme$test_set(x))
smpls = lapply(1:self$n_rep, function(i_repeat) {
list(
train_ids = train_ids[((i_repeat - 1) * self$n_folds + 1):
(i_repeat * self$n_folds)],
test_ids = test_ids[((i_repeat - 1) * self$n_folds + 1):
(i_repeat * self$n_folds)])
})
}
} else {
if (self$n_folds == 2) {
dummy_resampling_scheme = rsmp("holdout", ratio = 0.5)$instantiate(dummy_task)
train_ids = list(dummy_resampling_scheme$train_set(1))
test_ids = list(dummy_resampling_scheme$test_set(1))
smpls = list(list(train_ids = train_ids, test_ids = test_ids))
} else if (self$n_folds == 1) {
dummy_resampling_scheme = rsmp("insample")$instantiate(dummy_task)
train_ids = lapply(
1:(self$n_folds * self$n_rep),
function(x) dummy_resampling_scheme$train_set(x))
test_ids = lapply(
1:(self$n_folds * self$n_rep),
function(x) dummy_resampling_scheme$test_set(x))
smpls = lapply(1:self$n_rep, function(i_repeat) {
list(
train_ids = train_ids[((i_repeat - 1) * self$n_folds + 1):
(i_repeat * self$n_folds)],
test_ids = test_ids[((i_repeat - 1) * self$n_folds + 1):
(i_repeat * self$n_folds)])
})
}
}
private$smpls_ = smpls
invisible(self)
},
#' @description
#' Set the sample splitting for DoubleML models.
#'
#' The attributes `n_folds` and `n_rep` are derived from the provided
#' partition.
#'
#' @param smpls (`list()`) \cr
#' A nested `list()`. The outer lists needs to provide an entry per
#' repeated sample splitting (length of the list is set as `n_rep`).
#' The inner list is a named `list()` with names `train_ids` and `test_ids`.
#' The entries in `train_ids` and `test_ids` must be partitions per fold
#' (length of `train_ids` and `test_ids` is set as `n_folds`).
#'
#' @return self
#'
#' @examples
#' library(DoubleML)
#' library(mlr3)
#' set.seed(2)
#' obj_dml_data = make_plr_CCDDHNR2018(n_obs=10)
#' dml_plr_obj = DoubleMLPLR$new(obj_dml_data,
#' lrn("regr.rpart"), lrn("regr.rpart"))
#'
#' # simple sample splitting with two folds and without cross-fitting
#' smpls = list(list(train_ids = list(c(1, 2, 3, 4, 5)),
#' test_ids = list(c(6, 7, 8, 9, 10))))
#' dml_plr_obj$set_sample_splitting(smpls)
#'
#' # sample splitting with two folds and cross-fitting but no repeated cross-fitting
#' smpls = list(list(train_ids = list(c(1, 2, 3, 4, 5), c(6, 7, 8, 9, 10)),
#' test_ids = list(c(6, 7, 8, 9, 10), c(1, 2, 3, 4, 5))))
#' dml_plr_obj$set_sample_splitting(smpls)
#'
#' # sample splitting with two folds and repeated cross-fitting with n_rep = 2
#' smpls = list(list(train_ids = list(c(1, 2, 3, 4, 5), c(6, 7, 8, 9, 10)),
#' test_ids = list(c(6, 7, 8, 9, 10), c(1, 2, 3, 4, 5))),
#' list(train_ids = list(c(1, 3, 5, 7, 9), c(2, 4, 6, 8, 10)),
#' test_ids = list(c(2, 4, 6, 8, 10), c(1, 3, 5, 7, 9))))
#' dml_plr_obj$set_sample_splitting(smpls)
set_sample_splitting = function(smpls) {
if (private$is_cluster_data) {
stop(paste(
"Externally setting the sample splitting for DoubleML is",
"not yet implemented with clustering."))
}
if (test_list(smpls, names = "unnamed")) {
lapply(smpls, function(x) check_smpl_split(x, self$data$n_obs))
n_folds_each_train_smpl = vapply(
smpls, function(x) length(x$train_ids),
integer(1L))
n_folds_each_test_smpl = vapply(
smpls, function(x) length(x$test_ids),
integer(1L))
if (!all(n_folds_each_train_smpl == n_folds_each_train_smpl[1])) {
stop("Different number of folds for repeated cross-fitting.")
}
smpls_are_partitions = vapply(
smpls,
function(x) check_is_partition(x$test_ids, self$data$n_obs),
FUN.VALUE = TRUE)
if (all(smpls_are_partitions)) {
if (length(smpls) == 1 &
n_folds_each_train_smpl[1] == 1 &
check_is_partition(smpls[[1]]$train_ids, self$data$n_obs)) {
private$n_rep_ = 1
private$n_folds_ = 1
private$apply_cross_fitting_ = FALSE
private$smpls_ = smpls
} else {
private$n_rep_ = length(smpls)
private$n_folds_ = n_folds_each_train_smpl[1]
private$apply_cross_fitting_ = TRUE
lapply(
smpls,
function(x) {
check_smpl_split(x, self$data$n_obs,
check_intersect = TRUE)
})
private$smpls_ = smpls
}
} else {
if (n_folds_each_train_smpl[1] != 1) {
stop(paste(
"Invalid partition provided.",
"Tuples (train_ids, test_ids) for more than one fold",
"provided that don't form a partition."))
}
if (length(smpls) != 1) {
stop(paste(
"Repeated sample splitting without cross-fitting not",
"implemented."))
}
private$n_rep_ = length(smpls)
private$n_folds_ = 2
private$apply_cross_fitting_ = FALSE
lapply(
smpls,
function(x) {
check_smpl_split(x, self$data$n_obs,
check_intersect = TRUE)
})
private$smpls_ = smpls
}
} else {
check_smpl_split(smpls, self$data$n_obs)
private$n_rep_ = 1
n_folds = length(smpls$train_ids)
if (check_is_partition(smpls$test_ids, self$data$n_obs)) {
if (n_folds == 1 & check_is_partition(smpls$train_ids, self$data$n_obs)) {
private$n_folds_ = 1
private$apply_cross_fitting_ = FALSE
private$smpls_ = list(smpls)
} else {
private$n_folds_ = n_folds
private$apply_cross_fitting_ = TRUE
check_smpl_split(smpls, self$data$n_obs,
check_intersect = TRUE)
private$smpls_ = list(smpls)
}
} else {
if (n_folds != 1) {
stop(paste(
"Invalid partition provided.",
"Tuples (train_ids, test_ids) for more than one fold",
"provided that don't form a partition."))
}
private$n_folds_ = 2
private$apply_cross_fitting_ = FALSE
check_smpl_split(smpls, self$data$n_obs,
check_intersect = TRUE)
private$smpls_ = list(smpls)
}
}
private$initialize_arrays()
invisible(self)
},
#' @description
#' Hyperparameter-tuning for DoubleML models.
#'
#' The hyperparameter-tuning is performed using the tuning methods provided
#' in the [mlr3tuning](https://mlr3tuning.mlr-org.com/) package. For more
#' information on tuning in [mlr3](https://mlr3.mlr-org.com/), we refer to
#' the section on parameter tuning in the
#' [mlr3 book](https://mlr3book.mlr-org.com/chapters/chapter4/hyperparameter_optimization.html).
#'
#' @param param_set (named `list()`) \cr
#' A named `list` with a parameter grid for each nuisance model/learner
#' (see method `learner_names()`). The parameter grid must be an object of
#' class [ParamSet][paradox::ParamSet].
#'
#' @param tune_settings (named `list()`) \cr
#' A named `list()` with arguments passed to the hyperparameter-tuning with
#' [mlr3tuning](https://mlr3tuning.mlr-org.com/) to set up
#' [TuningInstance][mlr3tuning::TuningInstanceSingleCrit] objects.
#' `tune_settings` has entries
#' * `terminator` ([Terminator][bbotk::Terminator]) \cr
#' A [Terminator][bbotk::Terminator] object. Specification of `terminator`
#' is required to perform tuning.
#' * `algorithm` ([Tuner][mlr3tuning::Tuner] or `character(1)`) \cr
#' A [Tuner][mlr3tuning::Tuner] object (recommended) or key passed to the
#' respective dictionary to specify the tuning algorithm used in
#' [tnr()][mlr3tuning::tnr()]. `algorithm` is passed as an argument to
#' [tnr()][mlr3tuning::tnr()]. If `algorithm` is not specified by the users,
#' default is set to `"grid_search"`. If set to `"grid_search"`, then
#' additional argument `"resolution"` is required.
#' * `rsmp_tune` ([Resampling][mlr3::Resampling] or `character(1)`)\cr
#' A [Resampling][mlr3::Resampling] object (recommended) or option passed
#' to [rsmp()][mlr3::mlr_sugar] to initialize a
#' [Resampling][mlr3::Resampling] for parameter tuning in `mlr3`.
#' If not specified by the user, default is set to `"cv"`
#' (cross-validation).
#' * `n_folds_tune` (`integer(1)`, optional) \cr
#' If `rsmp_tune = "cv"`, number of folds used for cross-validation.
#' If not specified by the user, default is set to `5`.
#' * `measure` (`NULL`, named `list()`, optional) \cr
#' Named list containing the measures used for parameter tuning. Entries in
#' list must either be [Measure][mlr3::Measure] objects or keys to be
#' passed to passed to [msr()][mlr3::msr()]. The names of the entries must
#' match the learner names (see method `learner_names()`). If set to `NULL`,
#' default measures are used, i.e., `"regr.mse"` for continuous outcome
#' variables and `"classif.ce"` for binary outcomes.
#' * `resolution` (`character(1)`) \cr The key passed to the respective
#' dictionary to specify the tuning algorithm used in
#' [tnr()][mlr3tuning::tnr()]. `resolution` is passed as an argument to
#' [tnr()][mlr3tuning::tnr()].
#'
#' @param tune_on_folds (`logical(1)`) \cr
#' Indicates whether the tuning should be done fold-specific or globally.
#' Default is `FALSE`.
#'
#' @return self
tune = function(param_set, tune_settings = list(
n_folds_tune = 5,
rsmp_tune = mlr3::rsmp("cv", folds = 5),
measure = NULL,
terminator = mlr3tuning::trm("evals", n_evals = 20),
algorithm = mlr3tuning::tnr("grid_search"),
resolution = 5),
tune_on_folds = FALSE) {
assert_list(param_set)
valid_learner = self$learner_names()
if (!test_names(names(param_set), subset.of = valid_learner)) {
stop(paste(
"Invalid param_set", paste0(names(param_set), collapse = ", "),
"\n param_grids must be a named list with elements named",
paste0(valid_learner, collapse = ", ")))
}
for (i_grid in seq_len(length(param_set))) {
assert_class(param_set[[i_grid]], "ParamSet")
}
assert_logical(tune_on_folds, len = 1)
tune_settings = private$assert_tune_settings(tune_settings)
if (!self$apply_cross_fitting) {
stop("Parameter tuning for no-cross-fitting case not implemented.")
}
if (tune_on_folds) {
params_rep = vector("list", self$n_rep)
private$tuning_res_ = rep(list(params_rep), self$data$n_treat)
names(private$tuning_res_) = self$data$d_cols
private$fold_specific_params = TRUE
} else {
private$tuning_res_ = vector("list", self$data$n_treat)
names(private$tuning_res_) = self$data$d_cols
}
for (i_treat in 1:self$data$n_treat) {
private$i_treat = i_treat
if (self$data$n_treat > 1) {
self$data$set_data_model(self$data$d_cols[i_treat])
}
if (tune_on_folds) {
for (i_rep in 1:self$n_rep) {
private$i_rep = i_rep
param_tuning = private$nuisance_tuning(
private$get__smpls(),
param_set, tune_settings, tune_on_folds)
private$tuning_res_[[i_treat]][[i_rep]] = param_tuning
for (nuisance_model in names(param_tuning)) {
if (!is.null(param_tuning[[nuisance_model]][[1]])) {
self$set_ml_nuisance_params(
learner = nuisance_model,
treat_var = self$data$treat_col,
params = param_tuning[[nuisance_model]]$params,
set_fold_specific = FALSE)
} else {
next
}
}
}
} else {
private$i_rep = 1
param_tuning = private$nuisance_tuning(
private$get__smpls(),
param_set, tune_settings, tune_on_folds)
private$tuning_res_[[i_treat]] = param_tuning
for (nuisance_model in self$params_names()) {
if (!is.null(param_tuning[[nuisance_model]][[1]])) {
self$set_ml_nuisance_params(
learner = nuisance_model,
treat_var = self$data$treat_col,
params = param_tuning[[nuisance_model]]$params[[1]],
set_fold_specific = FALSE)
} else {
next
}
}
}
}
invisible(self)
},
#' @description
#' Summary for DoubleML models after calling `fit()`.
#'
#' @param digits (`integer(1)`) \cr
#' The number of significant digits to use when printing.
summary = function(digits = max(3L, getOption("digits") -
3L)) {
if (all(is.na(self$coef))) {
message("fit() not yet called.")
} else {
k = length(self$coef)
table = matrix(NA_real_, ncol = 4, nrow = k)
rownames(table) = names(self$coef)
colnames(table) = c("Estimate.", "Std. Error", "t value", "Pr(>|t|)")
table[, 1] = self$coef
table[, 2] = self$se
table[, 3] = self$t_stat
table[, 4] = self$pval
private$summary_table = table
if (length(k)) {
cat(
"Estimates and significance testing of the",
"effect of target variables\n")
res = as.matrix(printCoefmat(private$summary_table,
digits = digits,
P.values = TRUE,
has.Pvalue = TRUE))
cat("\n")
}
else {
cat("No coefficients\n")
}
cat("\n")
invisible(res)
}
},
#' @description
#' Confidence intervals for DoubleML models.
#'
#' @param joint (`logical(1)`) \cr
#' Indicates whether joint confidence intervals are computed.
#' Default is `FALSE`.
#'
#' @param level (`numeric(1)`) \cr
#' The confidence level. Default is `0.95`.
#'
#' @param parm (`numeric()` or `character()`) \cr
#' A specification of which parameters are to be given confidence intervals
#' among the variables for which inference was done, either a vector of
#' numbers or a vector of names. If missing, all parameters are considered
#' (default).
#' @return A `matrix()` with the confidence interval(s).
confint = function(parm, joint = FALSE, level = 0.95) {
assert_logical(joint, len = 1)
assert_numeric(level, len = 1)
if (level <= 0 | level >= 1) {
stop("'level' must be > 0 and < 1.")
}
if (missing(parm)) {
parm = names(self$coef)
}
else {
assert(
check_character(parm, max.len = self$data$n_treat),
check_numeric(parm, max.len = self$data$n_treat))
if (is.numeric(parm)) {
parm = names(self$coef)[parm]
}
}
if (joint == FALSE) {
a = (1 - level) / 2
a = c(a, 1 - a)
pct = format_perc(a, 3)
fac = qnorm(a)
ci = array(NA_real_,
dim = c(length(parm), 2L),
dimnames = list(parm, pct))
ci[] = self$coef[parm] + self$se[parm] %o% fac
}
if (joint == TRUE) {
a = (1 - level)
ab = c(a / 2, 1 - a / 2)
pct = format_perc(ab, 3)
ci = array(NA_real_,
dim = c(length(parm), 2L),
dimnames = list(parm, pct))
if (all(is.na(self$boot_coef))) {
stop(paste(
"Multiplier bootstrap has not yet been performed.",
"First call bootstrap() and then try confint() again."))
}
sim = apply(abs(self$boot_t_stat), 2, max)
hatc = quantile(sim, probs = 1 - a)
ci[, 1] = self$coef[parm] - hatc * self$se[parm]
ci[, 2] = self$coef[parm] + hatc * self$se[parm]
}
return(ci)
},
#' @description
#' Returns the names of the learners.
#'
#' @return `character()` with names of learners.
learner_names = function() {
return(names(self$learner))
},
#' @description
#' Returns the names of the nuisance models with hyperparameters.
#'
#' @return `character()` with names of nuisance models with hyperparameters.
params_names = function() {
return(names(self$params))
},
#' @description
#' Set hyperparameters for the nuisance models of DoubleML models.
#'