Conditional Average Treatment Effects (CATE) with DoWhy and EconML#
This is an experimental feature where we use EconML methods from DoWhy. Using EconML allows CATE estimation using different methods.
All four steps of causal inference in DoWhy remain the same: model, identify, estimate, and refute. The key difference is that we now call econml methods in the estimation step. There is also a simpler example using linear regression to understand the intuition behind CATE estimators.
All datasets are generated using linear structural equations.
[1]:
%load_ext autoreload
%autoreload 2
[2]:
import numpy as np
import pandas as pd
import logging
import dowhy
from dowhy import CausalModel
import dowhy.datasets
import econml
import warnings
warnings.filterwarnings('ignore')
BETA = 10
[3]:
data = dowhy.datasets.linear_dataset(BETA, num_common_causes=4, num_samples=10000,
num_instruments=2, num_effect_modifiers=2,
num_treatments=1,
treatment_is_binary=False,
num_discrete_common_causes=2,
num_discrete_effect_modifiers=0,
one_hot_encode=False)
df=data['df']
print(df.head())
print("True causal estimate is", data["ate"])
X0 X1 Z0 Z1 W0 W1 W2 W3 v0 \
0 -0.325038 0.026434 0.0 0.617499 0.493523 -0.283728 3 1 24.980222
1 -0.408271 1.749117 1.0 0.932782 0.909109 -1.608716 1 0 21.460274
2 1.343407 -0.206811 0.0 0.075321 0.140837 -0.385296 2 3 22.954173
3 0.555999 0.511967 0.0 0.580734 2.275824 1.121968 2 3 35.662852
4 -1.690808 1.173344 0.0 0.773229 1.624739 -1.084779 2 1 20.521744
y
0 234.994132
1 291.200833
2 348.856987
3 505.382467
4 157.535747
True causal estimate is 8.902669609774744
[4]:
model = CausalModel(data=data["df"],
treatment=data["treatment_name"], outcome=data["outcome_name"],
graph=data["gml_graph"])
[5]:
model.view_model()
from IPython.display import Image, display
display(Image(filename="causal_model.png"))
[6]:
identified_estimand= model.identify_effect(proceed_when_unidentifiable=True)
print(identified_estimand)
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: backdoor
Estimand expression:
d
─────(E[y|W0,W2,W3,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W3,W1,U) = P(y|v0,W0,W2,W3,W1)
### Estimand : 2
Estimand name: iv
Estimand expression:
⎡ -1⎤
⎢ d ⎛ d ⎞ ⎥
E⎢─────────(y)⋅⎜─────────([v₀])⎟ ⎥
⎣d[Z₀ Z₁] ⎝d[Z₀ Z₁] ⎠ ⎦
Estimand assumption 1, As-if-random: If U→→y then ¬(U →→{Z0,Z1})
Estimand assumption 2, Exclusion: If we remove {Z0,Z1}→{v0}, then ¬({Z0,Z1}→y)
### Estimand : 3
Estimand name: frontdoor
No such variable(s) found!
Linear Model#
First, let us build some intuition using a linear model for estimating CATE. The effect modifiers (that lead to a heterogeneous treatment effect) can be modeled as interaction terms with the treatment. Thus, their value modulates the effect of treatment.
Below the estimated effect of changing treatment from 0 to 1.
[7]:
linear_estimate = model.estimate_effect(identified_estimand,
method_name="backdoor.linear_regression",
control_value=0,
treatment_value=1)
print(linear_estimate)
*** Causal Estimate ***
## Identified estimand
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: backdoor
Estimand expression:
d
─────(E[y|W0,W2,W3,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W3,W1,U) = P(y|v0,W0,W2,W3,W1)
## Realized estimand
b: y~v0+W0+W2+W3+W1+v0*X1+v0*X0
Target units:
## Estimate
Mean value: 8.902862963689204
### Conditional Estimates
__categorical__X1 __categorical__X0
(-3.8, -1.1] (-4.15, -0.961] -0.151653
(-0.961, -0.362] 2.923912
(-0.362, 0.171] 4.954060
(0.171, 0.75] 6.903461
(0.75, 4.024] 10.096284
(-1.1, -0.505] (-4.15, -0.961] 2.136280
(-0.961, -0.362] 5.396042
(-0.362, 0.171] 7.442992
(0.171, 0.75] 9.425397
(0.75, 4.024] 12.515350
(-0.505, 0.00923] (-4.15, -0.961] 3.568826
(-0.961, -0.362] 6.911587
(-0.362, 0.171] 8.895381
(0.171, 0.75] 11.006341
(0.75, 4.024] 14.008498
(0.00923, 0.585] (-4.15, -0.961] 5.297837
(-0.961, -0.362] 8.467598
(-0.362, 0.171] 10.418943
(0.171, 0.75] 12.395746
(0.75, 4.024] 15.662744
(0.585, 3.327] (-4.15, -0.961] 7.700977
(-0.961, -0.362] 10.861886
(-0.362, 0.171] 12.803144
(0.171, 0.75] 14.888401
(0.75, 4.024] 18.031512
dtype: float64
EconML methods#
We now move to the more advanced methods from the EconML package for estimating CATE.
First, let us look at the double machine learning estimator. Method_name corresponds to the fully qualified name of the class that we want to use. For double ML, it is “econml.dml.DML”.
Target units defines the units over which the causal estimate is to be computed. This can be a lambda function filter on the original dataframe, a new Pandas dataframe, or a string corresponding to the three main kinds of target units (“ate”, “att” and “atc”). Below we show an example of a lambda function.
Method_params are passed directly to EconML. For details on allowed parameters, refer to the EconML documentation.
[8]:
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LassoCV
from sklearn.ensemble import GradientBoostingRegressor
dml_estimate = model.estimate_effect(identified_estimand, method_name="backdoor.econml.dml.DML",
control_value = 0,
treatment_value = 1,
target_units = lambda df: df["X0"]>1, # condition used for CATE
confidence_intervals=False,
method_params={"init_params":{'model_y':GradientBoostingRegressor(),
'model_t': GradientBoostingRegressor(),
"model_final":LassoCV(fit_intercept=False),
'featurizer':PolynomialFeatures(degree=1, include_bias=False)},
"fit_params":{}})
print(dml_estimate)
*** Causal Estimate ***
## Identified estimand
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: backdoor
Estimand expression:
d
─────(E[y|W0,W2,W3,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W3,W1,U) = P(y|v0,W0,W2,W3,W1)
## Realized estimand
b: y~v0+W0+W2+W3+W1 | X1,X0
Target units: Data subset defined by a function
## Estimate
Mean value: 14.941209807972584
Effect estimates: [[14.45315884]
[11.64582565]
[16.57347686]
...
[16.42103416]
[15.73007015]
[13.66670667]]
[9]:
print("True causal estimate is", data["ate"])
True causal estimate is 8.902669609774744
[10]:
dml_estimate = model.estimate_effect(identified_estimand, method_name="backdoor.econml.dml.DML",
control_value = 0,
treatment_value = 1,
target_units = 1, # condition used for CATE
confidence_intervals=False,
method_params={"init_params":{'model_y':GradientBoostingRegressor(),
'model_t': GradientBoostingRegressor(),
"model_final":LassoCV(fit_intercept=False),
'featurizer':PolynomialFeatures(degree=1, include_bias=True)},
"fit_params":{}})
print(dml_estimate)
*** Causal Estimate ***
## Identified estimand
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: backdoor
Estimand expression:
d
─────(E[y|W0,W2,W3,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W3,W1,U) = P(y|v0,W0,W2,W3,W1)
## Realized estimand
b: y~v0+W0+W2+W3+W1 | X1,X0
Target units:
## Estimate
Mean value: 8.891875726258442
Effect estimates: [[ 8.85425759]
[13.41414491]
[14.469258 ]
...
[ 7.76091255]
[12.16180249]
[-0.6761542 ]]
CATE Object and Confidence Intervals#
EconML provides its own methods to compute confidence intervals. Using BootstrapInference in the example below.
[11]:
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LassoCV
from sklearn.ensemble import GradientBoostingRegressor
from econml.inference import BootstrapInference
dml_estimate = model.estimate_effect(identified_estimand,
method_name="backdoor.econml.dml.DML",
target_units = "ate",
confidence_intervals=True,
method_params={"init_params":{'model_y':GradientBoostingRegressor(),
'model_t': GradientBoostingRegressor(),
"model_final": LassoCV(fit_intercept=False),
'featurizer':PolynomialFeatures(degree=1, include_bias=True)},
"fit_params":{
'inference': BootstrapInference(n_bootstrap_samples=100, n_jobs=-1),
}
})
print(dml_estimate)
*** Causal Estimate ***
## Identified estimand
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: backdoor
Estimand expression:
d
─────(E[y|W0,W2,W3,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W3,W1,U) = P(y|v0,W0,W2,W3,W1)
## Realized estimand
b: y~v0+W0+W2+W3+W1 | X1,X0
Target units: ate
## Estimate
Mean value: 8.838156630291222
Effect estimates: [[ 8.81120921]
[13.37990042]
[14.35224352]
...
[ 7.70898768]
[12.12553041]
[-0.68579583]]
95.0% confidence interval: [[[ 8.80660901 13.2333401 14.36763455 ... 7.73945914 12.01716696
-0.95668123]]
[[ 8.9762209 13.70762288 14.77051902 ... 7.87237853 12.40107481
-0.4862633 ]]]
Can provide a new inputs as target units and estimate CATE on them.#
[12]:
test_cols= data['effect_modifier_names'] # only need effect modifiers' values
test_arr = [np.random.uniform(0,1, 10) for _ in range(len(test_cols))] # all variables are sampled uniformly, sample of 10
test_df = pd.DataFrame(np.array(test_arr).transpose(), columns=test_cols)
dml_estimate = model.estimate_effect(identified_estimand,
method_name="backdoor.econml.dml.DML",
target_units = test_df,
confidence_intervals=False,
method_params={"init_params":{'model_y':GradientBoostingRegressor(),
'model_t': GradientBoostingRegressor(),
"model_final":LassoCV(),
'featurizer':PolynomialFeatures(degree=1, include_bias=True)},
"fit_params":{}
})
print(dml_estimate.cate_estimates)
[[11.06860472]
[12.47575413]
[12.80112045]
[13.76858344]
[14.83918453]
[12.32441378]
[14.33254117]
[12.78596297]
[14.78849047]
[13.90845204]]
Can also retrieve the raw EconML estimator object for any further operations#
[13]:
print(dml_estimate._estimator_object)
<econml.dml.dml.DML object at 0x7f9d2b7a1b80>
Works with any EconML method#
In addition to double machine learning, below we example analyses using orthogonal forests, DRLearner (bug to fix), and neural network-based instrumental variables.
Binary treatment, Binary outcome#
[14]:
data_binary = dowhy.datasets.linear_dataset(BETA, num_common_causes=4, num_samples=10000,
num_instruments=1, num_effect_modifiers=2,
treatment_is_binary=True, outcome_is_binary=True)
# convert boolean values to {0,1} numeric
data_binary['df'].v0 = data_binary['df'].v0.astype(int)
data_binary['df'].y = data_binary['df'].y.astype(int)
print(data_binary['df'])
model_binary = CausalModel(data=data_binary["df"],
treatment=data_binary["treatment_name"], outcome=data_binary["outcome_name"],
graph=data_binary["gml_graph"])
identified_estimand_binary = model_binary.identify_effect(proceed_when_unidentifiable=True)
X0 X1 Z0 W0 W1 W2 W3 v0 y
0 -0.891000 1.068849 1.0 -0.449970 0.200347 -1.183873 1.491834 1 1
1 -0.347087 -0.381876 1.0 -1.408697 1.508676 -1.239940 -0.497845 1 1
2 -1.450958 1.251430 1.0 -1.121218 0.677152 0.332284 -0.324673 1 1
3 -0.074376 0.451862 1.0 -0.930789 -0.179364 -0.776244 2.974451 1 1
4 1.190687 1.021066 1.0 0.491658 -0.396474 1.264223 1.232690 1 1
... ... ... ... ... ... ... ... .. ..
9995 0.005269 0.604047 1.0 -1.646588 -0.873766 -1.537043 -0.466181 0 0
9996 3.166990 0.853544 1.0 -1.930949 0.708433 -2.695599 0.661317 0 0
9997 -1.518529 2.295651 1.0 -3.436668 0.942600 0.517978 1.104407 1 1
9998 0.870103 1.160866 1.0 -0.582403 -2.308482 1.483123 0.185109 1 1
9999 0.053390 0.084704 1.0 -1.086259 -1.985226 1.481227 2.206679 1 1
[10000 rows x 9 columns]
Using DRLearner estimator#
[15]:
from sklearn.linear_model import LogisticRegressionCV
#todo needs binary y
drlearner_estimate = model_binary.estimate_effect(identified_estimand_binary,
method_name="backdoor.econml.dr.LinearDRLearner",
confidence_intervals=False,
method_params={"init_params":{
'model_propensity': LogisticRegressionCV(cv=3, solver='lbfgs', multi_class='auto')
},
"fit_params":{}
})
print(drlearner_estimate)
print("True causal estimate is", data_binary["ate"])
*** Causal Estimate ***
## Identified estimand
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: backdoor
Estimand expression:
d
─────(E[y|W0,W2,W3,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W3,W1,U) = P(y|v0,W0,W2,W3,W1)
## Realized estimand
b: y~v0+W0+W2+W3+W1 | X1,X0
Target units: ate
## Estimate
Mean value: 0.2466102513892442
Effect estimates: [[0.26899938]
[0.25297638]
[0.29139942]
...
[0.28949862]
[0.1955492 ]
[0.23426653]]
True causal estimate is 0.2269
Instrumental Variable Method#
[16]:
dmliv_estimate = model.estimate_effect(identified_estimand,
method_name="iv.econml.iv.dml.DMLIV",
target_units = lambda df: df["X0"]>-1,
confidence_intervals=False,
method_params={"init_params":{
'discrete_treatment':False,
'discrete_instrument':False
},
"fit_params":{}})
print(dmliv_estimate)
*** Causal Estimate ***
## Identified estimand
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: iv
Estimand expression:
⎡ -1⎤
⎢ d ⎛ d ⎞ ⎥
E⎢─────────(y)⋅⎜─────────([v₀])⎟ ⎥
⎣d[Z₀ Z₁] ⎝d[Z₀ Z₁] ⎠ ⎦
Estimand assumption 1, As-if-random: If U→→y then ¬(U →→{Z0,Z1})
Estimand assumption 2, Exclusion: If we remove {Z0,Z1}→{v0}, then ¬({Z0,Z1}→y)
## Realized estimand
b: y~v0+W0+W2+W3+W1 | X1,X0
Target units: Data subset defined by a function
## Estimate
Mean value: 10.164821752275158
Effect estimates: [[ 8.90451098]
[13.42654773]
[14.3142846 ]
...
[ 3.6660944 ]
[ 7.80758771]
[12.18533079]]
Metalearners#
[17]:
data_experiment = dowhy.datasets.linear_dataset(BETA, num_common_causes=5, num_samples=10000,
num_instruments=2, num_effect_modifiers=5,
treatment_is_binary=True, outcome_is_binary=False)
# convert boolean values to {0,1} numeric
data_experiment['df'].v0 = data_experiment['df'].v0.astype(int)
print(data_experiment['df'])
model_experiment = CausalModel(data=data_experiment["df"],
treatment=data_experiment["treatment_name"], outcome=data_experiment["outcome_name"],
graph=data_experiment["gml_graph"])
identified_estimand_experiment = model_experiment.identify_effect(proceed_when_unidentifiable=True)
X0 X1 X2 X3 X4 Z0 Z1 \
0 0.260393 0.719301 -0.754579 0.126868 -0.201087 1.0 0.763917
1 0.941073 0.127123 1.054205 -0.848329 -0.629751 1.0 0.640327
2 -0.817784 -0.847592 -0.622050 0.032113 2.103121 1.0 0.927565
3 0.265890 0.094979 1.030916 -1.692414 1.914537 1.0 0.467812
4 0.576822 -1.643755 0.149765 -0.569399 -0.577180 1.0 0.679476
... ... ... ... ... ... ... ...
9995 -0.461245 -1.070942 -0.035788 -2.299669 0.528908 0.0 0.784723
9996 1.054222 -0.149919 2.591542 -1.831742 1.241029 0.0 0.504520
9997 2.135569 -1.045682 1.138920 -0.768199 0.486598 1.0 0.083866
9998 0.004286 0.350758 0.352595 -0.763722 0.691796 1.0 0.350065
9999 -1.773971 -0.956212 3.013741 -2.076913 -0.087576 1.0 0.958802
W0 W1 W2 W3 W4 v0 y
0 -0.816231 -0.278030 -1.358452 -1.169202 -0.541160 1 -0.917065
1 -0.087284 0.706231 0.451799 -0.498180 -0.773171 1 7.622680
2 -1.597080 0.028219 1.062276 0.148348 -1.184611 1 5.064207
3 -1.546551 0.146455 -1.750542 -1.286350 -1.421732 0 -17.272413
4 0.428079 -1.664901 0.320817 -1.404837 -0.528236 1 -8.350570
... ... ... ... ... ... .. ...
9995 -1.745984 -0.712558 0.628140 -2.172792 -0.543586 0 -14.159060
9996 0.809316 0.331980 -0.047900 -1.770173 -1.127656 1 0.176703
9997 -1.649127 -1.048371 -1.767434 0.181614 -3.470777 0 -26.433027
9998 -0.105860 -0.976386 -2.152419 -0.834633 -0.191533 1 -5.289629
9999 -1.380797 0.648727 -0.831082 -1.026712 -0.690042 1 -13.222182
[10000 rows x 14 columns]
[18]:
from sklearn.ensemble import RandomForestRegressor
metalearner_estimate = model_experiment.estimate_effect(identified_estimand_experiment,
method_name="backdoor.econml.metalearners.TLearner",
confidence_intervals=False,
method_params={"init_params":{
'models': RandomForestRegressor()
},
"fit_params":{}
})
print(metalearner_estimate)
print("True causal estimate is", data_experiment["ate"])
*** Causal Estimate ***
## Identified estimand
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: backdoor
Estimand expression:
d
─────(E[y|W0,W4,W2,W3,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W4,W2,W3,W1,U) = P(y|v0,W0,W4,W2,W3,W1)
## Realized estimand
b: y~v0+X3+X4+X0+X2+X1+W0+W4+W2+W3+W1
Target units: ate
## Estimate
Mean value: 11.389059695393675
Effect estimates: [[12.43025891]
[11.86000901]
[10.03820659]
...
[23.65085435]
[11.30398871]
[-3.88591856]]
True causal estimate is 8.630221128294048
Avoiding retraining the estimator#
Once an estimator is fitted, it can be reused to estimate effect on different data points. In this case, you can pass fit_estimator=False
to estimate_effect
. This works for any EconML estimator. We show an example for the T-learner below.
[19]:
# For metalearners, need to provide all the features (except treatmeant and outcome)
metalearner_estimate = model_experiment.estimate_effect(identified_estimand_experiment,
method_name="backdoor.econml.metalearners.TLearner",
confidence_intervals=False,
fit_estimator=False,
target_units=data_experiment["df"].drop(["v0","y", "Z0", "Z1"], axis=1)[9995:],
method_params={})
print(metalearner_estimate)
print("True causal estimate is", data_experiment["ate"])
*** Causal Estimate ***
## Identified estimand
Estimand type: EstimandType.NONPARAMETRIC_ATE
### Estimand : 1
Estimand name: backdoor
Estimand expression:
d
─────(E[y|W0,W4,W2,W3,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W4,W2,W3,W1,U) = P(y|v0,W0,W4,W2,W3,W1)
## Realized estimand
b: y~v0+X3+X4+X0+X2+X1+W0+W4+W2+W3+W1
Target units: Data subset provided as a data frame
## Estimate
Mean value: 8.14088580999011
Effect estimates: [[ 0.50906441]
[ 9.12644014]
[23.65085435]
[11.30398871]
[-3.88591856]]
True causal estimate is 8.630221128294048
Refuting the estimate#
Adding a random common cause variable#
[20]:
res_random=model.refute_estimate(identified_estimand, dml_estimate, method_name="random_common_cause")
print(res_random)
Refute: Add a random common cause
Estimated effect:13.309310770960835
New effect:13.21637787572473
p value:0.04
Adding an unobserved common cause variable#
[21]:
res_unobserved=model.refute_estimate(identified_estimand, dml_estimate, method_name="add_unobserved_common_cause",
confounders_effect_on_treatment="linear", confounders_effect_on_outcome="linear",
effect_strength_on_treatment=0.01, effect_strength_on_outcome=0.02)
print(res_unobserved)
Refute: Add an Unobserved Common Cause
Estimated effect:13.309310770960835
New effect:13.176560758447843
Replacing treatment with a random (placebo) variable#
[22]:
res_placebo=model.refute_estimate(identified_estimand, dml_estimate,
method_name="placebo_treatment_refuter", placebo_type="permute",
num_simulations=10 # at least 100 is good, setting to 10 for speed
)
print(res_placebo)
Refute: Use a Placebo Treatment
Estimated effect:13.309310770960835
New effect:0.006582087697995104
p value:0.4319472926953155
Removing a random subset of the data#
[23]:
res_subset=model.refute_estimate(identified_estimand, dml_estimate,
method_name="data_subset_refuter", subset_fraction=0.8,
num_simulations=10)
print(res_subset)
Refute: Use a subset of data
Estimated effect:13.309310770960835
New effect:13.205149366780697
p value:0.07841967993720045
More refutation methods to come, especially specific to the CATE estimators.