-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
X-Learner: Use the same sample splits in all base models. #84
Draft
kklein
wants to merge
11
commits into
main
Choose a base branch
from
xlearner-sync
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
5afa7af
Draft usage of same splits in all models.
kklein 413e5b0
Clean up.
kklein 59554b1
Fix attribute reference.
kklein c0bdcbd
Filter properly.
kklein fe16b75
Fix out-of-sample evaluate.
kklein 410e9e7
Fix in-sample evaluate.
kklein 6a43c9c
Adapt synchronization-related tests.
kklein bbfff15
Fix cao estimation only taking place for seen variant.
kklein c8dd77e
Merge branch 'main' into xlearner-sync
kklein 6803096
Update metalearners/xlearner.py
kklein b005eb7
Add type hints for cv-split-related attributes.
kklein File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -99,31 +99,39 @@ def fit_all_nuisance( | |
|
||
qualified_fit_params = self._qualified_fit_params(fit_params) | ||
|
||
self._cvs: list = [] | ||
# TODO: Move this to object initialization. | ||
if not synchronize_cross_fitting: | ||
raise ValueError( | ||
"The X-Learner does not support synchronize_cross_fitting=False." | ||
) | ||
|
||
self._cv_split_indices = self._split(X) | ||
self._treatment_cv_split_indices = {} | ||
|
||
for treatment_variant in range(self.n_variants): | ||
self._treatment_variants_indices.append(w == treatment_variant) | ||
if synchronize_cross_fitting: | ||
cv_split_indices = self._split( | ||
index_matrix(X, self._treatment_variants_indices[treatment_variant]) | ||
treatment_indices = np.where( | ||
self._treatment_variants_indices[treatment_variant] | ||
)[0] | ||
self._treatment_cv_split_indices[treatment_variant] = [ | ||
( | ||
np.intersect1d(train_indices, treatment_indices), | ||
np.intersect1d(test_indices, treatment_indices), | ||
) | ||
else: | ||
cv_split_indices = None | ||
self._cvs.append(cv_split_indices) | ||
for train_indices, test_indices in self._cv_split_indices | ||
MatthiasLoefflerQC marked this conversation as resolved.
Show resolved
Hide resolved
|
||
] | ||
|
||
nuisance_jobs: list[_ParallelJoblibSpecification | None] = [] | ||
for treatment_variant in range(self.n_variants): | ||
nuisance_jobs.append( | ||
self._nuisance_joblib_specifications( | ||
X=index_matrix( | ||
X, self._treatment_variants_indices[treatment_variant] | ||
), | ||
y=y[self._treatment_variants_indices[treatment_variant]], | ||
X=X, | ||
y=y, | ||
model_kind=VARIANT_OUTCOME_MODEL, | ||
model_ord=treatment_variant, | ||
n_jobs_cross_fitting=n_jobs_cross_fitting, | ||
fit_params=qualified_fit_params[NUISANCE][VARIANT_OUTCOME_MODEL], | ||
cv=self._cvs[treatment_variant], | ||
cv=self._treatment_cv_split_indices[treatment_variant], | ||
) | ||
) | ||
|
||
|
@@ -160,14 +168,14 @@ def fit_all_treatment( | |
) -> Self: | ||
if self._treatment_variants_indices is None: | ||
raise ValueError( | ||
"The nuisance models need to be fitted before fitting the treatment models." | ||
"The nuisance models need to be fitted before fitting the treatment models. " | ||
"In particular, the MetaLearner's attribute _treatment_variant_indices, " | ||
"typically set during nuisance fitting, is None." | ||
) | ||
if not hasattr(self, "_cvs"): | ||
if not hasattr(self, "_treatment_cv_split_indices"): | ||
raise ValueError( | ||
"The nuisance models need to be fitted before fitting the treatment models." | ||
"In particular, the MetaLearner's attribute _cvs, " | ||
"The nuisance models need to be fitted before fitting the treatment models. " | ||
"In particular, the MetaLearner's attribute _treatment_cv_split_indices, " | ||
"typically set during nuisance fitting, does not exist." | ||
) | ||
qualified_fit_params = self._qualified_fit_params(fit_params) | ||
|
@@ -180,34 +188,32 @@ def fit_all_treatment( | |
is_oos=False, | ||
) | ||
) | ||
|
||
for treatment_variant in range(1, self.n_variants): | ||
imputed_te_control, imputed_te_treatment = self._pseudo_outcome( | ||
y, w, treatment_variant, conditional_average_outcome_estimates | ||
) | ||
|
||
treatment_jobs.append( | ||
self._treatment_joblib_specifications( | ||
X=index_matrix( | ||
X, self._treatment_variants_indices[treatment_variant] | ||
), | ||
X=X, | ||
y=imputed_te_treatment, | ||
model_kind=TREATMENT_EFFECT_MODEL, | ||
model_ord=treatment_variant - 1, | ||
n_jobs_cross_fitting=n_jobs_cross_fitting, | ||
fit_params=qualified_fit_params[TREATMENT][TREATMENT_EFFECT_MODEL], | ||
cv=self._cvs[treatment_variant], | ||
cv=self._treatment_cv_split_indices[treatment_variant], | ||
) | ||
) | ||
|
||
treatment_jobs.append( | ||
self._treatment_joblib_specifications( | ||
X=index_matrix(X, self._treatment_variants_indices[0]), | ||
X=X, | ||
y=imputed_te_control, | ||
model_kind=CONTROL_EFFECT_MODEL, | ||
model_ord=treatment_variant - 1, | ||
n_jobs_cross_fitting=n_jobs_cross_fitting, | ||
fit_params=qualified_fit_params[TREATMENT][CONTROL_EFFECT_MODEL], | ||
cv=self._cvs[0], | ||
cv=self._treatment_cv_split_indices[0], | ||
) | ||
) | ||
|
||
|
@@ -216,6 +222,7 @@ def fit_all_treatment( | |
delayed(_fit_cross_fit_estimator_joblib)(job) for job in treatment_jobs | ||
) | ||
self._assign_joblib_treatment_results(results) | ||
|
||
return self | ||
|
||
def predict( | ||
|
@@ -278,19 +285,18 @@ def predict( | |
oos_method=oos_method, | ||
) | ||
) | ||
|
||
tau_hat_treatment[treatment_variant_indices] = self.predict_treatment( | ||
X=index_matrix(X, treatment_variant_indices), | ||
X=X, | ||
model_kind=TREATMENT_EFFECT_MODEL, | ||
model_ord=treatment_variant - 1, | ||
is_oos=False, | ||
) | ||
)[treatment_variant_indices] | ||
tau_hat_control[control_indices] = self.predict_treatment( | ||
X=index_matrix(X, control_indices), | ||
X=X, | ||
model_kind=CONTROL_EFFECT_MODEL, | ||
model_ord=treatment_variant - 1, | ||
is_oos=False, | ||
) | ||
)[control_indices] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. do we need is_oos=False below (and likewise for tau_hat_treatment)? Might be worth a try. |
||
tau_hat_control[non_control_indices] = self.predict_treatment( | ||
X=index_matrix(X, non_control_indices), | ||
model_kind=CONTROL_EFFECT_MODEL, | ||
|
@@ -337,8 +343,8 @@ def evaluate( | |
|
||
variant_outcome_evaluation = _evaluate_model_kind( | ||
cfes=self._nuisance_models[VARIANT_OUTCOME_MODEL], | ||
Xs=[X[w == tv] for tv in range(self.n_variants)], | ||
ys=[y[w == tv] for tv in range(self.n_variants)], | ||
Xs=[X] * self.n_variants, | ||
ys=[y] * self.n_variants, | ||
scorers=safe_scoring[VARIANT_OUTCOME_MODEL], | ||
model_kind=VARIANT_OUTCOME_MODEL, | ||
is_oos=is_oos, | ||
|
@@ -378,7 +384,7 @@ def evaluate( | |
|
||
te_treatment_evaluation = _evaluate_model_kind( | ||
self._treatment_models[TREATMENT_EFFECT_MODEL], | ||
Xs=[X[w == tv] for tv in range(1, self.n_variants)], | ||
Xs=[X] * self.n_variants, | ||
ys=imputed_te_treatment, | ||
scorers=safe_scoring[TREATMENT_EFFECT_MODEL], | ||
model_kind=TREATMENT_EFFECT_MODEL, | ||
|
@@ -390,7 +396,7 @@ def evaluate( | |
|
||
te_control_evaluation = _evaluate_model_kind( | ||
self._treatment_models[CONTROL_EFFECT_MODEL], | ||
Xs=[X[w == 0] for _ in range(1, self.n_variants)], | ||
Xs=[X] * self.n_variants, | ||
ys=imputed_te_control, | ||
scorers=safe_scoring[CONTROL_EFFECT_MODEL], | ||
model_kind=CONTROL_EFFECT_MODEL, | ||
|
@@ -424,16 +430,8 @@ def _pseudo_outcome( | |
This function can be used with both in-sample or out-of-sample data. | ||
""" | ||
validate_valid_treatment_variant_not_control(treatment_variant, self.n_variants) | ||
|
||
treatment_indices = w == treatment_variant | ||
control_indices = w == 0 | ||
|
||
treatment_outcome = index_matrix( | ||
conditional_average_outcome_estimates, control_indices | ||
)[:, treatment_variant] | ||
control_outcome = index_matrix( | ||
conditional_average_outcome_estimates, treatment_indices | ||
)[:, 0] | ||
treatment_outcome = conditional_average_outcome_estimates[:, treatment_variant] | ||
control_outcome = conditional_average_outcome_estimates[:, 0] | ||
|
||
if self.is_classification: | ||
# Get the probability of positive class, multiclass is currently not supported. | ||
|
@@ -443,8 +441,8 @@ def _pseudo_outcome( | |
control_outcome = control_outcome[:, 0] | ||
treatment_outcome = treatment_outcome[:, 0] | ||
|
||
imputed_te_treatment = y[treatment_indices] - control_outcome | ||
imputed_te_control = treatment_outcome - y[control_indices] | ||
imputed_te_treatment = y - control_outcome | ||
imputed_te_control = treatment_outcome - y | ||
|
||
return imputed_te_control, imputed_te_treatment | ||
|
||
|
@@ -534,3 +532,54 @@ def _build_onnx(self, models: Mapping[str, Sequence], output_name: str = "tau"): | |
final_model = build(input_dict, {output_name: cate}) | ||
check_model(final_model, full_check=True) | ||
return final_model | ||
|
||
def predict_conditional_average_outcomes( | ||
self, X: Matrix, is_oos: bool, oos_method: OosMethod = OVERALL | ||
) -> np.ndarray: | ||
if self._treatment_variants_indices is None: | ||
raise ValueError( | ||
"The metalearner needs to be fitted before predicting." | ||
"In particular, the MetaLearner's attribute _treatment_variant_indices, " | ||
"typically set during fitting, is None." | ||
) | ||
# TODO: Consider multiprocessing | ||
n_obs = len(X) | ||
cao_tensor = self._nuisance_tensors(n_obs)[VARIANT_OUTCOME_MODEL][0] | ||
predict_method_name = self.nuisance_model_specifications()[ | ||
VARIANT_OUTCOME_MODEL | ||
]["predict_method"](self) | ||
conditional_average_outcomes_list = [] | ||
|
||
for tv in range(self.n_variants): | ||
if is_oos: | ||
conditional_average_outcomes_list.append( | ||
self.predict_nuisance( | ||
X=X, | ||
model_kind=VARIANT_OUTCOME_MODEL, | ||
model_ord=tv, | ||
is_oos=True, | ||
kklein marked this conversation as resolved.
Show resolved
Hide resolved
|
||
oos_method=oos_method, | ||
) | ||
) | ||
else: | ||
# TODO: Consider moving this logic to CrossFitEstimator.predict. | ||
cfe = self._nuisance_models[VARIANT_OUTCOME_MODEL][tv] | ||
conditional_average_outcome_estimates = cao_tensor.copy() | ||
|
||
for fold_index, (train_indices, prediction_indices) in enumerate( | ||
self._cv_split_indices | ||
): | ||
fold_model = cfe._estimators[fold_index] | ||
predict_method = getattr(fold_model, predict_method_name) | ||
fold_estimates = predict_method(index_matrix(X, prediction_indices)) | ||
conditional_average_outcome_estimates[prediction_indices] = ( | ||
fold_estimates | ||
) | ||
|
||
conditional_average_outcomes_list.append( | ||
conditional_average_outcome_estimates | ||
) | ||
|
||
return np.stack(conditional_average_outcomes_list, axis=1).reshape( | ||
n_obs, self.n_variants, -1 | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is an opaque way of turning an array
[True, True, False, False, True]
into an array[0, 1, 4]
. Not sure if there's a neater way of doing that.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[index for index, value in enumerate(vector) if value]
would work too, I guess, and is more verbose, but I like the np.where :)