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.074490 -1.303370 1.0 0.827043 -0.080143 0.000727 3 1 27.367451
1 1.176271 0.484643 0.0 0.109790 1.704084 -0.958790 1 3 22.497209
2 -0.389033 -1.461422 1.0 0.883955 1.996364 -1.449119 3 2 38.095012
3 0.107164 -1.996178 0.0 0.801593 -0.746967 -1.977423 2 1 9.170798
4 -1.201743 -2.174917 0.0 0.183059 1.326386 -1.799496 3 1 11.610957
y
0 186.694028
1 331.587591
2 212.780923
3 42.530990
4 21.256660
True causal estimate is 8.094725071630723
[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|W2,W1,W3,W0])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W2,W1,W3,W0,U) = P(y|v0,W2,W1,W3,W0)
### 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|W2,W1,W3,W0])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W2,W1,W3,W0,U) = P(y|v0,W2,W1,W3,W0)
## Realized estimand
b: y~v0+W2+W1+W3+W0+v0*X0+v0*X1
Target units:
## Estimate
Mean value: 8.09471042319068
### Conditional Estimates
__categorical__X0 __categorical__X1
(-3.377, -0.714] (-4.288, -1.746] 0.805358
(-1.746, -1.178] 3.000837
(-1.178, -0.657] 4.194688
(-0.657, -0.0598] 5.579816
(-0.0598, 2.641] 7.870514
(-0.714, -0.127] (-4.288, -1.746] 3.213006
(-1.746, -1.178] 5.358204
(-1.178, -0.657] 6.600773
(-0.657, -0.0598] 7.956970
(-0.0598, 2.641] 10.182312
(-0.127, 0.37] (-4.288, -1.746] 4.596031
(-1.746, -1.178] 6.710503
(-1.178, -0.657] 8.027413
(-0.657, -0.0598] 9.386630
(-0.0598, 2.641] 11.511261
(0.37, 0.981] (-4.288, -1.746] 6.054914
(-1.746, -1.178] 8.222549
(-1.178, -0.657] 9.499573
(-0.657, -0.0598] 10.818442
(-0.0598, 2.641] 13.051497
(0.981, 3.948] (-4.288, -1.746] 8.511649
(-1.746, -1.178] 10.569371
(-1.178, -0.657] 11.892832
(-0.657, -0.0598] 13.177976
(-0.0598, 2.641] 15.587627
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|W2,W1,W3,W0])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W2,W1,W3,W0,U) = P(y|v0,W2,W1,W3,W0)
## Realized estimand
b: y~v0+W2+W1+W3+W0 | X0,X1
Target units: Data subset defined by a function
## Estimate
Mean value: 11.964386425883687
Effect estimates: [[14.47167642]
[11.31694365]
[15.36851497]
...
[ 8.96589624]
[11.65398595]
[12.53445187]]
[9]:
print("True causal estimate is", data["ate"])
True causal estimate is 8.094725071630723
[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|W2,W1,W3,W0])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W2,W1,W3,W0,U) = P(y|v0,W2,W1,W3,W0)
## Realized estimand
b: y~v0+W2+W1+W3+W0 | X0,X1
Target units:
## Estimate
Mean value: 8.090013247557842
Effect estimates: [[ 6.51904728]
[14.60526795]
[ 5.2184427 ]
...
[-1.49907887]
[ 4.85329253]
[ 4.30149063]]
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|W2,W1,W3,W0])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W2,W1,W3,W0,U) = P(y|v0,W2,W1,W3,W0)
## Realized estimand
b: y~v0+W2+W1+W3+W0 | X0,X1
Target units: ate
## Estimate
Mean value: 8.043447636378056
Effect estimates: [[ 6.49707874]
[14.43254149]
[ 5.23348911]
...
[-1.34452368]
[ 5.0236655 ]
[ 4.27935727]]
95.0% confidence interval: [[[ 6.51034028 14.45636701 5.22182635 ... -1.61324872 5.02328586
4.1845468 ]]
[[ 6.60374581 14.82293306 5.33566466 ... -1.22208464 5.28895868
4.38553916]]]
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.64394486]
[13.20788147]
[13.70694189]
[12.66864124]
[13.05853696]
[11.79337697]
[14.29543355]
[11.8040143 ]
[11.82573939]
[11.84604109]]
Can also retrieve the raw EconML estimator object for any further operations#
[13]:
print(dml_estimate._estimator_object)
<econml.dml.dml.DML object at 0x7fb442dffa60>
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.155064 -1.633513 0.0 1.808959 -0.554698 -0.015043 2.231266 1 1
1 -1.609667 -0.534600 1.0 -0.174732 2.645888 0.275202 0.003838 1 1
2 -1.556884 2.150726 0.0 1.512723 -0.278896 1.481449 0.105573 1 1
3 -0.572510 0.373897 0.0 -1.005399 0.661162 0.933428 0.090465 0 1
4 -1.712721 -0.117035 0.0 -0.314088 -0.606881 1.636273 1.719106 1 1
... ... ... ... ... ... ... ... .. ..
9995 0.254564 1.359995 0.0 -0.688704 0.060614 2.260174 -0.491484 0 0
9996 -0.438280 -1.153138 0.0 -1.302373 -0.567533 1.133784 -1.361383 0 0
9997 -0.802721 1.145639 0.0 -0.337605 0.807286 -0.718472 0.513604 1 1
9998 0.823203 1.321392 0.0 -0.624833 -0.233625 0.507267 -0.323660 0 0
9999 -1.281630 1.392570 1.0 -0.507362 0.555843 1.450096 0.674521 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|W2,W1,W3,W0])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W2,W1,W3,W0,U) = P(y|v0,W2,W1,W3,W0)
## Realized estimand
b: y~v0+W2+W1+W3+W0 | X0,X1
Target units: ate
## Estimate
Mean value: 0.32261445159094565
Effect estimates: [[0.23822163]
[0.26333773]
[0.34452621]
...
[0.32731623]
[0.36025662]
[0.32654465]]
True causal estimate is 0.2887
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+W2+W1+W3+W0 | X0,X1
Target units: Data subset defined by a function
## Estimate
Mean value: 8.750332593238001
Effect estimates: [[ 6.49965218]
[14.4889332 ]
[ 5.21609758]
...
[ 6.07498688]
[ 7.32526361]
[ 4.3039397 ]]
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.347363 0.125177 0.748467 -1.993687 -1.500770 0.0 0.655666
1 0.469182 -0.474045 -0.467413 -0.302767 -0.787000 1.0 0.870732
2 -1.118131 1.549390 1.139146 0.529937 0.191335 1.0 0.816647
3 0.118830 -0.968209 0.178145 0.447873 -0.796003 0.0 0.267590
4 -1.403957 0.451548 1.201263 0.430005 -0.894778 0.0 0.992131
... ... ... ... ... ... ... ...
9995 -0.659737 -1.277258 3.000070 -1.557859 1.356978 1.0 0.886732
9996 -0.276562 0.121784 -0.128049 0.376909 -2.446541 1.0 0.493861
9997 0.532812 0.258483 0.276562 -0.050333 -0.103349 0.0 0.092673
9998 0.342211 -1.521201 1.100245 0.115469 -0.070985 0.0 0.084780
9999 0.133669 -0.832255 1.328982 -0.699116 -0.067885 1.0 0.895874
W0 W1 W2 W3 W4 v0 y
0 0.371112 0.505477 -0.931820 1.534702 -0.648170 1 -9.464629
1 -1.248896 1.210981 1.603311 0.844024 -0.182294 1 7.750967
2 0.010915 -0.467206 -1.027313 0.432912 -1.207178 1 13.128632
3 0.521502 -1.269203 1.204482 2.199003 0.356945 1 13.602156
4 -0.466176 -0.919095 1.039380 1.071455 -0.134228 1 13.971409
... ... ... ... ... ... .. ...
9995 -0.701444 -1.418816 1.183439 -0.604605 -3.256044 1 -0.265908
9996 -0.874899 -1.025318 -0.256059 -0.291492 -0.168500 1 -5.671599
9997 2.289518 -1.509546 1.682752 1.160737 0.770691 1 25.808788
9998 -2.820784 -0.636941 1.422567 1.290314 -2.421858 1 1.015467
9999 1.011680 -0.572083 0.076794 0.631778 1.374830 1 15.569260
[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|W2,W1,W3,W4,W0])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W2,W1,W3,W4,W0,U) = P(y|v0,W2,W1,W3,W4,W0)
## Realized estimand
b: y~v0+X2+X4+X0+X3+X1+W2+W1+W3+W4+W0
Target units: ate
## Estimate
Mean value: 13.96672280619354
Effect estimates: [[-1.50772722]
[ 4.19225725]
[24.62384343]
...
[18.47059573]
[11.1463899 ]
[10.20916965]]
True causal estimate is 11.526729300025101
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|W2,W1,W3,W4,W0])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W2,W1,W3,W4,W0,U) = P(y|v0,W2,W1,W3,W4,W0)
## Realized estimand
b: y~v0+X2+X4+X0+X3+X1+W2+W1+W3+W4+W0
Target units: Data subset provided as a data frame
## Estimate
Mean value: 10.43963727783133
Effect estimates: [[10.93056674]
[ 1.44146437]
[18.47059573]
[11.1463899 ]
[10.20916965]]
True causal estimate is 11.526729300025101
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:12.585055171417508
New effect:12.744732986389408
p value:0.0
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:12.585055171417508
New effect:12.715212800083075
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:12.585055171417508
New effect:0.008710002302220158
p value:0.3619712187410795
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:12.585055171417508
New effect:12.727194132590444
p value:0.05516230920523492
More refutation methods to come, especially specific to the CATE estimators.