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.804960 0.340254 0.0 0.285999 0.974860 1.842413 0 1 8.890790
1 -0.833919 2.720888 0.0 0.653392 0.940763 -0.383673 2 1 20.190431
2 1.793524 0.958651 0.0 0.062492 1.572829 -0.559695 1 2 13.555869
3 0.053002 2.000443 0.0 0.816949 0.100082 -1.864247 1 0 14.182127
4 -2.507652 -1.851551 0.0 0.355198 -0.504796 1.177497 3 2 24.962308
y
0 106.403477
1 352.761225
2 198.280581
3 215.103913
4 119.857828
True causal estimate is 12.008183025631391
[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,W1,W2,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W1,W2,W3,U) = P(y|v0,W0,W1,W2,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,W1,W2,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W1,W2,W3,U) = P(y|v0,W0,W1,W2,W3)
## Realized estimand
b: y~v0+W0+W1+W2+W3+v0*X0+v0*X1
Target units:
## Estimate
Mean value: 12.008232994270037
### Conditional Estimates
__categorical__X0 __categorical__X1
(-4.1370000000000005, -1.098] (-2.959, -0.0343] 7.500050
(-0.0343, 0.552] 9.745907
(0.552, 1.062] 11.204830
(1.062, 1.644] 12.603578
(1.644, 4.655] 14.872838
(-1.098, -0.503] (-2.959, -0.0343] 7.989228
(-0.0343, 0.552] 10.271272
(0.552, 1.062] 11.693993
(1.062, 1.644] 13.134770
(1.644, 4.655] 15.563532
(-0.503, 0.00582] (-2.959, -0.0343] 8.181871
(-0.0343, 0.552] 10.544116
(0.552, 1.062] 12.036289
(1.062, 1.644] 13.422816
(1.644, 4.655] 15.714528
(0.00582, 0.595] (-2.959, -0.0343] 8.683817
(-0.0343, 0.552] 10.884850
(0.552, 1.062] 12.319892
(1.062, 1.644] 13.709233
(1.644, 4.655] 16.005228
(0.595, 3.962] (-2.959, -0.0343] 9.130391
(-0.0343, 0.552] 11.462807
(0.552, 1.062] 12.785725
(1.062, 1.644] 14.218457
(1.644, 4.655] 16.537321
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,W1,W2,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W1,W2,W3,U) = P(y|v0,W0,W1,W2,W3)
## Realized estimand
b: y~v0+W0+W1+W2+W3 | X0,X1
Target units: Data subset defined by a function
## Estimate
Mean value: 12.787688330873959
Effect estimates: [[13.53040654]
[ 8.6793453 ]
[12.18071332]
...
[12.23257577]
[12.66836777]
[11.58951399]]
[9]:
print("True causal estimate is", data["ate"])
True causal estimate is 12.008183025631391
[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,W1,W2,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W1,W2,W3,U) = P(y|v0,W0,W1,W2,W3)
## Realized estimand
b: y~v0+W0+W1+W2+W3 | X0,X1
Target units:
## Estimate
Mean value: 11.93733837590736
Effect estimates: [[10.39678622]
[16.63619074]
[13.47340147]
...
[ 6.21569661]
[11.85738555]
[14.81662799]]
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,W1,W2,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W1,W2,W3,U) = P(y|v0,W0,W1,W2,W3)
## Realized estimand
b: y~v0+W0+W1+W2+W3 | X0,X1
Target units: ate
## Estimate
Mean value: 11.908405225580475
Effect estimates: [[10.31950741]
[16.76510337]
[13.48592147]
...
[ 6.00055997]
[11.82499395]
[14.88382287]]
95.0% confidence interval: [[[10.25153087 16.77850545 13.44485001 ... 5.68411901 11.80780407
14.88696904]]
[[10.35512533 17.09672386 13.69795517 ... 5.96594057 11.91010139
15.11013832]]]
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.43298931]
[11.07941252]
[10.59329993]
[10.49762947]
[11.03226891]
[11.85317435]
[12.36586889]
[11.54393076]
[11.40376238]
[10.93578326]]
Can also retrieve the raw EconML estimator object for any further operations
[13]:
print(dml_estimate._estimator_object)
<econml.dml.dml.DML object at 0x7f4c3809dac0>
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.737065 -1.072964 1.0 -0.388094 0.525728 -0.715041 0.224334 1 1
1 -1.149267 -1.796967 0.0 -0.612683 -0.745804 0.252993 0.414059 0 0
2 -0.595089 -0.471618 0.0 -3.620881 -0.790281 0.782429 1.244299 0 0
3 -0.602614 -1.190146 1.0 0.084845 -0.202473 -0.070229 0.901543 1 1
4 -1.851642 0.476941 0.0 -1.259075 -2.596152 1.996187 -0.450505 0 0
... ... ... ... ... ... ... ... .. ..
9995 0.755220 0.885310 1.0 -0.988350 -0.330313 -0.875471 -0.217590 1 1
9996 0.270041 -0.657571 0.0 -1.059183 -2.069073 1.525051 0.065367 0 0
9997 -1.578795 0.303172 0.0 -2.773952 -1.086120 1.139950 1.233514 0 0
9998 -2.893679 0.353020 0.0 0.123402 -1.548967 1.007740 1.839298 0 1
9999 -1.885767 0.107075 0.0 0.224728 -1.313888 0.144936 1.852247 0 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,W1,W2,W3])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W1,W2,W3,U) = P(y|v0,W0,W1,W2,W3)
## Realized estimand
b: y~v0+W0+W1+W2+W3 | X0,X1
Target units: ate
## Estimate
Mean value: 0.25393741311823576
Effect estimates: [[ 0.2586901 ]
[ 0.15740397]
[ 0.30756034]
...
[ 0.16527201]
[-0.06408473]
[ 0.10347327]]
True causal estimate is 0.2428
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+W1+W2+W3 | X0,X1
Target units: Data subset defined by a function
## Estimate
Mean value: 12.346565111344125
Effect estimates: [[10.51837783]
[16.74164163]
[13.79944516]
...
[ 6.34250091]
[12.03568031]
[14.95518295]]
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.294515 2.021100 -0.400969 1.001272 -0.255332 1.0 0.789372
1 0.567898 0.502837 0.812207 1.167339 0.015679 1.0 0.733075
2 -1.771417 1.951379 1.781827 0.319133 -0.517705 1.0 0.807958
3 -0.223645 0.583579 2.217813 0.983221 0.646921 1.0 0.142880
4 -0.142972 1.566078 1.199371 0.561942 1.744763 0.0 0.582262
... ... ... ... ... ... ... ...
9995 0.516938 1.552206 2.111972 1.906909 0.724382 1.0 0.239563
9996 0.663853 0.182259 2.858206 0.597013 0.850559 1.0 0.048901
9997 -0.587015 2.444305 0.671331 -0.492370 0.557032 1.0 0.591897
9998 1.797653 1.098485 0.704680 0.257548 0.194590 1.0 0.847106
9999 0.887323 0.017509 0.443635 0.252148 -0.678747 0.0 0.049787
W0 W1 W2 W3 W4 v0 y
0 0.213702 0.448370 -1.610561 -0.324921 0.840035 1 9.654270
1 0.054257 -1.293510 0.809660 0.418565 1.474496 1 16.916323
2 -0.711372 -0.768835 -0.296304 -0.090520 0.847601 1 12.174951
3 -2.086637 0.914846 -0.412381 1.359414 3.819178 1 24.645863
4 0.290338 3.623860 -0.033126 0.246722 1.056886 1 29.725477
... ... ... ... ... ... .. ...
9995 1.495736 0.360780 1.235263 -0.617458 0.705889 1 29.938798
9996 0.227960 0.806736 0.209862 -1.534227 1.884250 1 30.248584
9997 0.429874 2.464721 0.376801 -0.559631 2.245034 1 20.861214
9998 1.087953 0.540293 -1.278817 -0.401619 1.293324 1 20.857098
9999 -0.452531 0.006141 1.108613 1.218417 3.013994 1 13.318078
[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|W1,W2,W0,W3,W4])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W2,W0,W3,W4,U) = P(y|v0,W1,W2,W0,W3,W4)
## Realized estimand
b: y~v0+X2+X4+X3+X1+X0+W1+W2+W0+W3+W4
Target units: ate
## Estimate
Mean value: 14.68852105963044
Effect estimates: [[10.12777423]
[17.53854428]
[14.25622559]
...
[20.28515765]
[19.793201 ]
[13.09617623]]
True causal estimate is 12.70992845701649
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|W1,W2,W0,W3,W4])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W2,W0,W3,W4,U) = P(y|v0,W1,W2,W0,W3,W4)
## Realized estimand
b: y~v0+X2+X4+X3+X1+X0+W1+W2+W0+W3+W4
Target units: Data subset provided as a data frame
## Estimate
Mean value: 22.083276653644315
Effect estimates: [[27.27288614]
[29.96896225]
[20.28515765]
[19.793201 ]
[13.09617623]]
True causal estimate is 12.70992845701649
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.273811978455843
New effect:11.287547309229048
p value:0.7
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.273811978455843
New effect:11.311447634723644
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.273811978455843
New effect:0.014951084203414821
p value:0.41037090226212897
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.273811978455843
New effect:11.278454042091491
p value:0.4126388531894509
More refutation methods to come, especially specific to the CATE estimators.