-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathdouble_ml.py
More file actions
1661 lines (1395 loc) · 63.8 KB
/
double_ml.py
File metadata and controls
1661 lines (1395 loc) · 63.8 KB
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
import copy
import warnings
from abc import ABC, abstractmethod
import numpy as np
import pandas as pd
from scipy.stats import norm
from sklearn.base import is_classifier, is_regressor
from .double_ml_data import DoubleMLBaseData, DoubleMLClusterData
from .double_ml_framework import DoubleMLFramework
from .utils._checks import _check_external_predictions, _check_sample_splitting
from .utils._estimation import _aggregate_coefs_and_ses, _rmse, _set_external_predictions, _var_est
from .utils._sensitivity import _compute_sensitivity_bias
from .utils.gain_statistics import gain_statistics
from .utils.resampling import DoubleMLClusterResampling, DoubleMLResampling
_implemented_data_backends = ["DoubleMLData", "DoubleMLClusterData"]
class DoubleML(ABC):
"""Double Machine Learning."""
def __init__(self, obj_dml_data, n_folds, n_rep, score, draw_sample_splitting):
# check and pick up obj_dml_data
if not isinstance(obj_dml_data, DoubleMLBaseData):
raise TypeError(
"The data must be of " + " or ".join(_implemented_data_backends) + " type. "
f"{str(obj_dml_data)} of type {str(type(obj_dml_data))} was passed."
)
self._is_cluster_data = False
if isinstance(obj_dml_data, DoubleMLClusterData):
if obj_dml_data.n_cluster_vars > 2:
raise NotImplementedError("Multi-way (n_ways > 2) clustering not yet implemented.")
self._is_cluster_data = True
self._dml_data = obj_dml_data
# initialize framework which is constructed after the fit method is called
self._framework = None
# initialize learners and parameters which are set model specific
self._learner = None
self._params = None
self._is_classifier = {}
# initialize predictions and target to None which are only stored if method fit is called with store_predictions=True
self._predictions = None
self._nuisance_targets = None
self._nuisance_loss = None
# initialize models to None which are only stored if method fit is called with store_models=True
self._models = None
# initialize sensitivity elements to None (only available if implemented for the class
self._sensitivity_implemented = False
self._sensitivity_elements = None
self._sensitivity_params = None
# initialize external predictions
self._external_predictions_implemented = False
# check resampling specifications
if not isinstance(n_folds, int):
raise TypeError(
f"The number of folds must be of int type. {str(n_folds)} of type {str(type(n_folds))} was passed."
)
if n_folds < 1:
raise ValueError(f"The number of folds must be positive. {str(n_folds)} was passed.")
if not isinstance(n_rep, int):
raise TypeError(
"The number of repetitions for the sample splitting must be of int type. "
f"{str(n_rep)} of type {str(type(n_rep))} was passed."
)
if n_rep < 1:
raise ValueError(f"The number of repetitions for the sample splitting must be positive. {str(n_rep)} was passed.")
if not isinstance(draw_sample_splitting, bool):
raise TypeError(f"draw_sample_splitting must be True or False. Got {str(draw_sample_splitting)}.")
# set resampling specifications
if self._is_cluster_data:
self._n_folds_per_cluster = n_folds
self._n_folds = n_folds**self._dml_data.n_cluster_vars
else:
self._n_folds = n_folds
self._n_rep = n_rep
self._score = score
# default is no stratification
self._strata = None
# perform sample splitting
self._smpls = None
self._smpls_cluster = None
if draw_sample_splitting:
self.draw_sample_splitting()
# initialize arrays according to obj_dml_data and the resampling settings
(
self._psi,
self._psi_deriv,
self._psi_elements,
self._var_scaling_factors,
self._coef,
self._se,
self._all_coef,
self._all_se,
) = self._initialize_arrays()
# initialize instance attributes which are later used for iterating
self._i_rep = None
self._i_treat = None
def __str__(self):
class_name = self.__class__.__name__
header = f"================== {class_name} Object ==================\n"
data_summary = self._dml_data._data_summary_str()
score_info = f"Score function: {str(self.score)}\n"
learner_info = ""
for key, value in self.learner.items():
learner_info += f"Learner {key}: {str(value)}\n"
if self.nuisance_loss is not None:
learner_info += "Out-of-sample Performance:\n"
is_classifier = [value for value in self._is_classifier.values()]
is_regressor = [not value for value in is_classifier]
if any(is_regressor):
learner_info += "Regression:\n"
for learner in [key for key, value in self._is_classifier.items() if value is False]:
learner_info += f"Learner {learner} RMSE: {self.nuisance_loss[learner]}\n"
if any(is_classifier):
learner_info += "Classification:\n"
for learner in [key for key, value in self._is_classifier.items() if value is True]:
learner_info += f"Learner {learner} Log Loss: {self.nuisance_loss[learner]}\n"
if self._is_cluster_data:
resampling_info = (
f"No. folds per cluster: {self._n_folds_per_cluster}\n"
f"No. folds: {self.n_folds}\n"
f"No. repeated sample splits: {self.n_rep}\n"
)
else:
resampling_info = f"No. folds: {self.n_folds}\nNo. repeated sample splits: {self.n_rep}\n"
fit_summary = str(self.summary)
res = (
header
+ "\n------------------ Data summary ------------------\n"
+ data_summary
+ "\n------------------ Score & algorithm ------------------\n"
+ score_info
+ "\n------------------ Machine learner ------------------\n"
+ learner_info
+ "\n------------------ Resampling ------------------\n"
+ resampling_info
+ "\n------------------ Fit summary ------------------\n"
+ fit_summary
)
return res
@property
def n_folds(self):
"""
Number of folds.
"""
return self._n_folds
@property
def n_rep(self):
"""
Number of repetitions for the sample splitting.
"""
return self._n_rep
@property
def n_rep_boot(self):
"""
The number of bootstrap replications.
"""
if self._framework is None:
n_rep_boot = None
else:
n_rep_boot = self._framework.n_rep_boot
return n_rep_boot
@property
def boot_method(self):
"""
The method to construct the bootstrap replications.
"""
if self._framework is None:
method = None
else:
method = self._framework.boot_method
return method
@property
def score(self):
"""
The score function.
"""
return self._score
@property
def framework(self):
"""
The corresponding :class:`doubleml.DoubleMLFramework` object.
"""
return self._framework
@property
def learner(self):
"""
The machine learners for the nuisance functions.
"""
return self._learner
@property
def learner_names(self):
"""
The names of the learners.
"""
return list(self._learner.keys())
@property
def params(self):
"""
The hyperparameters of the learners.
"""
return self._params
@property
def params_names(self):
"""
The names of the nuisance models with hyperparameters.
"""
return list(self._params.keys())
@property
def predictions(self):
"""
The predictions of the nuisance models in form of a dictinary.
Each key refers to a nuisance element with a array of values of shape ``(n_obs, n_rep, n_coefs)``.
"""
return self._predictions
@property
def nuisance_targets(self):
"""
The outcome of the nuisance models.
"""
return self._nuisance_targets
@property
def nuisance_loss(self):
"""
The losses of the nuisance models (root-mean-squared-errors or logloss).
"""
return self._nuisance_loss
@property
def models(self):
"""
The fitted nuisance models.
"""
return self._models
def get_params(self, learner):
"""
Get hyperparameters for the nuisance model of DoubleML models.
Parameters
----------
learner : str
The nuisance model / learner (see attribute ``params_names``).
Returns
-------
params : dict
Parameters for the nuisance model / learner.
"""
valid_learner = self.params_names
if (not isinstance(learner, str)) | (learner not in valid_learner):
raise ValueError(
"Invalid nuisance learner "
+ str(learner)
+ ". "
+ "Valid nuisance learner "
+ " or ".join(valid_learner)
+ "."
)
return self._params[learner]
# The private function _get_params delivers the single treatment, single (cross-fitting) sample subselection.
# The slicing is based on the two properties self._i_treat, the index of the treatment variable, and
# self._i_rep, the index of the cross-fitting sample.
def _get_params(self, learner):
return self._params[learner][self._dml_data.d_cols[self._i_treat]][self._i_rep]
@property
def smpls(self):
"""
The partition used for cross-fitting.
"""
if self._smpls is None:
err_msg = (
"Sample splitting not specified. Either draw samples via .draw_sample splitting() "
+ "or set external samples via .set_sample_splitting()."
)
raise ValueError(err_msg)
return self._smpls
@property
def smpls_cluster(self):
"""
The partition of clusters used for cross-fitting.
"""
return self._smpls_cluster
@property
def psi(self):
"""
Values of the score function after calling :meth:`fit`;
For models (e.g., PLR, IRM, PLIV, IIVM) with linear score (in the parameter)
:math:`\\psi(W; \\theta, \\eta) = \\psi_a(W; \\eta) \\theta + \\psi_b(W; \\eta)`.
The shape is ``(n_obs, n_rep, n_coefs)``.
"""
return self._psi
@property
def psi_deriv(self):
"""
Values of the derivative of the score function with respect to the parameter :math:`\\theta`
after calling :meth:`fit`;
For models (e.g., PLR, IRM, PLIV, IIVM) with linear score (in the parameter)
:math:`\\psi_a(W; \\eta)`.
The shape is ``(n_obs, n_rep, n_coefs)``.
"""
return self._psi_deriv
@property
def psi_elements(self):
"""
Values of the score function components after calling :meth:`fit`;
For models (e.g., PLR, IRM, PLIV, IIVM) with linear score (in the parameter) a dictionary with entries ``psi_a``
and ``psi_b`` for :math:`\\psi_a(W; \\eta)` and :math:`\\psi_b(W; \\eta)`.
"""
return self._psi_elements
@property
def sensitivity_elements(self):
"""
Values of the sensitivity components after calling :meth:`fit`;
If available (e.g., PLR, IRM) a dictionary with entries ``sigma2``, ``nu2``, ``psi_sigma2``, ``psi_nu2``
and ``riesz_rep``.
"""
return self._sensitivity_elements
@property
def sensitivity_params(self):
"""
Values of the sensitivity parameters after calling :meth:`sesitivity_analysis`;
If available (e.g., PLR, IRM) a dictionary with entries ``theta``, ``se``, ``ci``, ``rv``
and ``rva``.
"""
if self._framework is None:
sensitivity_params = None
else:
sensitivity_params = self._framework.sensitivity_params
return sensitivity_params
@property
def coef(self):
"""
Estimates for the causal parameter(s) after calling :meth:`fit`.
"""
return self._coef
@coef.setter
def coef(self, value):
self._coef = value
@property
def se(self):
"""
Standard errors for the causal parameter(s) after calling :meth:`fit`.
"""
return self._se
@se.setter
def se(self, value):
self._se = value
@property
def t_stat(self):
"""
t-statistics for the causal parameter(s) after calling :meth:`fit`.
"""
t_stat = self.coef / self.se
return t_stat
@property
def pval(self):
"""
p-values for the causal parameter(s) after calling :meth:`fit`.
"""
pval = 2 * norm.cdf(-np.abs(self.t_stat))
return pval
@property
def boot_t_stat(self):
"""
Bootstrapped t-statistics for the causal parameter(s) after calling :meth:`fit` and :meth:`bootstrap`.
"""
if self._framework is None:
boot_t_stat = None
else:
boot_t_stat = self._framework.boot_t_stat
return boot_t_stat
@property
def all_coef(self):
"""
Estimates of the causal parameter(s) for the ``n_rep`` different sample splits after calling :meth:`fit`.
"""
return self._all_coef
@property
def all_se(self):
"""
Standard errors of the causal parameter(s) for the ``n_rep`` different sample splits after calling :meth:`fit`.
"""
return self._all_se
@property
def summary(self):
"""
A summary for the estimated causal effect after calling :meth:`fit`.
"""
col_names = ["coef", "std err", "t", "P>|t|"]
if np.isnan(self.coef).all():
df_summary = pd.DataFrame(columns=col_names)
else:
summary_stats = np.transpose(np.vstack([self.coef, self.se, self.t_stat, self.pval]))
df_summary = pd.DataFrame(summary_stats, columns=col_names, index=self._dml_data.d_cols)
ci = self.confint()
df_summary = df_summary.join(ci)
return df_summary
# The private properties with __ always deliver the single treatment, single (cross-fitting) sample subselection.
# The slicing is based on the two properties self._i_treat, the index of the treatment variable, and
# self._i_rep, the index of the cross-fitting sample.
@property
def __smpls(self):
return self._smpls[self._i_rep]
@property
def __smpls_cluster(self):
return self._smpls_cluster[self._i_rep]
@property
def __psi(self):
return self._psi[:, self._i_rep, self._i_treat]
@property
def __psi_deriv(self):
return self._psi_deriv[:, self._i_rep, self._i_treat]
@property
def __all_se(self):
return self._all_se[self._i_treat, self._i_rep]
def fit(self, n_jobs_cv=None, store_predictions=True, external_predictions=None, store_models=False):
"""
Estimate DoubleML models.
Parameters
----------
n_jobs_cv : None or int
The number of CPUs to use to fit the learners. ``None`` means ``1``.
Default is ``None``.
store_predictions : bool
Indicates whether the predictions for the nuisance functions should be stored in ``predictions``.
Default is ``True``.
store_models : bool
Indicates whether the fitted models for the nuisance functions should be stored in ``models``. This allows
to analyze the fitted models or extract information like variable importance.
Default is ``False``.
external_predictions : None or dict
If `None` all models for the learners are fitted and evaluated. If a dictionary containing predictions
for a specific learner is supplied, the model will use the supplied nuisance predictions instead. Has to
be a nested dictionary where the keys refer to the treatment and the keys of the nested dictionarys refer to the
corresponding learners.
Default is `None`.
Returns
-------
self : object
"""
self._check_fit(n_jobs_cv, store_predictions, external_predictions, store_models)
self._initalize_fit(store_predictions, store_models)
for i_rep in range(self.n_rep):
self._i_rep = i_rep
for i_d in range(self._dml_data.n_treat):
self._i_treat = i_d
# this step could be skipped for the single treatment variable case
if self._dml_data.n_treat > 1:
self._dml_data.set_x_d(self._dml_data.d_cols[i_d])
# predictions have to be stored in loop for sensitivity analysis
nuisance_predictions = self._fit_nuisance_and_score_elements(
n_jobs_cv, store_predictions, external_predictions, store_models
)
self._solve_score_and_estimate_se()
# sensitivity elements can depend on the estimated parameter
self._fit_sensitivity_elements(nuisance_predictions)
# aggregated parameter estimates and standard errors from repeated cross-fitting
self.coef, self.se = _aggregate_coefs_and_ses(self._all_coef, self._all_se, self._var_scaling_factors)
# validate sensitivity elements (e.g., re-estimate nu2 if negative)
self._validate_sensitivity_elements()
# construct framework for inference
self._framework = self.construct_framework()
return self
def construct_framework(self):
"""
Construct a :class:`doubleml.DoubleMLFramework` object. Can be used to construct e.g. confidence intervals.
Parameters
----------
Returns
-------
doubleml_framework : doubleml.DoubleMLFramework
"""
# standardize the score function and reshape to (n_obs, n_coefs, n_rep)
scaled_psi = np.divide(self.psi, np.mean(self.psi_deriv, axis=0))
scaled_psi_reshape = np.transpose(scaled_psi, (0, 2, 1))
doubleml_dict = {
"thetas": self.coef,
"all_thetas": self.all_coef,
"ses": self.se,
"all_ses": self.all_se,
"var_scaling_factors": self._var_scaling_factors,
"scaled_psi": scaled_psi_reshape,
"is_cluster_data": self._is_cluster_data,
"treatment_names": self._dml_data.d_cols,
}
if self._sensitivity_implemented:
# reshape sensitivity elements to (1 or n_obs, n_coefs, n_rep)
sensitivity_dict = {
"sigma2": np.transpose(self.sensitivity_elements["sigma2"], (0, 2, 1)),
"nu2": np.transpose(self.sensitivity_elements["nu2"], (0, 2, 1)),
"psi_sigma2": np.transpose(self.sensitivity_elements["psi_sigma2"], (0, 2, 1)),
"psi_nu2": np.transpose(self.sensitivity_elements["psi_nu2"], (0, 2, 1)),
}
max_bias, psi_max_bias = _compute_sensitivity_bias(**sensitivity_dict)
doubleml_dict.update(
{
"sensitivity_elements": {
"max_bias": max_bias,
"psi_max_bias": psi_max_bias,
"sigma2": sensitivity_dict["sigma2"],
"nu2": sensitivity_dict["nu2"],
}
}
)
if self._is_cluster_data:
doubleml_dict.update(
{
"is_cluster_data": True,
"cluster_dict": {
"smpls": self._smpls,
"smpls_cluster": self._smpls_cluster,
"cluster_vars": self._dml_data.cluster_vars,
"n_folds_per_cluster": self._n_folds_per_cluster,
},
}
)
doubleml_framework = DoubleMLFramework(doubleml_dict)
return doubleml_framework
def bootstrap(self, method="normal", n_rep_boot=500):
"""
Multiplier bootstrap for DoubleML models.
Parameters
----------
method : str
A str (``'Bayes'``, ``'normal'`` or ``'wild'``) specifying the multiplier bootstrap method.
Default is ``'normal'``
n_rep_boot : int
The number of bootstrap replications.
Returns
-------
self : object
"""
if self._framework is None:
raise ValueError("Apply fit() before bootstrap().")
self._framework.bootstrap(method=method, n_rep_boot=n_rep_boot)
return self
def confint(self, joint=False, level=0.95):
"""
Confidence intervals for DoubleML models.
Parameters
----------
joint : bool
Indicates whether joint confidence intervals are computed.
Default is ``False``
level : float
The confidence level.
Default is ``0.95``.
Returns
-------
df_ci : pd.DataFrame
A data frame with the confidence interval(s).
"""
if self.framework is None:
raise ValueError("Apply fit() before confint().")
df_ci = self.framework.confint(joint=joint, level=level)
df_ci.set_index(pd.Index(self._dml_data.d_cols), inplace=True)
return df_ci
def p_adjust(self, method="romano-wolf"):
"""
Multiple testing adjustment for DoubleML models.
Parameters
----------
method : str
A str (``'romano-wolf''``, ``'bonferroni'``, ``'holm'``, etc) specifying the adjustment method.
In addition to ``'romano-wolf''``, all methods implemented in
:py:func:`statsmodels.stats.multitest.multipletests` can be applied.
Default is ``'romano-wolf'``.
Returns
-------
p_val : pd.DataFrame
A data frame with adjusted p-values.
"""
if self.framework is None:
raise ValueError("Apply fit() before p_adjust().")
p_val, _ = self.framework.p_adjust(method=method)
p_val.set_index(pd.Index(self._dml_data.d_cols), inplace=True)
return p_val
def tune(
self,
param_grids,
tune_on_folds=False,
scoring_methods=None, # if None the estimator's score method is used
n_folds_tune=5,
search_mode="grid_search",
n_iter_randomized_search=100,
n_jobs_cv=None,
set_as_params=True,
return_tune_res=False,
):
"""
Hyperparameter-tuning for DoubleML models.
The hyperparameter-tuning is performed using either an exhaustive search over specified parameter values
implemented in :class:`sklearn.model_selection.GridSearchCV` or via a randomized search implemented in
:class:`sklearn.model_selection.RandomizedSearchCV`.
Parameters
----------
param_grids : dict
A dict with a parameter grid for each nuisance model / learner (see attribute ``learner_names``).
tune_on_folds : bool
Indicates whether the tuning should be done fold-specific or globally.
Default is ``False``.
scoring_methods : None or dict
The scoring method used to evaluate the predictions. The scoring method must be set per nuisance model via
a dict (see attribute ``learner_names`` for the keys).
If None, the estimator’s score method is used.
Default is ``None``.
n_folds_tune : int
Number of folds used for tuning.
Default is ``5``.
search_mode : str
A str (``'grid_search'`` or ``'randomized_search'``) specifying whether hyperparameters are optimized via
:class:`sklearn.model_selection.GridSearchCV` or :class:`sklearn.model_selection.RandomizedSearchCV`.
Default is ``'grid_search'``.
n_iter_randomized_search : int
If ``search_mode == 'randomized_search'``. The number of parameter settings that are sampled.
Default is ``100``.
n_jobs_cv : None or int
The number of CPUs to use to tune the learners. ``None`` means ``1``.
Default is ``None``.
set_as_params : bool
Indicates whether the hyperparameters should be set in order to be used when :meth:`fit` is called.
Default is ``True``.
return_tune_res : bool
Indicates whether detailed tuning results should be returned.
Default is ``False``.
Returns
-------
self : object
Returned if ``return_tune_res`` is ``False``.
tune_res: list
A list containing detailed tuning results and the proposed hyperparameters.
Returned if ``return_tune_res`` is ``True``.
"""
if (not isinstance(param_grids, dict)) | (not all(k in param_grids for k in self.learner_names)):
raise ValueError(
"Invalid param_grids " + str(param_grids) + ". "
"param_grids must be a dictionary with keys " + " and ".join(self.learner_names) + "."
)
if scoring_methods is not None:
if (not isinstance(scoring_methods, dict)) | (not all(k in self.learner_names for k in scoring_methods)):
raise ValueError(
"Invalid scoring_methods "
+ str(scoring_methods)
+ ". "
+ "scoring_methods must be a dictionary. "
+ "Valid keys are "
+ " and ".join(self.learner_names)
+ "."
)
if not all(k in scoring_methods for k in self.learner_names):
# if there are learners for which no scoring_method was set, we fall back to None, i.e., default scoring
for learner in self.learner_names:
if learner not in scoring_methods:
scoring_methods[learner] = None
if not isinstance(tune_on_folds, bool):
raise TypeError(f"tune_on_folds must be True or False. Got {str(tune_on_folds)}.")
if not isinstance(n_folds_tune, int):
raise TypeError(
"The number of folds used for tuning must be of int type. "
f"{str(n_folds_tune)} of type {str(type(n_folds_tune))} was passed."
)
if n_folds_tune < 2:
raise ValueError(f"The number of folds used for tuning must be at least two. {str(n_folds_tune)} was passed.")
if (not isinstance(search_mode, str)) | (search_mode not in ["grid_search", "randomized_search"]):
raise ValueError(f'search_mode must be "grid_search" or "randomized_search". Got {str(search_mode)}.')
if not isinstance(n_iter_randomized_search, int):
raise TypeError(
"The number of parameter settings sampled for the randomized search must be of int type. "
f"{str(n_iter_randomized_search)} of type "
f"{str(type(n_iter_randomized_search))} was passed."
)
if n_iter_randomized_search < 2:
raise ValueError(
"The number of parameter settings sampled for the randomized search must be at least two. "
f"{str(n_iter_randomized_search)} was passed."
)
if n_jobs_cv is not None:
if not isinstance(n_jobs_cv, int):
raise TypeError(
"The number of CPUs used to fit the learners must be of int type. "
f"{str(n_jobs_cv)} of type {str(type(n_jobs_cv))} was passed."
)
if not isinstance(set_as_params, bool):
raise TypeError(f"set_as_params must be True or False. Got {str(set_as_params)}.")
if not isinstance(return_tune_res, bool):
raise TypeError(f"return_tune_res must be True or False. Got {str(return_tune_res)}.")
if tune_on_folds:
tuning_res = [[None] * self.n_rep] * self._dml_data.n_treat
else:
tuning_res = [None] * self._dml_data.n_treat
for i_d in range(self._dml_data.n_treat):
self._i_treat = i_d
# this step could be skipped for the single treatment variable case
if self._dml_data.n_treat > 1:
self._dml_data.set_x_d(self._dml_data.d_cols[i_d])
if tune_on_folds:
nuisance_params = list()
for i_rep in range(self.n_rep):
self._i_rep = i_rep
# tune hyperparameters
res = self._nuisance_tuning(
self.__smpls,
param_grids,
scoring_methods,
n_folds_tune,
n_jobs_cv,
search_mode,
n_iter_randomized_search,
)
tuning_res[i_rep][i_d] = res
nuisance_params.append(res["params"])
if set_as_params:
for nuisance_model in nuisance_params[0].keys():
params = [x[nuisance_model] for x in nuisance_params]
self.set_ml_nuisance_params(nuisance_model, self._dml_data.d_cols[i_d], params)
else:
smpls = [(np.arange(self._dml_data.n_obs), np.arange(self._dml_data.n_obs))]
# tune hyperparameters
res = self._nuisance_tuning(
smpls, param_grids, scoring_methods, n_folds_tune, n_jobs_cv, search_mode, n_iter_randomized_search
)
tuning_res[i_d] = res
if set_as_params:
for nuisance_model in res["params"].keys():
params = res["params"][nuisance_model]
self.set_ml_nuisance_params(nuisance_model, self._dml_data.d_cols[i_d], params[0])
if return_tune_res:
return tuning_res
else:
return self
def set_ml_nuisance_params(self, learner, treat_var, params):
"""
Set hyperparameters for the nuisance models of DoubleML models.
Parameters
----------
learner : str
The nuisance model / learner (see attribute ``params_names``).
treat_var : str
The treatment variable (hyperparameters can be set treatment-variable specific).
params : dict or list
A dict with estimator parameters (used for all folds) or a nested list with fold specific parameters. The
outer list needs to be of length ``n_rep`` and the inner list of length ``n_folds``.
Returns
-------
self : object
"""
valid_learner = self.params_names
if learner not in valid_learner:
raise ValueError(
"Invalid nuisance learner " + learner + ". " + "Valid nuisance learner " + " or ".join(valid_learner) + "."
)
if treat_var not in self._dml_data.d_cols:
raise ValueError(
"Invalid treatment variable "
+ treat_var
+ ". "
+ "Valid treatment variable "
+ " or ".join(self._dml_data.d_cols)
+ "."
)
if params is None:
all_params = [None] * self.n_rep
elif isinstance(params, dict):
all_params = [[params] * self.n_folds] * self.n_rep
else:
# ToDo: Add meaningful error message for asserts and corresponding uni tests
assert len(params) == self.n_rep
assert np.all(np.array([len(x) for x in params]) == self.n_folds)
all_params = params
self._params[learner][treat_var] = all_params
return self
@abstractmethod
def _initialize_ml_nuisance_params(self):
pass
@abstractmethod
def _nuisance_est(self, smpls, n_jobs_cv, return_models, external_predictions):
pass
@abstractmethod
def _nuisance_tuning(
self, smpls, param_grids, scoring_methods, n_folds_tune, n_jobs_cv, search_mode, n_iter_randomized_search
):
pass
@staticmethod
def _check_learner(learner, learner_name, regressor, classifier):
err_msg_prefix = f"Invalid learner provided for {learner_name}: "
warn_msg_prefix = f"Learner provided for {learner_name} is probably invalid: "
if isinstance(learner, type):
raise TypeError(err_msg_prefix + "provide an instance of a learner instead of a class.")
if not hasattr(learner, "fit"):
raise TypeError(err_msg_prefix + f"{str(learner)} has no method .fit().")
if not hasattr(learner, "set_params"):
raise TypeError(err_msg_prefix + f"{str(learner)} has no method .set_params().")
if not hasattr(learner, "get_params"):
raise TypeError(err_msg_prefix + f"{str(learner)} has no method .get_params().")
if regressor & classifier:
if is_classifier(learner):
learner_is_classifier = True
elif is_regressor(learner):
learner_is_classifier = False
else:
warnings.warn(
warn_msg_prefix
+ f"{str(learner)} is (probably) neither a regressor nor a classifier. "
+ "Method predict is used for prediction."
)
learner_is_classifier = False
elif classifier:
if not is_classifier(learner):
warnings.warn(warn_msg_prefix + f"{str(learner)} is (probably) no classifier.")
learner_is_classifier = True
else:
assert regressor # classifier, regressor or both must be True
if not is_regressor(learner):
warnings.warn(warn_msg_prefix + f"{str(learner)} is (probably) no regressor.")
learner_is_classifier = False
# check existence of the prediction method
if learner_is_classifier:
if not hasattr(learner, "predict_proba"):
raise TypeError(err_msg_prefix + f"{str(learner)} has no method .predict_proba().")
else:
if not hasattr(learner, "predict"):
raise TypeError(err_msg_prefix + f"{str(learner)} has no method .predict().")
return learner_is_classifier
def _check_fit(self, n_jobs_cv, store_predictions, external_predictions, store_models):
if n_jobs_cv is not None:
if not isinstance(n_jobs_cv, int):
raise TypeError(
"The number of CPUs used to fit the learners must be of int type. "
f"{str(n_jobs_cv)} of type {str(type(n_jobs_cv))} was passed."
)
if not isinstance(store_predictions, bool):
raise TypeError(f"store_predictions must be True or False. Got {str(store_predictions)}.")
if not isinstance(store_models, bool):
raise TypeError(f"store_models must be True or False. Got {str(store_models)}.")
# check if external predictions are implemented
if self._external_predictions_implemented:
_check_external_predictions(
external_predictions=external_predictions,
valid_treatments=self._dml_data.d_cols,
valid_learners=self.params_names,
n_obs=self._dml_data.n_obs,
n_rep=self.n_rep,
)
elif not self._external_predictions_implemented and external_predictions is not None:
raise NotImplementedError(f"External predictions not implemented for {self.__class__.__name__}.")
def _initalize_fit(self, store_predictions, store_models):