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
dowhy.enable_notebook_rendering()
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.158168 -0.899820  0.0  0.681746  0.251151  1.546765  2  1  19.285470
1 -0.518711 -0.422343  0.0  0.620648  1.598874  0.916203  2  0  22.228781
2  0.868765 -1.072946  1.0  0.341001  0.869204 -1.279572  1  3  25.278296
3  0.997861 -1.261269  0.0  0.130633  1.161313 -0.255593  1  2  14.289586
4  0.739726 -0.333233  0.0  0.869945  1.052723 -1.414590  3  3  27.371729

            y
0  175.731229
1  198.484323
2  272.509369
3  161.939588
4  320.463876
True causal estimate is 10.052350974942225
[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"))
../_images/example_notebooks_dowhy-conditional-treatment-effects_5_0.png
../_images/example_notebooks_dowhy-conditional-treatment-effects_5_1.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|W1,W0,W3,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W0,W3,W2,U) = P(y|v0,W1,W0,W3,W2)

### 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 →→{Z1,Z0})
Estimand assumption 2, Exclusion: If we remove {Z1,Z0}→{v0}, then ¬({Z1,Z0}→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|W1,W0,W3,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W0,W3,W2,U) = P(y|v0,W1,W0,W3,W2)

## Realized estimand
b: y~v0+W1+W0+W3+W2+v0*X0+v0*X1
Target units:

## Estimate
Mean value: 10.05244064596517
### Conditional Estimates
__categorical__X0  __categorical__X1
(-3.375, -0.296]   (-4.672000000000001, -1.735]     4.643267
                   (-1.735, -1.149]                 5.776182
                   (-1.149, -0.642]                 6.646150
                   (-0.642, -0.0575]                7.469222
                   (-0.0575, 2.563]                 8.647232
(-0.296, 0.281]    (-4.672000000000001, -1.735]     6.727452
                   (-1.735, -1.149]                 7.991766
                   (-1.149, -0.642]                 8.736092
                   (-0.642, -0.0575]                9.480334
                   (-0.0575, 2.563]                10.746659
(0.281, 0.793]     (-4.672000000000001, -1.735]     8.000614
                   (-1.735, -1.149]                 9.287632
                   (-1.149, -0.642]                10.041091
                   (-0.642, -0.0575]               10.772865
                   (-0.0575, 2.563]                12.043642
(0.793, 1.391]     (-4.672000000000001, -1.735]     9.309314
                   (-1.735, -1.149]                10.571383
                   (-1.149, -0.642]                11.331530
                   (-0.642, -0.0575]               12.129391
                   (-0.0575, 2.563]                13.430726
(1.391, 4.153]     (-4.672000000000001, -1.735]    11.570792
                   (-1.735, -1.149]                12.664186
                   (-1.149, -0.642]                13.506773
                   (-0.642, -0.0575]               14.199751
                   (-0.0575, 2.563]                15.592690
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|W1,W0,W3,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W0,W3,W2,U) = P(y|v0,W1,W0,W3,W2)

## Realized estimand
b: y~v0+W1+W0+W3+W2 | X0,X1
Target units: Data subset defined by a function

## Estimate
Mean value: 12.724114658038909
Effect estimates: [[12.32549879]
 [11.48621088]
 [10.29598336]
 ...
 [13.06497594]
 [12.99927179]
 [13.47068249]]

[9]:
print("True causal estimate is", data["ate"])
True causal estimate is 10.052350974942225
[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|W1,W0,W3,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W0,W3,W2,U) = P(y|v0,W1,W0,W3,W2)

## Realized estimand
b: y~v0+W1+W0+W3+W2 | X0,X1
Target units:

## Estimate
Mean value: 10.007138467469218
Effect estimates: [[ 8.27896146]
 [ 8.06912081]
 [10.5547101 ]
 ...
 [13.53650729]
 [ 8.21836869]
 [ 8.57064946]]

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|W1,W0,W3,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W0,W3,W2,U) = P(y|v0,W1,W0,W3,W2)

## Realized estimand
b: y~v0+W1+W0+W3+W2 | X0,X1
Target units: ate

## Estimate
Mean value: 9.985011865732911
Effect estimates: [[ 8.23756616]
 [ 8.02156246]
 [10.5401139 ]
 ...
 [13.5488267 ]
 [ 8.18331964]
 [ 8.52887433]]
95.0% confidence interval: [[[ 8.19389327  7.95849847 10.57995031 ... 13.63906709  8.13179248
    8.4946665 ]]

 [[ 8.33763354  8.14618487 10.74364047 ... 13.89436939  8.30171948
    8.66247911]]]

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)
[[13.43969097]
 [11.32273231]
 [12.0283356 ]
 [10.90767878]
 [10.41732177]
 [11.92877615]
 [11.96392541]
 [12.42338763]
 [10.15245793]
 [13.51158454]]

Can also retrieve the raw EconML estimator object for any further operations#

[13]:
print(dml_estimate._estimator_object)
<econml.dml.dml.DML object at 0x7fb74c6186d0>

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.988945  0.840370  1.0  0.683200  0.274016 -0.634471  1.119904   1  1
1     0.451659 -0.594991  0.0  0.495553  1.004219  0.488562 -1.078950   0  1
2     1.943625  0.504463  0.0  0.021209  0.703041  0.021460 -1.504013   0  0
3     1.044612 -0.288771  1.0  0.515555  0.876293 -0.568368 -0.872207   1  1
4    -0.108572 -0.139374  0.0  0.497722  0.038500  0.401862  0.048720   1  1
...        ...       ...  ...       ...       ...       ...       ...  .. ..
9995  1.227030 -0.075185  0.0  0.574797  0.072891 -1.636966 -0.668303   0  0
9996  1.828590 -0.249369  1.0  0.026493 -0.754906 -1.130846  0.720418   1  1
9997 -1.224322  1.712493  1.0  0.043201  0.162106  0.255226 -1.827822   1  1
9998  0.955146 -0.127441  0.0 -1.317885  0.500058  0.564298 -0.275331   0  0
9999 -0.596428  0.379681  1.0  2.032313  1.617950  0.110537 -0.797839   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|W1,W0,W3,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W0,W3,W2,U) = P(y|v0,W1,W0,W3,W2)

## Realized estimand
b: y~v0+W1+W0+W3+W2 | X0,X1
Target units: ate

## Estimate
Mean value: 0.41006300548417896
Effect estimates: [[0.45575493]
 [0.37042961]
 [0.49389833]
 ...
 [0.37099675]
 [0.41589054]
 [0.35237337]]

True causal estimate is 0.3859

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 →→{Z1,Z0})
Estimand assumption 2, Exclusion: If we remove {Z1,Z0}→{v0}, then ¬({Z1,Z0}→y)

## Realized estimand
b: y~v0+W1+W0+W3+W2 | X0,X1
Target units: Data subset defined by a function

## Estimate
Mean value: 10.418594762407347
Effect estimates: [[ 8.39708245]
 [ 8.15942937]
 [10.66260236]
 ...
 [13.56714678]
 [ 8.39174839]
 [ 8.65774773]]

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.673567  0.779109  0.979387 -0.566541  0.385187  1.0  0.809832
1    -1.700907  0.755687  0.174225  0.775343  1.567062  1.0  0.526990
2    -0.395052  0.546008  1.346170  0.109725 -0.592301  1.0  0.649820
3    -0.270270 -0.511317 -3.448955  0.246494  0.066131  1.0  0.754702
4     1.244300  1.189364  0.263170  0.615951  0.720920  1.0  0.078798
...        ...       ...       ...       ...       ...  ...       ...
9995 -0.272654 -0.198207  1.937509  0.259348  2.197771  0.0  0.068599
9996 -0.718622  2.013798 -1.253183 -1.198201  0.158790  1.0  0.767897
9997 -1.480663  1.199702 -0.150894 -0.038546 -0.866769  1.0  0.994632
9998 -0.596533  0.778277  1.117764 -1.567821 -0.151158  1.0  0.105203
9999 -1.255599 -0.747164  0.084200  0.121297  0.181659  1.0  0.120355

            W0        W1        W2        W3        W4  v0          y
0    -0.869329 -0.680114  1.080360 -1.267563 -0.302709   1   4.401948
1     1.180123 -0.935925  0.640415  0.768572 -0.267085   1  14.736772
2    -0.728879 -2.015205 -0.086730  0.477856  1.053149   1  17.097882
3     1.314418 -1.528743  0.403226  1.424989 -2.694857   1  -9.678455
4    -0.780325 -0.554654  1.704568 -1.654622 -0.163814   1  18.879374
...        ...       ...       ...       ...       ...  ..        ...
9995  0.193683 -0.620305 -0.356591  0.290428 -1.309601   0  -7.397450
9996  2.237951 -0.640805 -0.853326  1.849186  0.849366   1  25.935128
9997 -0.335791 -1.311826  0.043025 -0.086856 -1.348279   1  -1.886256
9998 -0.754909 -0.694784  0.020434 -1.793268 -0.852010   1  -0.036135
9999  0.280544 -0.893750 -0.149135 -2.949767 -0.960666   0 -17.091987

[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|W4,W1,W0,W3,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W4,W1,W0,W3,W2,U) = P(y|v0,W4,W1,W0,W3,W2)

## Realized estimand
b: y~v0+X2+X0+X4+X3+X1+W4+W1+W0+W3+W2
Target units: ate

## Estimate
Mean value: 10.514148013344004
Effect estimates: [[11.71647696]
 [14.41155434]
 [15.44497341]
 ...
 [ 8.53424195]
 [16.61085926]
 [ 7.3818374 ]]

True causal estimate is 7.558272423238339

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|W4,W1,W0,W3,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W4,W1,W0,W3,W2,U) = P(y|v0,W4,W1,W0,W3,W2)

## Realized estimand
b: y~v0+X2+X0+X4+X3+X1+W4+W1+W0+W3+W2
Target units: Data subset provided as a data frame

## Estimate
Mean value: 13.476788302090373
Effect estimates: [[13.06368204]
 [21.79332086]
 [ 8.53424195]
 [16.61085926]
 [ 7.3818374 ]]

True causal estimate is 7.558272423238339

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.80958911083216
New effect:11.78121030149439
p value:0.56

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.80958911083216
New effect:11.856197319690104

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.80958911083216
New effect:-0.01025715381028482
p value:0.40330604176138607

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.80958911083216
New effect:11.775595368050565
p value:0.33744503518931845

More refutation methods to come, especially specific to the CATE estimators.