Note
-
Download Jupyter notebook:
https://docs.doubleml.org/stable/examples/py_double_ml_cate.ipynb.
Python: Conditional Average Treatment Effects (CATEs) for IRM models#
In this simple example, we illustrate how the DoubleML package can be used to estimate conditional average treatment effects with B-splines for one or two-dimensional effects in the DoubleMLIRM model.
[1]:
import numpy as np
import pandas as pd
import doubleml as dml
from doubleml.datasets import make_heterogeneous_data
Data#
We define a data generating process to create synthetic data to compare the estimates to the true effect. The data generating process is based on the Monte Carlo simulation from Oprescu et al. (2019).
The documentation of the data generating process can be found here.
One-dimensional Example#
We start with an one-dimensional effect and create our training data. In this example the true effect depends only the first covariate \(X_0\) and takes the following form
The generated dictionary also contains a callable with key treatment_effect
to calculate the true treatment effect for new observations.
[2]:
np.random.seed(42)
data_dict = make_heterogeneous_data(
n_obs=2000,
p=10,
support_size=5,
n_x=1,
binary_treatment=True,
)
treatment_effect = data_dict['treatment_effect']
data = data_dict['data']
print(data.head())
y d X_0 X_1 X_2 X_3 X_4 X_5 \
0 4.803300 1.0 0.259828 0.886086 0.895690 0.297287 0.229994 0.411304
1 5.655547 1.0 0.824350 0.396992 0.156317 0.737951 0.360475 0.671271
2 1.878402 0.0 0.988421 0.977280 0.793818 0.659423 0.577807 0.866102
3 6.941440 1.0 0.427486 0.330285 0.564232 0.850575 0.201528 0.934433
4 1.703049 1.0 0.016200 0.818380 0.040139 0.889913 0.991963 0.294067
X_6 X_7 X_8 X_9
0 0.240532 0.672384 0.826065 0.673092
1 0.270644 0.081230 0.992582 0.156202
2 0.289440 0.467681 0.619390 0.411190
3 0.689088 0.823273 0.556191 0.779517
4 0.210319 0.765363 0.253026 0.865562
First, define the DoubleMLData
object.
[3]:
data_dml_base = dml.DoubleMLData(
data,
y_col='y',
d_cols='d'
)
Next, define the learners for the nuisance functions and fit the IRM Model. Remark that linear learners would usually be optimal due to the data generating process.
[4]:
# First stage estimation
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
randomForest_reg = RandomForestRegressor(n_estimators=500)
randomForest_class = RandomForestClassifier(n_estimators=500)
np.random.seed(42)
dml_irm = dml.DoubleMLIRM(data_dml_base,
ml_g=randomForest_reg,
ml_m=randomForest_class,
trimming_threshold=0.05,
n_folds=5)
print("Training IRM Model")
dml_irm.fit()
print(dml_irm.summary)
Training IRM Model
coef std err t P>|t| 2.5 % 97.5 %
d 4.475569 0.0408 109.695045 0.0 4.395603 4.555536
To estimate the CATE, we rely on the best-linear-predictor of the linear score as in Semenova et al. (2021) To approximate the target function \(\theta_0(x)\) with a linear form, we have to define a data frame of basis functions. Here, we rely on patsy to construct a suitable basis of B-splines.
[5]:
import patsy
design_matrix = patsy.dmatrix("bs(x, df=5, degree=2)", {"x": data["X_0"]})
spline_basis = pd.DataFrame(design_matrix)
To estimate the parameters to calculate the CATE estimate call the cate()
method and supply the dataframe of basis elements.
[6]:
cate = dml_irm.cate(spline_basis)
print(cate)
================== DoubleMLBLP Object ==================
------------------ Fit summary ------------------
coef std err t P>|t| [0.025 0.975]
0 0.691423 0.160438 4.309605 1.715075e-05 0.376780 1.006066
1 2.303007 0.267099 8.622301 1.314071e-17 1.779185 2.826829
2 4.904315 0.171709 28.561819 1.047375e-150 4.567568 5.241063
3 4.755688 0.205656 23.124465 5.235501e-105 4.352365 5.159011
4 3.745881 0.208922 17.929552 9.128273e-67 3.336153 4.155610
5 4.314341 0.224546 19.213635 1.278303e-75 3.873972 4.754710
To obtain the confidence intervals for the CATE, we have to call the confint()
method and a supply a dataframe of basis elements. This could be the same basis as for fitting the CATE model or a new basis to e.g. evaluate the CATE model on a grid. Here, we will evaluate the CATE on a grid from 0.1 to 0.9 to plot the final results. Further, we construct uniform confidence intervals by setting the option joint
and providing a number of bootstrap repetitions n_rep_boot
.
[7]:
new_data = {"x": np.linspace(0.1, 0.9, 100)}
spline_grid = pd.DataFrame(patsy.build_design_matrices([design_matrix.design_info], new_data)[0])
df_cate = cate.confint(spline_grid, level=0.95, joint=True, n_rep_boot=2000)
print(df_cate)
2.5 % effect 97.5 %
0 2.070552 2.333655 2.596758
1 2.185984 2.453279 2.720573
2 2.298076 2.570936 2.843796
3 2.407558 2.686627 2.965696
4 2.515031 2.800351 3.085671
.. ... ... ...
95 4.417640 4.704814 4.991988
96 4.424292 4.705354 4.986417
97 4.433750 4.708235 4.982720
98 4.445476 4.713457 4.981438
99 4.458784 4.721018 4.983253
[100 rows x 3 columns]
Finally, we can plot our results and compare them with the true effect.
[8]:
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = 10., 7.5
df_cate['x'] = new_data['x']
df_cate['true_effect'] = treatment_effect(new_data["x"].reshape(-1, 1))
fig, ax = plt.subplots()
ax.plot(df_cate['x'],df_cate['effect'], label='Estimated Effect')
ax.plot(df_cate['x'],df_cate['true_effect'], color="green", label='True Effect')
ax.fill_between(df_cate['x'], df_cate['2.5 %'], df_cate['97.5 %'], color='b', alpha=.3, label='Confidence Interval')
plt.legend()
plt.title('CATE')
plt.xlabel('x')
_ = plt.ylabel('Effect and 95%-CI')
If the effect is not one-dimensional, the estimate still corresponds to the projection of the true effect on the basis functions.
Two-Dimensional Example#
It is also possible to estimate multi-dimensional conditional effects. We will use a similar data generating process but now the effect depends on the first two covariates \(X_0\) and \(X_1\) and takes the following form
With the argument n_x=2
we can specify set the effect to be two-dimensional.
[9]:
np.random.seed(42)
data_dict = make_heterogeneous_data(
n_obs=5000,
p=10,
support_size=5,
n_x=2,
binary_treatment=True,
)
treatment_effect = data_dict['treatment_effect']
data = data_dict['data']
print(data.head())
y d X_0 X_1 X_2 X_3 X_4 X_5 \
0 1.286203 1.0 0.014080 0.006958 0.240127 0.100807 0.260211 0.177043
1 0.416899 1.0 0.152148 0.912230 0.892796 0.653901 0.672234 0.005339
2 2.087634 1.0 0.344787 0.893649 0.291517 0.562712 0.099731 0.921956
3 7.508433 1.0 0.619351 0.232134 0.000943 0.757151 0.985207 0.809913
4 0.567695 0.0 0.477130 0.447624 0.775191 0.526769 0.316717 0.258158
X_6 X_7 X_8 X_9
0 0.028520 0.909304 0.008223 0.736082
1 0.984872 0.877833 0.895106 0.659245
2 0.140770 0.224897 0.558134 0.764093
3 0.460207 0.903767 0.409848 0.524934
4 0.037747 0.583195 0.229961 0.148134
As univariate example estimate the IRM Model.
[10]:
data_dml_base = dml.DoubleMLData(
data,
y_col='y',
d_cols='d'
)
[11]:
# First stage estimation
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
randomForest_reg = RandomForestRegressor(n_estimators=500)
randomForest_class = RandomForestClassifier(n_estimators=500)
np.random.seed(42)
dml_irm = dml.DoubleMLIRM(data_dml_base,
ml_g=randomForest_reg,
ml_m=randomForest_class,
trimming_threshold=0.05,
n_folds=5)
print("Training IRM Model")
dml_irm.fit()
print(dml_irm.summary)
Training IRM Model
coef std err t P>|t| 2.5 % 97.5 %
d 4.547039 0.038845 117.056745 0.0 4.470904 4.623173
As above, we will rely on the patsy package to construct the basis elements. In the two-dimensional case, we will construct a tensor product of B-splines (for more information see here).
[12]:
design_matrix = patsy.dmatrix("te(bs(x_0, df=7, degree=3), bs(x_1, df=7, degree=3))", {"x_0": data["X_0"], "x_1": data["X_1"]})
spline_basis = pd.DataFrame(design_matrix)
cate = dml_irm.cate(spline_basis)
print(cate)
================== DoubleMLBLP Object ==================
------------------ Fit summary ------------------
coef std err t P>|t| [0.025 0.975]
0 2.805774 0.105942 26.483944 1.171868e-144 2.598080 3.013469
1 -1.115972 0.865284 -1.289718 1.972088e-01 -2.812311 0.580368
2 0.462979 0.856117 0.540789 5.886771e-01 -1.215389 2.141347
3 2.308774 0.755717 3.055078 2.262000e-03 0.827234 3.790314
4 0.575810 0.763219 0.754448 4.506159e-01 -0.920439 2.072058
5 -3.338603 0.960074 -3.477443 5.105751e-04 -5.220773 -1.456432
6 -4.994377 1.033224 -4.833781 1.380170e-06 -7.019953 -2.968800
7 -6.404411 1.003965 -6.379117 1.943465e-10 -8.372628 -4.436194
8 -2.644985 0.908620 -2.910991 3.618922e-03 -4.426283 -0.863687
9 3.753393 0.930417 4.034097 5.563851e-05 1.929363 5.577422
10 -0.018508 0.787396 -0.023505 9.812484e-01 -1.562153 1.525138
11 1.577813 0.827438 1.906864 5.659605e-02 -0.044334 3.199959
12 -1.070751 1.027329 -1.042266 2.973392e-01 -3.084771 0.943270
13 -2.291008 1.135396 -2.017805 4.366541e-02 -4.516888 -0.065128
14 -2.607264 1.040445 -2.505913 1.224539e-02 -4.646997 -0.567531
15 0.241678 0.762237 0.317064 7.512081e-01 -1.252644 1.736001
16 1.085395 0.774253 1.401861 1.610195e-01 -0.432484 2.603273
17 3.742375 0.665554 5.622949 1.980256e-08 2.437594 5.047156
18 1.384928 0.673586 2.056052 3.982986e-02 0.064400 2.705456
19 -1.506050 0.842444 -1.787716 7.388298e-02 -3.157613 0.145513
20 -2.315310 0.896758 -2.581868 9.855199e-03 -4.073352 -0.557267
21 -2.806554 0.779350 -3.601149 3.199206e-04 -4.334425 -1.278683
22 1.945881 0.772291 2.519622 1.177933e-02 0.431848 3.459913
23 2.189248 0.805962 2.716316 6.624224e-03 0.609205 3.769290
24 4.374862 0.693632 6.307176 3.089064e-10 3.015035 5.734689
25 2.134542 0.666865 3.200863 1.378828e-03 0.827192 3.441893
26 1.709596 0.876080 1.951415 5.106401e-02 -0.007909 3.427101
27 -1.233029 0.945417 -1.304217 1.922201e-01 -3.086464 0.620407
28 -1.378588 0.907702 -1.518767 1.288850e-01 -3.158087 0.400910
29 4.060417 0.983896 4.126875 3.737694e-05 2.131544 5.989291
30 4.063700 0.973262 4.175342 3.026518e-05 2.155676 5.971724
31 6.076596 0.840630 7.228621 5.624482e-13 4.428588 7.724603
32 3.840673 0.818590 4.691814 2.780887e-06 2.235873 5.445473
33 2.584928 1.056953 2.445642 1.449406e-02 0.512832 4.657024
34 -1.847555 1.182393 -1.562557 1.182208e-01 -4.165569 0.470458
35 -0.429705 1.156567 -0.371535 7.102553e-01 -2.697089 1.837680
36 7.039036 0.978554 7.193300 7.270694e-13 5.120636 8.957437
37 5.187664 1.021013 5.080900 3.894609e-07 3.186027 7.189302
38 7.151063 0.833117 8.583508 1.216130e-17 5.517785 8.784341
39 6.733644 0.913285 7.372989 1.945402e-13 4.943200 8.524088
40 2.381603 1.148950 2.072852 3.823769e-02 0.129152 4.634055
41 4.440747 1.263672 3.514160 4.450926e-04 1.963389 6.918104
42 1.732067 1.166079 1.485377 1.375077e-01 -0.553965 4.018099
43 10.068514 0.937857 10.735656 1.355699e-26 8.229897 11.907130
44 3.734635 1.133204 3.295642 9.888863e-04 1.513052 5.956217
45 9.197920 0.814410 11.293960 3.193069e-29 7.601314 10.794526
46 5.367181 0.825140 6.504569 8.560545e-11 3.749540 6.984821
47 5.925660 1.023160 5.791529 7.405400e-09 3.919814 7.931507
48 1.301737 1.049959 1.239799 2.151087e-01 -0.756647 3.360122
49 1.237341 1.039660 1.190140 2.340485e-01 -0.800854 3.275535
Finally, we create a new grid to evaluate and plot the effects.
[13]:
grid_size = 100
x_0 = np.linspace(0.1, 0.9, grid_size)
x_1 = np.linspace(0.1, 0.9, grid_size)
x_0, x_1 = np.meshgrid(x_0, x_1)
new_data = {"x_0": x_0.ravel(), "x_1": x_1.ravel()}
[14]:
spline_grid = pd.DataFrame(patsy.build_design_matrices([design_matrix.design_info], new_data)[0])
df_cate = cate.confint(spline_grid, joint=True, n_rep_boot=2000)
print(df_cate)
2.5 % effect 97.5 %
0 1.671690 2.379626 3.087561
1 1.681521 2.366950 3.052380
2 1.698509 2.357170 3.015831
3 1.720559 2.350208 2.979857
4 1.745444 2.345989 2.946533
... ... ... ...
9995 3.716387 4.506644 5.296901
9996 3.831741 4.661388 5.491034
9997 3.939250 4.811696 5.684142
9998 4.041925 4.955701 5.869477
9999 4.142382 5.091535 6.040688
[10000 rows x 3 columns]
[15]:
import plotly.graph_objects as go
grid_array = np.array(list(zip(x_0.ravel(), x_1.ravel())))
true_effect = treatment_effect(grid_array).reshape(x_0.shape)
effect = np.asarray(df_cate['effect']).reshape(x_0.shape)
lower_bound = np.asarray(df_cate['2.5 %']).reshape(x_0.shape)
upper_bound = np.asarray(df_cate['97.5 %']).reshape(x_0.shape)
fig = go.Figure(data=[
go.Surface(x=x_0,
y=x_1,
z=true_effect),
go.Surface(x=x_0,
y=x_1,
z=upper_bound, showscale=False, opacity=0.4,colorscale='purp'),
go.Surface(x=x_0,
y=x_1,
z=lower_bound, showscale=False, opacity=0.4,colorscale='purp'),
])
fig.update_traces(contours_z=dict(show=True, usecolormap=True,
highlightcolor="limegreen", project_z=True))
fig.update_layout(scene = dict(
xaxis_title='X_0',
yaxis_title='X_1',
zaxis_title='Effect'),
width=700,
margin=dict(r=20, b=10, l=10, t=10))
fig.show()