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  1.389948  1.751782  1.0  0.277274  0.459921  0.026215  0  1  20.099662
1  1.648881  0.355457  1.0  0.946902  0.648256 -1.071687  1  3  40.655806
2  1.646793  0.322880  1.0  0.749631  1.973935  0.525838  0  0  30.160862
3 -0.668594  0.124942  0.0  0.201486 -0.444083  1.956724  0  0   6.604685
4 -1.197690 -0.513994  1.0  0.266971 -0.337739 -0.072390  2  2  27.474367

            y
0  331.492776
1  576.802319
2  424.985944
3   63.158050
4  188.978847
True causal estimate is 13.457118235410977
[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|W0,W3,W2,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W3,W2,W1,U) = P(y|v0,W0,W3,W2,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 →→{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|W0,W3,W2,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W3,W2,W1,U) = P(y|v0,W0,W3,W2,W1)

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

## Estimate
Mean value: 13.456976757055791
### Conditional Estimates
__categorical__X1              __categorical__X0
(-3.0269999999999997, 0.0677]  (-3.098, -0.0464]     7.869591
                               (-0.0464, 0.536]      9.489400
                               (0.536, 1.052]       10.535905
                               (1.052, 1.637]       11.639891
                               (1.637, 4.509]       13.492587
(0.0677, 0.668]                (-3.098, -0.0464]     9.572119
                               (-0.0464, 0.536]     11.299742
                               (0.536, 1.052]       12.412045
                               (1.052, 1.637]       13.447886
                               (1.637, 4.509]       15.193414
(0.668, 1.151]                 (-3.098, -0.0464]    10.694397
                               (-0.0464, 0.536]     12.406668
                               (0.536, 1.052]       13.474619
                               (1.052, 1.637]       14.492004
                               (1.637, 4.509]       16.309308
(1.151, 1.733]                 (-3.098, -0.0464]    11.822768
                               (-0.0464, 0.536]     13.454937
                               (0.536, 1.052]       14.484410
                               (1.052, 1.637]       15.607954
                               (1.637, 4.509]       17.247350
(1.733, 4.475]                 (-3.098, -0.0464]    13.470358
                               (-0.0464, 0.536]     15.212844
                               (0.536, 1.052]       16.311794
                               (1.052, 1.637]       17.292626
                               (1.637, 4.509]       19.170564
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,W3,W2,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W3,W2,W1,U) = P(y|v0,W0,W3,W2,W1)

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

## Estimate
Mean value: 15.232323464230225
Effect estimates: [[16.35792307]
 [13.92164385]
 [13.84853653]
 ...
 [11.76471321]
 [15.13662187]
 [13.63640233]]

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

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

## Estimate
Mean value: 13.40997827165657
Effect estimates: [[16.37082847]
 [13.96019432]
 [13.88754709]
 ...
 [14.4139776 ]
 [ 9.16664745]
 [13.67048607]]

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

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

## Estimate
Mean value: 13.423007775922088
Effect estimates: [[16.33979429]
 [13.99270365]
 [13.92160102]
 ...
 [14.39642287]
 [ 9.23691436]
 [13.70169271]]
95.0% confidence interval: [[[16.40760595 14.09283523 14.01985701 ... 14.44438125  9.2115802
   13.80544371]]

 [[16.65749553 14.30964462 14.23819827 ... 14.64992264  9.45546334
   13.99843057]]]

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.64654058]
 [11.89127943]
 [12.882126  ]
 [10.89714313]
 [12.31414188]
 [12.58974454]
 [12.45612383]
 [12.51577482]
 [11.89926989]
 [10.14824073]]

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

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

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.365348 -1.489642  0.0 -2.155866 -0.339055  1.707948 -0.742730   0  0
1     0.942017 -1.118291  0.0  1.136966  0.387619 -0.271633 -1.091294   1  1
2     2.316352  1.863818  0.0 -1.327931 -1.192637 -0.237956  0.690746   0  0
3    -1.094361  0.596063  0.0  1.667407 -1.957329 -0.210338  0.073792   0  1
4     1.074975  0.788884  0.0 -0.972693  0.197499 -0.322668  0.440109   0  1
...        ...       ...  ...       ...       ...       ...       ...  .. ..
9995  2.122412 -0.115294  0.0  0.140727 -0.577960 -0.331180  0.436802   0  1
9996 -0.874360 -0.146047  0.0 -2.081466 -1.421407  0.091710 -0.750433   0  0
9997  1.376209 -1.331930  0.0 -0.305968 -0.381903  2.044766 -0.302418   1  1
9998  0.964367  0.599481  0.0  0.035603 -1.131292  0.204689  0.109697   0  1
9999  1.420323 -0.247298  1.0 -1.320424 -1.112439 -1.741890 -0.471134   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,W3,W2,W1])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W0,W3,W2,W1,U) = P(y|v0,W0,W3,W2,W1)

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

## Estimate
Mean value: 0.3428350903420822
Effect estimates: [[0.21178099]
 [0.29971609]
 [0.59627033]
 ...
 [0.30238201]
 [0.4360042 ]
 [0.38978362]]

True causal estimate is 0.3304

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+W0+W3+W2+W1 | X1,X0
Target units: Data subset defined by a function

## Estimate
Mean value: 13.655872005875057
Effect estimates: [[16.36018199]
 [14.01606711]
 [13.9457262 ]
 ...
 [14.48836513]
 [ 9.42696214]
 [13.74163463]]

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.369087 -0.859849  2.778047  1.816865  0.929263  1.0  0.929836
1     0.983202  0.504724  0.062642 -0.680262  0.905371  0.0  0.304379
2     0.705779 -0.676199  0.709269 -0.288758  1.115293  1.0  0.651446
3     1.228115 -0.906712  1.247130 -0.531836  0.843711  1.0  0.383913
4    -1.113011 -1.457240 -0.900143 -0.695445  2.509587  0.0  0.789069
...        ...       ...       ...       ...       ...  ...       ...
9995 -0.470038 -0.612368 -0.767987  2.084621  1.214764  1.0  0.046123
9996  0.827412 -0.267510  0.878308 -1.274637  0.540539  1.0  0.750163
9997  1.545613  0.005295  0.365863 -0.338149  2.283727  0.0  0.889457
9998 -0.137655 -1.414276 -0.840491 -1.316012  1.645392  1.0  0.476192
9999  0.614455 -0.027337  0.550950  0.603163 -0.621691  1.0  0.449623

            W0        W1        W2        W3        W4  v0          y
0    -0.584314 -0.645818  0.273595 -1.059159 -0.206934   1  22.930136
1    -0.520510  1.497755 -0.053756 -1.932104 -0.770150   0   2.400285
2    -1.071199  1.574762  0.912342 -1.114490 -0.575235   1  19.204991
3    -0.658392 -0.969398  1.187320 -1.787183  0.497403   1  11.991121
4    -2.101842  0.393741  1.271047 -0.191968 -1.046403   0   2.167690
...        ...       ...       ...       ...       ...  ..        ...
9995 -3.656408  0.646836 -0.337807 -2.966192 -1.757441   0  -9.891405
9996 -0.246921  2.973657  0.163503 -0.114932  0.788750   1  17.491909
9997 -1.890949  0.413400 -0.794034 -1.786689 -1.498221   0  -8.594221
9998  0.984867  1.273676 -1.537528 -1.769449 -0.948794   1   1.137030
9999 -1.808493  1.399741  0.690292 -1.426453 -0.841369   1  14.652876

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

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

## Estimate
Mean value: 14.258286349956952
Effect estimates: [[25.02218403]
 [13.22452994]
 [13.13108479]
 ...
 [22.7752059 ]
 [ 6.27402373]
 [13.90645862]]

True causal estimate is 12.484530355804123

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

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

## Estimate
Mean value: 16.02652794715638
Effect estimates: [[26.2442828 ]
 [10.93266869]
 [22.7752059 ]
 [ 6.27402373]
 [13.90645862]]

True causal estimate is 12.484530355804123

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.924038484111337
New effect:11.942372454700283
p value:0.52

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.924038484111337
New effect:12.016614708154487

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.924038484111337
New effect:-0.013454183183628255
p value:0.30010391507421597

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.924038484111337
New effect:11.951188846631586
p value:0.27783726571073336

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