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.390403 1.679967 0.0 0.627001 0.093041 -1.459386 0 2 4.204183
1 0.252010 -0.661353 0.0 0.741059 1.295219 0.299472 3 1 20.173468
2 0.121272 -0.473770 0.0 0.042571 -0.161902 0.754895 2 1 3.945207
3 0.452158 -0.479059 1.0 0.538432 -0.761370 -0.621642 1 3 14.612701
4 -0.861376 -1.017169 1.0 0.694183 0.066931 -1.141494 1 0 16.963859
y
0 67.616965
1 172.629444
2 42.371186
3 125.514972
4 89.515059
True causal estimate is 10.115173307156159
[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,W1,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W1,W3,U) = P(y|v0,W0,W2,W1,W3)
### 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,W1,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W1,W3,U) = P(y|v0,W0,W2,W1,W3)
## Realized estimand
b: y~v0+W0+W2+W1+W3+v0*X1+v0*X0
Target units:
## Estimate
Mean value: 10.115232051072493
### Conditional Estimates
__categorical__X1 __categorical__X0
(-4.027, -0.78] (-3.835, -0.947] 3.232661
(-0.947, -0.361] 3.935033
(-0.361, 0.14] 4.396352
(0.14, 0.735] 5.038326
(0.735, 3.533] 5.876148
(-0.78, -0.186] (-3.835, -0.947] 6.721049
(-0.947, -0.361] 7.546194
(-0.361, 0.14] 7.995455
(0.14, 0.735] 8.470519
(0.735, 3.533] 9.308400
(-0.186, 0.304] (-3.835, -0.947] 8.893489
(-0.947, -0.361] 9.638015
(-0.361, 0.14] 10.202317
(0.14, 0.735] 10.614547
(0.735, 3.533] 11.508316
(0.304, 0.885] (-3.835, -0.947] 10.928639
(-0.947, -0.361] 11.724816
(-0.361, 0.14] 12.233992
(0.14, 0.735] 12.660952
(0.735, 3.533] 13.479923
(0.885, 3.775] (-3.835, -0.947] 14.332366
(-0.947, -0.361] 15.205151
(-0.361, 0.14] 15.614997
(0.14, 0.735] 16.356563
(0.735, 3.533] 16.958301
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,W1,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W1,W3,U) = P(y|v0,W0,W2,W1,W3)
## Realized estimand
b: y~v0+W0+W2+W1+W3 | X1,X0
Target units: Data subset defined by a function
## Estimate
Mean value: 11.555694014316966
Effect estimates: [[13.11580953]
[11.15127997]
[12.59983748]
...
[11.11147584]
[ 5.80016563]
[10.54259082]]
[9]:
print("True causal estimate is", data["ate"])
True causal estimate is 10.115173307156159
[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,W1,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W1,W3,U) = P(y|v0,W0,W2,W1,W3)
## Realized estimand
b: y~v0+W0+W2+W1+W3 | X1,X0
Target units:
## Estimate
Mean value: 10.057353772978695
Effect estimates: [[16.354826 ]
[ 7.50105768]
[ 8.14028247]
...
[ 7.53989247]
[10.40991005]
[18.24808762]]
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,W1,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W1,W3,U) = P(y|v0,W0,W2,W1,W3)
## Realized estimand
b: y~v0+W0+W2+W1+W3 | X1,X0
Target units: ate
## Estimate
Mean value: 10.011130311033616
Effect estimates: [[16.23743303]
[ 7.49012637]
[ 8.11941592]
...
[ 7.48329953]
[10.36387369]
[18.12399872]]
95.0% confidence interval: [[[16.241172 7.40887792 8.06423385 ... 7.38443403 10.35498524
18.14700155]]
[[16.5971469 7.52201806 8.16259681 ... 7.54135118 10.46881713
18.5531562 ]]]
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)
[[10.81890077]
[11.48805456]
[12.22158394]
[12.65584434]
[11.88328359]
[10.6823496 ]
[10.83076128]
[10.68507901]
[10.78816145]
[12.07359798]]
Can also retrieve the raw EconML estimator object for any further operations#
[13]:
print(dml_estimate._estimator_object)
<econml.dml.dml.DML object at 0x7fa89f69c2e0>
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 1.024148 -1.055064 0.0 -0.756150 1.620484 1.335869 0.186241 0 1
1 -1.222637 -1.410161 0.0 1.740952 -0.135198 -0.194422 -0.299153 1 1
2 -1.135109 -0.205192 1.0 1.742539 -0.268335 1.286121 -0.259469 1 1
3 -0.417956 0.108974 0.0 1.557403 0.983411 2.308749 0.315475 1 1
4 0.251667 -0.407366 1.0 0.925844 -0.965755 0.158682 -0.266748 1 1
... ... ... ... ... ... ... ... .. ..
9995 -1.906248 -1.172726 1.0 0.564009 0.394872 1.199234 0.547700 1 1
9996 1.422366 -2.865519 0.0 0.942461 -0.677161 0.999380 0.625962 1 1
9997 -0.878282 1.045554 1.0 0.717845 -0.275277 1.100961 0.537997 1 1
9998 -0.544228 -0.963796 0.0 0.034510 2.127658 0.385225 -0.096976 0 1
9999 2.232242 -0.809376 0.0 0.178958 -0.513625 0.033423 -1.528925 0 0
[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,W1,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W1,W3,U) = P(y|v0,W0,W2,W1,W3)
## Realized estimand
b: y~v0+W0+W2+W1+W3 | X1,X0
Target units: ate
## Estimate
Mean value: 0.1491092874608888
Effect estimates: [[0.19976935]
[0.08340154]
[0.10045313]
...
[0.12647311]
[0.12210266]
[0.26291562]]
True causal estimate is 0.1298
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+W1+W3 | X1,X0
Target units: Data subset defined by a function
## Estimate
Mean value: 10.486339540539216
Effect estimates: [[16.53832163]
[ 7.57570115]
[ 8.22115894]
...
[18.57113156]
[10.52022391]
[18.4664777 ]]
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 -1.132619 2.240804 0.484197 -2.104434 0.271481 0.0 0.586419
1 -1.311758 -0.485217 1.143235 -3.198105 -1.135851 0.0 0.806936
2 -0.207521 2.173122 0.090477 -1.983387 -2.008659 0.0 0.093819
3 -2.012235 1.233586 2.054828 -1.684281 -0.990385 0.0 0.509539
4 -1.760209 1.553054 1.591233 -0.563960 0.379794 0.0 0.454560
... ... ... ... ... ... ... ...
9995 -1.250526 2.326968 2.617440 -1.035179 -2.259243 0.0 0.716315
9996 -0.807387 -0.132493 0.441849 -0.690211 -1.812296 0.0 0.019810
9997 -1.325716 0.709405 0.321411 -1.766552 -0.917100 1.0 0.422460
9998 0.268305 -0.021396 0.534883 -0.161991 -1.489943 0.0 0.033144
9999 -0.573728 -1.010675 -0.062066 0.775892 -0.627839 1.0 0.341401
W0 W1 W2 W3 W4 v0 y
0 -0.767587 -1.395723 -0.120423 1.472097 0.949983 1 15.862526
1 -0.626848 0.094632 -0.989083 2.369389 0.316418 1 6.503628
2 -0.228156 -0.684086 0.559360 1.951354 -0.221470 1 21.089089
3 0.263738 0.257647 -1.102054 1.016231 0.396830 1 11.450630
4 0.945290 -0.829428 -0.596404 -0.906032 0.384260 1 9.870467
... ... ... ... ... ... .. ...
9995 -2.051696 -0.447844 0.006830 1.223629 0.491844 1 14.141882
9996 -0.119938 -0.771478 -1.095222 -0.007406 -0.254909 0 -7.163060
9997 0.145702 -1.524784 2.435758 1.489068 0.217670 1 20.722895
9998 0.240900 0.882374 0.335550 0.535168 1.111983 1 15.471457
9999 -1.907873 -1.697899 3.206109 -1.650689 -1.734413 0 -1.430652
[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,W2,W4,W1,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W4,W1,W3,U) = P(y|v0,W0,W2,W4,W1,W3)
## Realized estimand
b: y~v0+X4+X0+X2+X1+X3+W0+W2+W4+W1+W3
Target units: ate
## Estimate
Mean value: 9.625309050343546
Effect estimates: [[16.84313317]
[ 7.71716076]
[16.5497815 ]
...
[10.59294754]
[12.98422653]
[ 9.35330482]]
True causal estimate is 7.222706421594205
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,W2,W4,W1,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W2,W4,W1,W3,U) = P(y|v0,W0,W2,W4,W1,W3)
## Realized estimand
b: y~v0+X4+X0+X2+X1+X3+W0+W2+W4+W1+W3
Target units: Data subset provided as a data frame
## Estimate
Mean value: 10.970710116410869
Effect estimates: [[14.33998211]
[ 7.58308959]
[10.59294754]
[12.98422653]
[ 9.35330482]]
True causal estimate is 7.222706421594205
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:11.412761652660517
New effect:11.431441291880999
p value:0.6799999999999999
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:11.412761652660517
New effect:11.425182579718742
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:11.412761652660517
New effect:0.010923840033110374
p value:0.4416574318094865
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:11.412761652660517
New effect:11.435429824047851
p value:0.1991544805084513
More refutation methods to come, especially specific to the CATE estimators.