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.789780  0.048623  0.0  0.671955 -1.070985  1.030736  1  3  18.583112
1  0.993418  0.490580  0.0  0.847466  0.089820  0.394096  3  1  24.969254
2 -1.255780 -0.597638  0.0  0.306126  0.485490  1.568325  3  0  23.448805
3  1.541588  0.245405  0.0  0.261690 -0.980028 -0.058530  1  2   9.716008
4 -0.097713 -0.905954  0.0  0.262759 -1.254197  1.092632  1  0   7.789164

            y
0  263.864773
1  431.269214
2   41.195718
3  180.277384
4   36.238149
True causal estimate is 10.254675233254078
[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,W3,W0,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W3,W0,W2,U) = P(y|v0,W1,W3,W0,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 →→{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|W1,W3,W0,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W3,W0,W2,U) = P(y|v0,W1,W3,W0,W2)

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

## Estimate
Mean value: 10.254739595051774
### Conditional Estimates
__categorical__X1  __categorical__X0
(-4.796, -0.881]   (-3.327, -0.747]     -3.294772
                   (-0.747, -0.15]       0.399036
                   (-0.15, 0.347]        2.892257
                   (0.347, 0.946]        5.155100
                   (0.946, 4.115]        9.128284
(-0.881, -0.297]   (-3.327, -0.747]      1.169153
                   (-0.747, -0.15]       5.058693
                   (-0.15, 0.347]        7.580121
                   (0.347, 0.946]        9.870173
                   (0.946, 4.115]       13.422064
(-0.297, 0.225]    (-3.327, -0.747]      4.196739
                   (-0.747, -0.15]       7.858165
                   (-0.15, 0.347]       10.299285
                   (0.347, 0.946]       12.591900
                   (0.946, 4.115]       16.246202
(0.225, 0.816]     (-3.327, -0.747]      7.064724
                   (-0.747, -0.15]      10.733194
                   (-0.15, 0.347]       13.109040
                   (0.347, 0.946]       15.407973
                   (0.946, 4.115]       19.197126
(0.816, 3.765]     (-3.327, -0.747]     11.624585
                   (-0.747, -0.15]      15.329720
                   (-0.15, 0.347]       17.747543
                   (0.347, 0.946]       19.798184
                   (0.946, 4.115]       23.795562
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,W3,W0,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W3,W0,W2,U) = P(y|v0,W1,W3,W0,W2)

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

## Estimate
Mean value: 16.67201204716318
Effect estimates: [[18.33400953]
 [13.63561248]
 [32.95431024]
 ...
 [10.8086604 ]
 [11.15060283]
 [20.29906355]]

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

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

## Estimate
Mean value: 10.262246833130455
Effect estimates: [[14.02048285]
 [17.51188739]
 [ 0.5838172 ]
 ...
 [ 9.7715035 ]
 [14.362032  ]
 [-2.99648652]]

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

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

## Estimate
Mean value: 10.247108476258715
Effect estimates: [[13.98326371]
 [17.46758251]
 [ 0.61253181]
 ...
 [ 9.81977586]
 [14.34337002]
 [-2.97554046]]
95.0% confidence interval: [[[14.09036649 17.63044909  0.13748918 ...  9.51927876 14.48401857
   -3.72657972]]

 [[14.55738376 18.26313893  0.68930835 ... 10.5112045  14.95330932
   -2.89134948]]]

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.38702862]
 [12.22207426]
 [17.4494481 ]
 [15.04647811]
 [15.11124775]
 [10.80267833]
 [12.38040651]
 [17.38715997]
 [12.98121809]
 [11.95966652]]

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

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

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.838229  0.097266  1.0  0.641414  1.673684 -0.213822 -0.350048   1  1
1    -0.529283  0.549490  0.0 -0.257200 -0.343666  0.603695 -0.782082   0  0
2     0.353487 -0.376465  0.0  0.667085  0.709624 -0.837459 -1.074170   1  1
3    -0.070158 -0.980965  0.0  1.033196  0.385868 -0.871454 -1.166392   0  0
4     1.310776  0.534937  0.0 -2.057763  1.188065 -1.266718 -1.237925   0  0
...        ...       ...  ...       ...       ...       ...       ...  .. ..
9995 -0.988840 -0.682079  0.0  1.196170 -0.067014  1.831027 -0.914099   1  1
9996 -1.335523  0.216664  0.0 -3.264795 -0.574689 -0.091977 -1.551812   0  0
9997 -0.284182 -1.111834  0.0 -0.826057  0.775565  0.598185 -0.226678   1  1
9998  1.680626  1.235197  0.0  0.154737  0.296073  1.489453 -0.116727   1  1
9999  1.426363  1.782950  0.0  0.716981  2.386219 -0.385721 -0.536957   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,W3,W0,W2])
d[v₀]
Estimand assumption 1, Unconfoundedness: If U→{v0} and U→y then P(y|v0,W1,W3,W0,W2,U) = P(y|v0,W1,W3,W0,W2)

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

## Estimate
Mean value: 0.2764284308347947
Effect estimates: [[0.17510811]
 [0.2353241 ]
 [0.31482178]
 ...
 [0.19879879]
 [0.5596808 ]
 [0.54851127]]

True causal estimate is 0.3388

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

## Estimate
Mean value: 11.643545820618844
Effect estimates: [[14.02495702]
 [17.40303484]
 [18.50963563]
 ...
 [ 2.21747867]
 [14.44572154]
 [-2.32881803]]

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.822084 -1.432822 -1.651705  1.026500 -0.011354  0.0  0.449272
1    -1.324517  1.763757 -1.943600  0.831940 -0.112171  1.0  0.777888
2    -0.547622 -0.045342 -1.087431 -0.251451  1.009945  1.0  0.617436
3    -1.221734  0.743682 -2.258666  1.238082  0.830887  0.0  0.898296
4    -0.534760  1.446037 -1.682900  1.745352 -0.163834  1.0  0.835362
...        ...       ...       ...       ...       ...  ...       ...
9995 -0.395432 -0.364258  0.275803  0.836851  0.241545  1.0  0.872138
9996 -0.769243  0.719430 -1.002376  0.613841  0.561358  1.0  0.978336
9997 -0.834666 -1.492056 -0.729744  0.340851  0.320197  0.0  0.529277
9998 -1.854424 -1.408596 -3.601367  0.780788  0.449757  1.0  0.388517
9999 -1.311915 -0.146299 -1.313614  1.673926 -1.587524  0.0  0.287262

            W0        W1        W2        W3        W4  v0          y
0    -1.195161  1.697060  1.097874 -1.642364  0.176369   1   7.647487
1    -0.928608  0.172719  0.398104 -2.014841  0.336926   1   1.887929
2    -0.535334  0.250091 -0.481064  0.242292  1.684539   1  14.481385
3    -0.289308  2.709293 -1.008313 -0.868622 -2.459526   1  11.990847
4    -0.063303 -0.079646  3.238831 -0.243752 -0.262899   1  12.827985
...        ...       ...       ...       ...       ...  ..        ...
9995 -1.434182  0.170555 -1.081243  0.770650  2.145111   1  14.616646
9996  0.134426  1.253381  0.612700 -1.432981  0.085526   1  12.989376
9997 -2.548825  2.817328 -0.201222 -2.971637 -1.313165   0  -4.776117
9998 -3.680357  2.118004  0.036917 -1.726676  1.355818   1  -7.991487
9999 -2.284869 -1.048796 -1.273857 -0.282567  1.314460   0  -7.665970

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

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

## Estimate
Mean value: 7.775587419007136
Effect estimates: [[10.40684069]
 [ 9.64079465]
 [12.59307897]
 ...
 [ 5.8680086 ]
 [-4.58300286]
 [-1.89793008]]

True causal estimate is 4.237934616738015

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

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

## Estimate
Mean value: 5.184298709396508
Effect estimates: [[11.57889993]
 [14.95551796]
 [ 5.8680086 ]
 [-4.58300286]
 [-1.89793008]]

True causal estimate is 4.237934616738015

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:13.6727406256968
New effect:13.542385196593823
p value:0.14

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:13.6727406256968
New effect:13.523263033975653

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:13.6727406256968
New effect:-0.03416040359793518
p value:0.3172535100869517

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:13.6727406256968
New effect:13.56197016827997
p value:0.07595331289151241

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