Created
December 14, 2022 15:17
-
-
Save arose13/77d8a0e97097e0c0aced26c8ed5e8141 to your computer and use it in GitHub Desktop.
Convert propensity score to sample weight for causal inference
This file contains hidden or 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
def compute_sample_weight(treatment_label, propensity_score, enforce_positivity=True, max_sample_weight=1e3): | |
""" | |
Demystifying Double Robustness | |
https://projecteuclid.org/download/pdfview_1/euclid.ss/1207580167 | |
https://arxiv.org/pdf/1706.10029.pdf | |
weights = [ti/g(Xi) + (1−ti)/(1−g(Xi))] | |
:param treatment_label: known treatment labels | |
:param propensity_score: estimated propensity scores | |
:param enforce_positivity: self explanatory | |
:param max_sample_weight: this is to prevent inf in subsquent calculation. N | |
:return: | |
""" | |
sample_weight = (treatment_label / propensity_score) + ((1 - treatment_label) / (1 - propensity_score)) | |
if enforce_positivity: | |
positively_control = np.isclose(propensity_score, 0) | |
positively_treatment = np.isclose(propensity_score, 1) | |
positivity_violations = positively_control | positively_treatment | |
sample_weight[positivity_violations] = 0 # This means the model ignores this value | |
return np.minimum(sample_weight, max_sample_weight) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment