API Documentation
DRLearner
DRLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
adaptive_clipping: bool = False,
)
Bases: _ConditionalAverageOutcomeMetaLearner
DR-Learner for CATE estimation as described by Kennedy (2020).
Importantly, the current DR-Learner implementation only supports:
- binary classes in case of a classification outcome
The DR-Learner contains the following nuisance models:
- a
"propensity_model"estimating \(\Pr[W=k|X]\) - one
"variant_outcome_model"for each treatment variant (including control) estimating \(\mathbb{E}[Y|X, W=k]\)
and one treatment model for each treatment variant (without control):
"treatment_model"which estimates \(\mathbb{E}[Y(k) - Y(0) | X]\)
If adaptive_clipping is set to True, then the pseudo outcomes are computed using
adaptive propensity clipping described in section 4.1, equation DR-Switch of
Mahajan et al. (2024).
Source code in metalearners/drlearner.py
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 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
average_treatment_effect
average_treatment_effect(
X: Matrix, y: Vector, w: Vector, is_oos: bool
) -> tuple[np.ndarray, np.ndarray]
Compute Average Treatment Effect (ATE) for each treatment variant using the
Augmented IPW estimator (Robins et al 1994). Does not require fitting a second-
stage treatment model: it uses the pseudo-outcome alone and computes the point
estimate and standard error. Can be used following the
fit_all_nuisance method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Matrix
|
Covariate matrix |
required |
y
|
Vector
|
Outcome vector |
required |
w
|
Vector
|
Treatment vector |
required |
is_oos
|
bool
|
indicator whether data is out of sample |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Treatment effect for each treatment variant. |
ndarray
|
np.ndarray: Standard error for each treatment variant. |
Source code in metalearners/drlearner.py
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 | |
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/drlearner.py
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 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/drlearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/drlearner.py
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 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/drlearner.py
76 77 78 79 80 81 82 83 84 85 86 87 | |
predict
predict(
X, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/drlearner.py
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 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/metalearner.py
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/drlearner.py
89 90 91 92 93 94 95 96 | |
RLearner
RLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: MetaLearner
R-Learner for CATE estimation as described by Nie et al. (2017).
Importantly, the current R-Learner implementation only supports:
- binary classes in case of a classification outcome
The R-Learner contains two nuisance models
- a
"propensity_model"estimating \(\Pr[W=k|X]\) - an
"outcome_model"estimating \(\mathbb{E}[Y|X]\)
and one treatment model per treatment variant which isn’t control
"treatment_model"which estimates \(\mathbb{E}[Y(k) - Y(0) | X]\)
The treatment_model_factory provided needs to support the argument
sample_weight in its fit method.
Source code in metalearners/metalearner.py
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 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
In the RLearner case, the "treatment_model" is always evaluated with the
r_loss besides the scorers in
scoring["treatment_model"], which should support passing the sample_weight
keyword argument.
Source code in metalearners/rlearner.py
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 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/rlearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
epsilon: float = _EPSILON,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/rlearner.py
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 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/rlearner.py
137 138 139 140 141 142 143 144 145 146 147 148 | |
predict
predict(
X, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/rlearner.py
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 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
The conditional average outcomes are estimated as follows:
- \(Y_i(0) = \hat{\mu}(X_i) - \sum_{k=1}^{K} \hat{e}_k(X_i) \hat{\tau_k}(X_i)\)
- \(Y_i(k) = Y_i(0) + \hat{\tau_k}(X_i)\) for \(k \in \{1, \dots, K\}\)
where \(K\) is the number of treatment variants.
Source code in metalearners/rlearner.py
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 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/rlearner.py
150 151 152 153 154 155 156 157 | |
SLearner
SLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: MetaLearner
S-Learner for CATE estimation as described by Kuenzel et al (2019).
Source code in metalearners/slearner.py
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 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/slearner.py
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 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/slearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/slearner.py
323 324 325 326 327 328 329 330 331 332 333 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/slearner.py
228 229 230 231 232 233 234 235 | |
predict
predict(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/slearner.py
335 336 337 338 339 340 341 342 343 344 345 346 347 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/slearner.py
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/slearner.py
237 238 239 | |
TLearner
TLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: _ConditionalAverageOutcomeMetaLearner
T-Learner for CATE estimation as described by Kuenzel et al (2019).
Source code in metalearners/metalearner.py
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/tlearner.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/tlearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/tlearner.py
106 107 108 109 110 111 112 113 114 115 116 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/tlearner.py
40 41 42 43 44 45 46 47 | |
predict
predict(
X, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/tlearner.py
118 119 120 121 122 123 124 125 126 127 128 129 130 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/metalearner.py
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/tlearner.py
49 50 51 | |
XLearner
XLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: _ConditionalAverageOutcomeMetaLearner
X-Learner for CATE estimation as described by Kuenzel et al (2019).
Importantly, the current X-Learner implementation only supports:
- binary classes in case of a classification outcome
Source code in metalearners/metalearner.py
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/xlearner.py
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 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/xlearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/xlearner.py
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 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/xlearner.py
52 53 54 55 56 57 58 59 60 61 62 63 | |
predict
predict(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/xlearner.py
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 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/metalearner.py
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/xlearner.py
65 66 67 68 69 70 71 72 73 74 75 76 | |
cross_fit_estimator
CrossFitEstimator
dataclass
CrossFitEstimator(
n_folds: int,
estimator_factory: type[_ScikitModel],
estimator_params: dict = dict(),
enable_overall: bool = True,
random_state: int | None = None,
)
Helper class for cross-fitting estimators on data.
Conceptually, it allows for fitting n_folds or n_folds + 1 models on
n_folds folds of the data.
estimator_factory is a class implementing an estimator with a scikit-learn
interface. Instantiation parameters can be passed to estimator_params.
An example argument for estimator_factory would be lightgbm.LGBMRegressor.
Importantly, the CrossFitEstimator can handle in-sample and out-of-sample
(‘oos’) data for prediction. When doing in-sample prediction the single model will
be used in which the respective data point has not been part of the training set.
When doing oos prediction, different options exist. These options either rely on
combining the n_folds models or using a model trained on all of the data
(enable_overall).
n_folds can be set to 1 if the user desires to deactivate cross-fitting. In
that case, the CrossFitEstimator would only fit one overall model which would be
the one used for either in sample or out of sample predictions. Note that this is
not recommended since it can lead to data leakage when doing in-sample predictions.
clone
clone() -> CrossFitEstimator
Construct a new unfitted CrossFitEstimator with the same init parameters.
Source code in metalearners/cross_fit_estimator.py
134 135 136 137 138 139 140 141 142 | |
fit
fit(
X: Matrix,
y: Vector | Matrix,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the underlying estimators.
One estimator is trained per n_folds.
If enable_overall is set, an additional estimator is trained on all data.
n_jobs_cross_fitting can be used to specify the number of jobs for cross-fitting.
For more information see the sklearn glossary.
cv can optionally be passed. If passed, it is expected to be a list of
(train_indices, test_indices) tuples indicating how to split the data at hand
into train and test/estimation sets for different folds.
Source code in metalearners/cross_fit_estimator.py
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 | |
predict
predict(
X: Matrix,
is_oos: bool,
oos_method: OosMethod | None = None,
**kwargs,
) -> np.ndarray
Predict from X.
If is_oos, the oos_method will be used to generate predictions
on ‘out of sample’ data. ‘Out of sample’ refers to this data not having been
used in the fit method. The oos_method 'overall' can only be used
if the CrossFitEstimator has been initialized with
enable_overall=True.
Source code in metalearners/cross_fit_estimator.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
predict_proba
predict_proba(
X: Matrix,
is_oos: bool,
oos_method: OosMethod | None = None,
) -> np.ndarray
Predict probability from X.
If is_oos, the oos_method will be used to generate predictions
on ‘out of sample’ data. ‘Out of sample’ refers to this data not having been
used in the fit method. The oos_method 'overall' can only be used
if the CrossFitEstimator has been initialized with
enable_overall=True.
Source code in metalearners/cross_fit_estimator.py
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
score
score(
X: Matrix,
y: Vector,
is_oos: bool,
oos_method: OosMethod | None = None,
sample_weight: Vector | None = None,
) -> float
Return the coefficient of determination of the prediction if the estimator is a regressor or the mean accuracy if it is a classifier.
Source code in metalearners/cross_fit_estimator.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | |
data_generation
compute_experiment_outputs
compute_experiment_outputs(
mu: ndarray,
treatment: Vector,
sigma_y: float = 1,
sigma_tau: float = 0.5,
n_variants: int | None = None,
is_classification: bool = False,
positive_proportion: float = 0.5,
return_probability_cate: bool = False,
rng: Generator | None = None,
) -> tuple[np.ndarray, np.ndarray]
Compute the experiment’s observed outcomes y and the true CATE.
This function generates experiment outputs and the true CATE values based on the
given potential outcomes function and treatments. The treatment effect for each
observation is computed as the difference in potential outcomes. Normally
distributed noise is added to the response variable \(Y_i(0)\) with standard
deviation sigma_y and to each corresponding treatment effect to simulate
real-world variance with standard deviation sigma_tau.
treatment must be a vector representing the treatment group assignment for each
observation. Each element of the vector is an integer representing a treatment variant
starting at 0.
mu must be a matrix of size (n_obs, n_variants) containing the potential
outcomes for each observation and treatment variant without added noise.
n_variants can be passed to specify the number of treatment variants. If None,
it is inferred from the maximum value in the ‘treatment’ vector plus one.
is_classification determines if the problem to be simulated is a classification problem.
If True, the function simulates a classification problem where the response variable is binary
and the proportion of positive outputs is controlled by the positive_proportion parameter.
It is important to notice that the potential outputs are passed through a sigmoid function and
therefore the domain of them can be \(\mathbb{R}\). Classification problems are
only implemented for binary treatments.
In the case of a classification problem return_probability_cate specifies if the
outputted CATE is the difference in probabilities between treating and not treating or
if it samples from a Bernoulli distribution and the difference in samples is returned.
The function returns a tuple containing the following elements:
-
y: numpy array of the experiment’s observed outcomes (response variable) after noise addition. -
true_cate: numpy array of the true CATE without any added noise.
Source code in metalearners/data_generation.py
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 | |
generate_categoricals
generate_categoricals(
n_obs: int,
n_features: int,
n_categories: int | ndarray | None = None,
n_uniform: int | None = None,
p_binomial: float = 0.5,
use_strings: bool = False,
rng: Generator | None = None,
) -> tuple[np.ndarray, np.ndarray]
Generate a dataset of categorical features.
Generates a dataset of n_obs observations and n_features categorical
features. The first n_uniform features are sampled uniformly across their
categories and the rest are sampled from a binomial distribution with parameters
\(n = c_i\) and \(p = p\_binomial\) where \(c_i\) is the number of
categories of feature \(i\).
n_categories is the number of categories of the features, it can either be an int
which is used for all the features or an array of length n_features. If None,
the number of categories for each feature is sampled from
\(c_i \sim \mathcal{U}\{2,3,\dots,10\}\).
In case n_uniform is None, all features are sampled uniformly.
use_strings can be set to True if the wanted represantion of the variables
are strings. If set to False it will return an array with dtype np.int64.
The function returns a np.ndarray with the sampled dataset and a np.ndarray
with the number of categories for each feature.
Source code in metalearners/data_generation.py
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 | |
generate_covariates
generate_covariates(
n_obs: int,
n_features: int,
n_categoricals: int = 0,
format: Literal["pandas", "numpy"] = "pandas",
mu: float | ndarray | None = None,
wishart_scale: float = 1,
n_categories: int | ndarray | None = None,
n_uniform: int | None = None,
p_binomial: float = 0.5,
use_strings: bool = False,
rng: Generator | None = None,
) -> tuple[Matrix, list[int], np.ndarray]
Generates a dataset of covariates with both numerical and categorical features.
Dataset is composed of n_obs observations and n_features features, with the
first n_features - n_categoricals being numerical and the rest being categorical.
Numerical features are generated using the function
generate_numericals and categorical features are
generated using the function generate_categoricals.
By default, the generated dataset is returned as a Pandas DataFrame where categorical
features are converted to pandas’ Categorical
type. Optionally, the dataset can be returned as a numpy array with dtype float64
with format = "numpy". If generating categorical variables, working with pandas
DataFrames is preferred as they have support for category dtype.
For mu and wishart_scale see the docstring for
generate_numericals
For n_categories, n_uniform, p_binomial and use_strings
see the docstring for generate_categoricals.
use_strings can only be set to True when using format = "pandas".
The function returns a tuple of three elements. The first element is the dataset
generated (either a numpy array or a pandas DataFrame depending on format). The
second element is a list of indices indicating the columns of categorical features
in the dataset. The third element is a np.ndarray with the number of categories
for each feature.
Source code in metalearners/data_generation.py
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 | |
generate_numericals
generate_numericals(
n_obs: int,
n_features: int,
mu: float | ndarray | None = None,
wishart_scale: float = 1,
rng: Generator | None = None,
) -> np.ndarray
Generate a dataset of numerical features.
Generates a dataset of n_obs observations and n_features numerical features.
These are sampled from \(\mathcal{N}(\mu, \Sigma)\) where
\(\mu \sim \mathcal{U}[-5,5]\) unless specified in mu and
\(\Sigma \sim \mathcal{W}(d, \sigma_w I_d)\) where \(W\) is the Wishart
distribution and \(d\) the number of features.
mu can be either a float or an array of length n_features.
wishart_scale should be \(\geq 0\) , in case it is 0 then \(\Sigma = I_d\).
Source code in metalearners/data_generation.py
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 | |
generate_treatment
generate_treatment(
propensity_scores: ndarray, rng: Generator | None = None
) -> np.ndarray
Generates a treatment assignment based on the provided propensity scores.
The function first determines the number of treatment variants based on the shape of the input propensity scores. If the propensity score array has a single dimension or only one column in the second dimension, there are two treatment variants (treated vs not-treated), and the value is interpreted as the treatment probability. Otherwise, the second dimension of the propensity scores array indicates the number of treatment variants.
Each observation is assigned to a treatment group by drawing from a categorical distribution where the probability of each treatment group is given by the propensity scores.
propensity_scores should be of size (n_obs,) or (n_obs, n_variants),
where n_obs is the number of observations and n_variants is the number of
treatment variants.
The function return an array of shape (n_obs,) where each element indicates the
treatment variant received.
Source code in metalearners/data_generation.py
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 | |
insert_missing
insert_missing(
X: Matrix,
missing_probability: float = 0.1,
rng: Generator | None = None,
) -> Matrix
Inserts missing values into the dataset.
Each element of the dataset has a missing_probability chance of being replaced
with a NaN, thus simulating a dataset with missing values.
The function returns a copy of the original dataset, but with some elements replaced by NaNs.
Source code in metalearners/data_generation.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
drlearner
DRLearner
DRLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
adaptive_clipping: bool = False,
)
Bases: _ConditionalAverageOutcomeMetaLearner
DR-Learner for CATE estimation as described by Kennedy (2020).
Importantly, the current DR-Learner implementation only supports:
- binary classes in case of a classification outcome
The DR-Learner contains the following nuisance models:
- a
"propensity_model"estimating \(\Pr[W=k|X]\) - one
"variant_outcome_model"for each treatment variant (including control) estimating \(\mathbb{E}[Y|X, W=k]\)
and one treatment model for each treatment variant (without control):
"treatment_model"which estimates \(\mathbb{E}[Y(k) - Y(0) | X]\)
If adaptive_clipping is set to True, then the pseudo outcomes are computed using
adaptive propensity clipping described in section 4.1, equation DR-Switch of
Mahajan et al. (2024).
Source code in metalearners/drlearner.py
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 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
average_treatment_effect
average_treatment_effect(
X: Matrix, y: Vector, w: Vector, is_oos: bool
) -> tuple[np.ndarray, np.ndarray]
Compute Average Treatment Effect (ATE) for each treatment variant using the
Augmented IPW estimator (Robins et al 1994). Does not require fitting a second-
stage treatment model: it uses the pseudo-outcome alone and computes the point
estimate and standard error. Can be used following the
fit_all_nuisance method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Matrix
|
Covariate matrix |
required |
y
|
Vector
|
Outcome vector |
required |
w
|
Vector
|
Treatment vector |
required |
is_oos
|
bool
|
indicator whether data is out of sample |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Treatment effect for each treatment variant. |
ndarray
|
np.ndarray: Standard error for each treatment variant. |
Source code in metalearners/drlearner.py
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 | |
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/drlearner.py
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 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/drlearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/drlearner.py
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 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/drlearner.py
76 77 78 79 80 81 82 83 84 85 86 87 | |
predict
predict(
X, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/drlearner.py
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 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/metalearner.py
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/drlearner.py
89 90 91 92 93 94 95 96 | |
explainer
Explainer
Explainer(cate_models: list[_ScikitModel])
Responsible class for managing all functions related to feature explanation and interpretation.
The cate_models parameter should be a list of length \(n_{variants} -1\) containing
a model for each treatment variant which estimates \(\tau_k\). The models should not be a
CrossFitEstimator rather just a plain sklearn
BaseEstimator. A suggested option in the case of a CrossFitEstimator
would be to use their _overall_estimator. These models should already be fitted
on the data.
Source code in metalearners/explainer.py
53 54 55 56 57 58 | |
feature_importances
feature_importances(
normalize: bool = False,
feature_names: Collection[str] | None = None,
sort_values: bool = False,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature key.
Source code in metalearners/explainer.py
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 | |
from_estimates
classmethod
from_estimates(
X: Matrix,
cate_estimates: ndarray,
cate_model_factory: type[_ScikitModel],
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer object from CATE estimates.
This function will fit a model for each treatment variant with X as its input
and the corresponding CATE estimates as its output.
The cate_estimates should be the raw outcome of a MetaLearner with 3 dimensions
and should not be simplified.
Source code in metalearners/explainer.py
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 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
Source code in metalearners/explainer.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
grid_search
GSResult
dataclass
GSResult(
metalearner: MetaLearner,
train_scores: dict,
test_scores: dict | None,
fit_time: float,
score_time: float,
)
Result from a single grid search evaluation.
MetaLearnerGridSearch
MetaLearnerGridSearch(
metalearner_factory: type[MetaLearner],
metalearner_params: Mapping[str, Any],
base_learner_grid: Mapping[
str, Sequence[type[_ScikitModel]]
],
param_grid: Mapping[
str, Mapping[str, Mapping[str, Sequence]]
],
scoring: Scoring | None = None,
n_jobs: int | None = None,
random_state: int | None = None,
verbose: int = 0,
store_raw_results: bool = True,
store_results: bool = True,
)
Exhaustive search over specified parameter values for a MetaLearner.
metalearner_params should contain the necessary params for the MetaLearner initialization
such as n_variants and is_classification. If one wants to pass optional parameters
to the MetaLearner initialization, such as n_folds or feature_set, this should
be done by this way, too.
Importantly, random_state must be passed through the random_state parameter
and not through metalearner_params.
base_learner_grid keys should be the names of the needed base models contained in the
MetaLearner defined by metalearner_factory, for
information about this names check
MetaLearner.nuisance_model_specifications and
MetaLearner.treatment_model_specifications. The
values should be sequences of model factories.
If base models are meant to be reused, they should be passed through metalearner_params
and the corresponding keys should not be passed to base_learner_grid.
param_grid should contain the parameters grid for each type of model used by the
base learners defined in base_learner_grid. The keys should be strings with the
model class name. An example for optimizing over the :class:metalearners.DRLearner
would be:
base_learner_grid = {
"propensity_model": (LGBMClassifier, LogisticRegression),
"variant_outcome_model": (LGBMRegressor, LinearRegression),
"treatment_model": (LGBMRegressor)
}
param_grid = {
"propensity_model": {
"LGBMClassifier": {"n_estimators": [1, 2, 3], "verbose": [-1]}
},
"variant_outcome_model": {
"LGBMRegressor": {"n_estimators": [1, 2], "verbose": [-1]},
},
"treatment_model": {
"LGBMRegressor": {"n_estimators": [5, 10], "verbose": [-1]},
},
}
If some model is not present in param_grid, the default parameters will be used.
For information on how to define scoring see MetaLearner.evaluate.
verbose will be passed to joblib.Parallel.
store_raw_results and store_results define which and how the results are saved
after calling MetaLearnerGridSearch.fit depending on
their values:
- Both are
True(default):raw_results_will be a list ofGSResultwith all the results andresults_will be a DataFrame with the processed results. store_raw_results=Trueandstore_results=False:raw_results_will be a list ofGSResultwith all the results andresultswill beNone.store_raw_results=Falseandstore_results=True:raw_results_will beNoneandresults_will be a DataFrame with the processed results.- Both are
False:raw_results_will be a generator which yields aGSResultfor each configuration andresultswill be None. This configuration can be useful in the case the grid search is big and you do not want to store all MetaLearners objects rather evaluate them after fitting each one and just store one.
grid_size_ will contain the number of hyperparameter combinations after fitting.
This attribute may be useful in the case store_raw_results = False and store_results = False.
In that case, the generator object returned in raw_results_ doesn’t trigger the fitting
of individual metalearners until explicitly requested, e.g. in a loop. This attribute
can be use to track the progress, for instance, by creating a progress bar or a similar utility.
For an illustration see our example on Tuning hyperparameters of a MetaLearner with MetaLearnerGridSearch.
Source code in metalearners/grid_search.py
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 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
X_test: Matrix | None = None,
y_test: Vector | None = None,
w_test: Vector | None = None,
oos_method: OosMethod = OVERALL,
**kwargs,
)
Run fit with all sets of parameters.
X_test, y_test and w_test are optional, in case they are passed all the
fitted metalearners will be evaluated on it.
kwargs will be passed through to the MetaLearner.fit
call of each individual MetaLearner.
Source code in metalearners/grid_search.py
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 | |
metalearner
MetaLearner
MetaLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: ABC
MetaLearner abstract class. All metalearner implementations should inherit from it.
All of
nuisance_model_factorytreatment_model_factorynuisance_model_paramstreatment_model_paramsfeature_set
can either
- contain a single value, such that the value will be used for all relevant models of the respective MetaLearner or
- a dictionary mapping from the relevant models (
model_kind, astr) to the respective value; at least all relevant models need to be present, more are allowed and ignored
The possible values for defining feature_set (either one single value for all
the models or the values inside the dictionary specifying for each model) can be:
None: All columns will be used.- A list of strings or integers indicating which columns to use.
[]meaning that no present column should be used for that model and the input of the model should be a vector of 1s.
To reuse already fitted models fitted_nuisance_models and fitted_propensity_model
should be used. The models should be fitted on the same data the MetaLearner is going
to call fit with. For an illustration, see our example on reusing models.
Source code in metalearners/metalearner.py
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 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
abstractmethod
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/metalearner.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
abstractmethod
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/metalearner.py
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 | |
fit_all_treatment
abstractmethod
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/metalearner.py
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
abstractmethod
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/metalearner.py
287 288 289 290 291 | |
predict
abstractmethod
predict(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/metalearner.py
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 | |
predict_conditional_average_outcomes
abstractmethod
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/metalearner.py
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
abstractmethod
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/metalearner.py
293 294 295 296 297 | |
outcome_functions
constant_treatment_effect
constant_treatment_effect(
dim: int,
tau: float | ndarray,
ulow: float = 0,
uhigh: float = 1,
rng: Generator | None = None,
) -> Callable
Generate a potential outcomes function with constant treatment effect.
where :math:x_i is a vector of features, :math:\tau a vector of treatment effects,
:math:w_i the treatment indicator, :math:n_v the number of variants and
.. math:: \beta_{control} \sim \mathcal{U}[u_l, u_h]
dim indicates the dimension of :math:\beta and therefore it should be the
number of numerical features plus the number of categories in all of the categorical
features.
tau expects to be of size :math:n_v-1.
Source code in metalearners/outcome_functions.py
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 | |
linear_treatment_effect
linear_treatment_effect(
dim: int,
n_variants: int = 2,
ulow: float = 0,
uhigh: float = 1,
rng: Generator | None = None,
) -> Callable
Generate a potential outcomes function with linear treatment effect.
.. math:: f(x_i, w_i) = x_i’ \beta_{control} + \sum_{k=1}^{n_v-1} \mathcal{I}({w_i = k}) \cdot x_i’ \beta^{(k)}
where :math:x_i is a vector of features, :math:w_i the treatment indicator, and
.. math:: \beta_{control} \sim \mathcal{U}[u_l, u_h] \beta_{(k)} \sim \mathcal{U}[u_l, u_h]
dim indicates the dimension of :math:\beta_{control} and :math:\beta_{(k)}
therefore it should be the number of numerical features plus the number of categories
in all of the categorical features.
Source code in metalearners/outcome_functions.py
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 | |
no_treatment_effect
no_treatment_effect(
dim: int,
n_variants: int = 2,
ulow: float = 0,
uhigh: float = 1,
rng: Generator | None = None,
) -> Callable
Generate a potential outcomes function with no treatment effect.
.. math:: f(x_i, w_i) = x_i’ \beta
where :math:x_i is a vector of features and
.. math:: \beta \sim \mathcal{U}[u_l, u_h]
dim indicates the dimension of :math:\beta and therefore the number of
numerical features plus the number of categories in all of the categorical features.
Source code in metalearners/outcome_functions.py
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 | |
rlearner
RLearner
RLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: MetaLearner
R-Learner for CATE estimation as described by Nie et al. (2017).
Importantly, the current R-Learner implementation only supports:
- binary classes in case of a classification outcome
The R-Learner contains two nuisance models
- a
"propensity_model"estimating \(\Pr[W=k|X]\) - an
"outcome_model"estimating \(\mathbb{E}[Y|X]\)
and one treatment model per treatment variant which isn’t control
"treatment_model"which estimates \(\mathbb{E}[Y(k) - Y(0) | X]\)
The treatment_model_factory provided needs to support the argument
sample_weight in its fit method.
Source code in metalearners/metalearner.py
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 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
In the RLearner case, the "treatment_model" is always evaluated with the
r_loss besides the scorers in
scoring["treatment_model"], which should support passing the sample_weight
keyword argument.
Source code in metalearners/rlearner.py
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 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/rlearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
epsilon: float = _EPSILON,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/rlearner.py
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 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/rlearner.py
137 138 139 140 141 142 143 144 145 146 147 148 | |
predict
predict(
X, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/rlearner.py
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 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
The conditional average outcomes are estimated as follows:
- \(Y_i(0) = \hat{\mu}(X_i) - \sum_{k=1}^{K} \hat{e}_k(X_i) \hat{\tau_k}(X_i)\)
- \(Y_i(k) = Y_i(0) + \hat{\tau_k}(X_i)\) for \(k \in \{1, \dots, K\}\)
where \(K\) is the number of treatment variants.
Source code in metalearners/rlearner.py
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 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/rlearner.py
150 151 152 153 154 155 156 157 | |
r_loss
r_loss(
cate_estimates: Vector,
outcome_estimates: Vector,
propensity_scores: Vector,
outcomes: Vector,
treatments: Vector,
) -> float
Compute the square-root of the R-loss as introduced by Nie et al.
This function computes:
The R-Learner proposed in Nie et al. (2017) relies on a loss function which can be used in combination with empirical risk minimization to learn a CATE model.
Independently of the R-Learner, one can use the R-loss for evaluating CATE estimates in general.
Source code in metalearners/rlearner.py
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 | |
slearner
SLearner
SLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: MetaLearner
S-Learner for CATE estimation as described by Kuenzel et al (2019).
Source code in metalearners/slearner.py
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 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/slearner.py
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 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/slearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/slearner.py
323 324 325 326 327 328 329 330 331 332 333 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/slearner.py
228 229 230 231 232 233 234 235 | |
predict
predict(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/slearner.py
335 336 337 338 339 340 341 342 343 344 345 346 347 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/slearner.py
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/slearner.py
237 238 239 | |
tlearner
TLearner
TLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: _ConditionalAverageOutcomeMetaLearner
T-Learner for CATE estimation as described by Kuenzel et al (2019).
Source code in metalearners/metalearner.py
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/tlearner.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/tlearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/tlearner.py
106 107 108 109 110 111 112 113 114 115 116 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/tlearner.py
40 41 42 43 44 45 46 47 | |
predict
predict(
X, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/tlearner.py
118 119 120 121 122 123 124 125 126 127 128 129 130 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/metalearner.py
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/tlearner.py
49 50 51 | |
utils
FixedBinaryPropensity
FixedBinaryPropensity(propensity_score: float)
Bases: ClassifierMixin, BaseEstimator
Binary classifier propensity dummy model which outputs a fixed propensity, independently of covariates.
Source code in metalearners/utils.py
88 89 90 91 92 93 | |
metalearner_factory
metalearner_factory(
metalearner_prefix: str,
) -> type[MetaLearner]
Returns the MetaLearner class corresponding to the given prefix.
The accepted metalearner_prefix values are:
Source code in metalearners/utils.py
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 | |
simplify_output
simplify_output(tensor: ndarray) -> np.ndarray
Reduces dimensions of a CATE estimation tensor if possible.
The returned results will be of shape
-
\((n_{obs})\) if there are 2 tratment variants and and the outcome is either a regression outcome or a binary classification outcome.
-
\((n_{obs}, n_{classes})\) if there are 2 treatment variants and and the outcome is a classification outcome with at least 3 classes.
-
\((n_{obs}, n_{variants} - 1)\) if there are at least 3 variants and the outcome is either a regression outcome or a binary classification outcome.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if there are at least 3 variants and and the outcome is a classification outcome with at least 3 classes.
Source code in metalearners/utils.py
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 | |
xlearner
XLearner
XLearner(
is_classification: bool,
n_variants: int,
nuisance_model_factory: ModelFactory | None = None,
treatment_model_factory: ModelFactory | None = None,
propensity_model_factory: type[_ScikitModel]
| None = None,
nuisance_model_params: Params
| dict[str, Params]
| None = None,
treatment_model_params: Params
| dict[str, Params]
| None = None,
propensity_model_params: Params | None = None,
fitted_nuisance_models: dict[
str, list[CrossFitEstimator]
]
| None = None,
fitted_propensity_model: CrossFitEstimator
| None = None,
feature_set: Features
| dict[str, Features]
| None = None,
n_folds: int | dict[str, int] = 10,
random_state: int | None = None,
)
Bases: _ConditionalAverageOutcomeMetaLearner
X-Learner for CATE estimation as described by Kuenzel et al (2019).
Importantly, the current X-Learner implementation only supports:
- binary classes in case of a classification outcome
Source code in metalearners/metalearner.py
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 | |
init_args
property
init_args: dict[str, Any]
Create initialization parameters for a new MetaLearner.
Importantly, this does not copy further internal state, such as the weights or parameters of trained base models.
evaluate
evaluate(
X: Matrix,
y: Vector,
w: Vector,
is_oos: bool,
oos_method: OosMethod = OVERALL,
scoring: Scoring | None = None,
) -> dict[str, float]
Evaluate the MetaLearner.
The keys in scoring which are not a name of a model contained in the MetaLearner
will be ignored, for information about this names check
nuisance_model_specifications and
treatment_model_specifications.
The values must be a list of:
stringrepresenting asklearnscoring method. Check here for the possible values.Callablewith signaturescorer(estimator, X, y_true, **kwargs). We recommend usingsklearn.metrics.make_scorerto create such aCallable.
If some model name is not present in the keys of scoring then the default used
metrics will be neg_log_loss if it is a classifier and neg_root_mean_squared_error
if it is a regressor.
The returned dictionary keys have the following structure:
-
For nuisance models:
- If the cardinality is one:
f"{model_kind}_{scorer}" - If there is one model for each treatment variant (including control):
f"{model_kind}_{treatment_variant}_{scorer}"
- If the cardinality is one:
-
For treatment models:
f"{model_kind}_{treatment_variant}_vs_0_{scorer}"
Where scorer is the name of the scorer if it is a string and "custom_scorer_{idx}"
if it is a callable where idx is the index in the scorers list.
Source code in metalearners/xlearner.py
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 | |
explainer
explainer(
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> Explainer
Create an Explainer
which can be used in feature_importances.
This function can be used in two distinct manners based on the provided parameters:
- When parameters
X,cate_estimates, andcate_model_factoryare all set toNone, the function creates anExplainerusing the pre-existing treatment models. If these models do not exist, however, it triggers aValueError. - On the contrary, if
X,cate_estimates, andcate_model_factoryare notNone, the function initiates an instance of theExplainerclass using these parameters. This instance then fits new models for each treatment variant, and these models are employed to calculate the importance of features.
Source code in metalearners/metalearner.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 | |
feature_importances
feature_importances(
feature_names: Collection[str] | None = None,
normalize: bool = False,
sort_values: bool = False,
explainer: Explainer | None = None,
X: Matrix | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> FeatureImportances
Calculates the feature importance for each treatment group.
If explainer is None, a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
X, cate_estimates, cate_model_factory and cate_model_params are
ignored.
If normalization = True, for each treatment variant the feature importances
are normalized so that they sum to 1.
feature_names is optional but in the case it’s not passed the names of the
features will default to f"Feature {i}" where i is the corresponding
feature index.
The returned list contains the feature importances for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
fit
fit(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
n_jobs_cross_fitting will be used at the cross-fitting level and
n_jobs_base_learners will be used at the stage level. None means 1 unless in a
joblib.parallel_backend
context. -1 means using all processors.
For more information about parallelism check parallelism.
fit_params is an optional dict to be forwarded to base estimator fit calls. It supports
two usages patterns:
fit_params={"parameter_of_interest": value_of_interest}
fit_params={
"nuisance": {
"nuisance_model_kind1": {"parameter_of_interest1": value_of_interest1},
"nuisance_model_kind3": {"parameter_of_interest3": value_of_interest3},
},
"treatment": {"treatment_model_kind1": {"parameter_of_interest4": value_of_interest4}}
}
In the former approach, the parameter and value of interest are passed to all base models. In the the latter approach, the explicitly qualified parameter-value pairs are passed to respective base models and no fitting parameters are passed to base models not explicitly listed. Note that in this pattern, propensity models are considered a nuisance model.
synchronize_cross_fitting indicates whether the learning of different base models should use exactly
the same data splits where possible. Note that if there are several models to be synchronized which are
classifiers, these cannot be split via stratification.
Source code in metalearners/metalearner.py
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 | |
fit_all_nuisance
fit_all_nuisance(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all nuisance models of the MetaLearner.
If pre-fitted models were passed at instantiation, these are never refitted.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the nuisance models, and in the case they should also be used
by the treatment models, these should also be passed in the following call to
fit_all_treatment.
This method, combined with fit_all_treatment,
facilitates the segmentation of the metalearner fitting process into two distinct parts.
This division allows for interventions between the two stages, such as performing
feature selection for the treatment models or conducting hyperparameter optimization
within the nuisance models.
Source code in metalearners/xlearner.py
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 | |
fit_all_treatment
fit_all_treatment(
X: Matrix,
y: Vector,
w: Vector,
n_jobs_cross_fitting: int | None = None,
fit_params: dict | None = None,
synchronize_cross_fitting: bool = True,
n_jobs_base_learners: int | None = None,
) -> Self
Fit all treatment models of the MetaLearner.
The only difference with fit parameters,
is that if fit_params follows the first usage pattern (explained in
fit), then the training parameters
will only be used for the treatment models, as the nuisance models should already
be fitted.
Source code in metalearners/xlearner.py
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 | |
fit_nuisance
fit_nuisance(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit a given nuisance model of a MetaLearner.
y represents the objective of the given nuisance model, not necessarily the outcome of the experiment.
If pre-fitted models were passed at instantiation, these are never refitted.
Source code in metalearners/metalearner.py
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 | |
fit_treatment
fit_treatment(
X: Matrix,
y: Vector,
model_kind: str,
model_ord: int,
fit_params: dict | None = None,
n_jobs_cross_fitting: int | None = None,
cv: SplitIndices | None = None,
) -> Self
Fit the treatment model of a MetaLearner.
y represents the objective of the given treatment model, not necessarily the outcome of the experiment.
Source code in metalearners/metalearner.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
nuisance_model_specifications
classmethod
nuisance_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all first-stage models.
Source code in metalearners/xlearner.py
52 53 54 55 56 57 58 59 60 61 62 63 | |
predict
predict(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Estimate the CATE.
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants} - 1, 1)\) if the outcome is a scalar, i.e. in case of a regression problem.
-
\((n_{obs}, n_{variants} - 1, n_{classes})\) if the outcome is a class, i.e. in case of a classification problem.
In the case of multiple treatment variants, the second dimension represents the CATE of the corresponding variant vs the control (variant 0).
Source code in metalearners/xlearner.py
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 | |
predict_conditional_average_outcomes
predict_conditional_average_outcomes(
X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL
) -> np.ndarray
Predict the vectors of conditional average outcomes.
These are defined as \(\mathbb{E}[Y_i(w) | X]\) for each treatment variant \(w\).
If is_oos, an acronym for ‘is out of sample’, is False,
the estimates will stem from cross-fitting. Otherwise,
various approaches exist, specified via oos_method.
The returned ndarray is of shape:
-
\((n_{obs}, n_{variants}, 1)\) if the outcome is a scalar, i.e., in case of a regression problem.
-
\((n_{obs}, n_{variants}, n_{classes})\) if the outcome is a class, i.e., in case of a classification problem.
Source code in metalearners/metalearner.py
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 | |
predict_nuisance
predict_nuisance(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given nuisance model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
predict_treatment
predict_treatment(
X: Matrix,
model_kind: str,
model_ord: int,
is_oos: bool,
oos_method: OosMethod = OVERALL,
) -> np.ndarray
Estimate based on a given treatment model.
Importantly, this method needs to implement the subselection of X based on
the feature_set field of MetaLearner.
Source code in metalearners/metalearner.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
shap_values
shap_values(
X: Matrix,
shap_explainer_factory: type[Explainer],
shap_explainer_params: dict | None = None,
explainer: Explainer | None = None,
cate_estimates: ndarray | None = None,
cate_model_factory: type[_ScikitModel] | None = None,
cate_model_params: Params | None = None,
) -> list[np.ndarray]
Calculates the shap values for each treatment group.
If explainer is None a new Explainer
is created using MetaLearner.explainer
with the passed parameters. If explainer is not None, then the parameters
cate_estimates, cate_model_factory and cate_model_params are
ignored.
The parameter shap_explainer_factory can be used to specify the type of shap
explainer, for the different options see
here.
The returned list contains the shap values for each treatment variant in ascending order.
Source code in metalearners/metalearner.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |
treatment_model_specifications
classmethod
treatment_model_specifications() -> dict[
str, _ModelSpecifications
]
Return the specifications of all second-stage models.
Source code in metalearners/xlearner.py
65 66 67 68 69 70 71 72 73 74 75 76 | |