Python: Conditional Average Treatment Effects (CATEs) for PLR 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 DoubleMLPLR model.

[1]:
import numpy as np
import pandas as pd
import doubleml as dml

from doubleml.irm.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

\[\theta_0(X) = \exp(2X_0) + 3\sin(4X_0).\]

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,
)
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  \
0  1.564451  0.241064  0.259828  0.886086  0.895690  0.297287  0.229994
1  1.114570  0.040912  0.824350  0.396992  0.156317  0.737951  0.360475
2  8.901013  1.392623  0.988421  0.977280  0.793818  0.659423  0.577807
3 -1.315155 -0.551317  0.427486  0.330285  0.564232  0.850575  0.201528
4  1.314625  0.683487  0.016200  0.818380  0.040139  0.889913  0.991963

        X_5       X_6       X_7       X_8       X_9
0  0.411304  0.240532  0.672384  0.826065  0.673092
1  0.671271  0.270644  0.081230  0.992582  0.156202
2  0.866102  0.289440  0.467681  0.619390  0.411190
3  0.934433  0.689088  0.823273  0.556191  0.779517
4  0.294067  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 PLR 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
ml_l = RandomForestRegressor(n_estimators=500)
ml_m = RandomForestRegressor(n_estimators=500)

np.random.seed(42)

dml_plr = dml.DoubleMLPLR(data_dml_base,
                          ml_l=ml_l,
                          ml_m=ml_m,
                          n_folds=5)
print("Training PLR Model")
dml_plr.fit()

print(dml_plr.summary)
Training PLR Model
       coef   std err          t  P>|t|    2.5 %    97.5 %
d  4.376718  0.044051  99.355251    0.0  4.29038  4.463057

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_plr.cate(spline_basis)
print(cate)
================== DoubleMLBLP Object ==================

------------------ Fit summary ------------------
       coef   std err          t          P>|t|    [0.025    0.975]
0  1.227765  0.141646   8.667860   4.403175e-18  0.950144  1.505385
1  1.589832  0.237704   6.688286   2.257998e-11  1.123940  2.055723
2  4.193802  0.156496  26.798090  3.401140e-158  3.887075  4.500530
3  4.046428  0.180496  22.418368  2.605646e-111  3.692662  4.400194
4  3.297555  0.180014  18.318281   5.915195e-75  2.944733  3.650376
5  3.798159  0.183654  20.681029   5.133365e-95  3.438203  4.158115

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.193938  2.423092  2.652247
1   2.284407  2.516043  2.747679
2   2.372329  2.608442  2.844556
3   2.458517  2.700290  2.942062
4   2.543665  2.791586  3.039506
..       ...       ...       ...
95  4.500229  4.740542  4.980855
96  4.508529  4.743437  4.978346
97  4.519170  4.748241  4.977312
98  4.531691  4.754953  4.978215
99  4.545504  4.763573  4.981642

[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')
../_images/examples_py_double_ml_cate_plr_17_0.png

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

\[\theta_0(X) = \exp(2X_0) + 3\sin(4X_1).\]

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,
)
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  \
0 -0.359307 -0.479722  0.014080  0.006958  0.240127  0.100807  0.260211
1  0.578557 -0.587135  0.152148  0.912230  0.892796  0.653901  0.672234
2  1.479882  0.172083  0.344787  0.893649  0.291517  0.562712  0.099731
3  4.468072  0.480579  0.619351  0.232134  0.000943  0.757151  0.985207
4  5.949866  0.974213  0.477130  0.447624  0.775191  0.526769  0.316717

        X_5       X_6       X_7       X_8       X_9
0  0.177043  0.028520  0.909304  0.008223  0.736082
1  0.005339  0.984872  0.877833  0.895106  0.659245
2  0.921956  0.140770  0.224897  0.558134  0.764093
3  0.809913  0.460207  0.903767  0.409848  0.524934
4  0.258158  0.037747  0.583195  0.229961  0.148134

As univariate example estimate the PLR Model.

[10]:
data_dml_base = dml.DoubleMLData(
    data,
    y_col='y',
    d_cols='d'
)
[11]:
# First stage estimation
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
ml_l = RandomForestRegressor(n_estimators=500)
ml_m = RandomForestRegressor(n_estimators=500)

np.random.seed(42)

dml_plr = dml.DoubleMLPLR(data_dml_base,
                          ml_l=ml_l,
                          ml_m=ml_m,
                          n_folds=5)
print("Training PLR Model")
dml_plr.fit()

print(dml_plr.summary)
Training PLR Model
       coef   std err          t  P>|t|     2.5 %    97.5 %
d  4.469769  0.049714  89.910059    0.0  4.372332  4.567206

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_plr.cate(spline_basis)
print(cate)
================== DoubleMLBLP Object ==================

------------------ Fit summary ------------------
        coef   std err          t         P>|t|    [0.025     0.975]
0   2.784364  0.172165  16.172659  7.862966e-59  2.446927   3.121801
1  -3.349379  0.856298  -3.911464  9.173829e-05 -5.027692  -1.671066
2   3.042957  0.734580   4.142444  3.436243e-05  1.603206   4.482707
3   1.746359  0.714919   2.442737  1.457637e-02  0.345143   3.147575
4   1.993173  0.676532   2.946165  3.217412e-03  0.667196   3.319151
5  -3.870106  0.867564  -4.460888  8.162072e-06 -5.570500  -2.169712
6  -5.432466  0.935501  -5.807011  6.359778e-09 -7.266015  -3.598918
7  -7.381083  0.948526  -7.781630  7.159573e-15 -9.240160  -5.522005
8  -0.585628  0.799466  -0.732525  4.638482e-01 -2.152552   0.981295
9  -0.213555  0.824536  -0.259001  7.956349e-01 -1.829616   1.402505
10  1.921184  0.728005   2.638971  8.315804e-03  0.494321   3.348047
11  0.593517  0.704848   0.842051  3.997596e-01 -0.787959   1.974993
12 -0.883050  0.889516  -0.992731  3.208408e-01 -2.626470   0.860369
13 -1.229766  0.981063  -1.253504  2.100225e-01 -3.152615   0.693082
14 -2.131914  0.766741  -2.780487  5.427747e-03 -3.634699  -0.629129
15  0.025487  0.772944   0.032974  9.736956e-01 -1.489455   1.540429
16  2.875404  0.707201   4.065892  4.784911e-05  1.489315   4.261493
17  1.881706  0.639198   2.943857  3.241495e-03  0.628902   3.134510
18  2.662696  0.615849   4.323615  1.534934e-05  1.455653   3.869738
19 -1.976368  0.749370  -2.637372  8.355112e-03 -3.445107  -0.507630
20 -1.968030  0.759087  -2.592626  9.524619e-03 -3.455813  -0.480246
21 -4.153728  0.635889  -6.532157  6.482902e-11 -5.400047  -2.907408
22  0.221643  0.790395   0.280421  7.791546e-01 -1.327503   1.770790
23  4.454305  0.766148   5.813894  6.103606e-09  2.952682   5.955929
24  2.326543  0.711849   3.268310  1.081919e-03  0.931345   3.721742
25  3.378428  0.683428   4.943355  7.678954e-07  2.038933   4.717923
26 -0.001289  0.809751  -0.001592  9.987296e-01 -1.588373   1.585794
27 -1.175606  0.887832  -1.324132  1.854593e-01 -2.915724   0.564512
28 -1.083449  0.918159  -1.180023  2.379910e-01 -2.883009   0.716110
29  5.468906  1.253056   4.364456  1.274397e-05  3.012962   7.924850
30  1.363059  1.068780   1.275341  2.021885e-01 -0.731711   3.457829
31  7.396763  0.951176   7.776439  7.459448e-15  5.532492   9.261034
32  2.887162  0.906346   3.185496  1.445059e-03  1.110756   4.663567
33  2.226769  1.083101   2.055921  3.979013e-02  0.103931   4.349607
34  0.255088  1.148177   0.222168  8.241834e-01 -1.995297   2.505473
35  0.967321  1.062813   0.910152  3.627424e-01 -1.115754   3.050396
36  6.653771  1.294862   5.138595  2.768000e-07  4.115888   9.191653
37  5.233720  1.221418   4.284953  1.827778e-05  2.839784   7.627656
38  6.980286  0.958072   7.285763  3.198556e-13  5.102499   8.858073
39  6.019948  1.179137   5.105384  3.301238e-07  3.708882   8.331015
40  4.296606  1.347547   3.188465  1.430305e-03  1.655462   6.937749
41  1.589835  1.323831   1.200935  2.297765e-01 -1.004827   4.184497
42 -0.685143  1.390337  -0.492789  6.221619e-01 -3.410153   2.039868
43  8.418412  1.393374   6.041746  1.524554e-09  5.687449  11.149375
44  7.097918  1.562660   4.542203  5.566943e-06  4.035161  10.160675
45  8.073592  0.911026   8.862083  7.853303e-19  6.288013   9.859171
46  6.964149  1.141426   6.101272  1.052274e-09  4.726995   9.201302
47  4.680889  1.325171   3.532291  4.119763e-04  2.083601   7.278176
48  2.470216  0.930416   2.654958  7.931825e-03  0.646634   4.293799
49  3.629657  0.544821   6.662109  2.699256e-11  2.561827   4.697486

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.324078  2.028503  2.732928
1     1.340692  2.029455  2.718219
2     1.368592  2.037117  2.705641
3     1.405411  2.050950  2.696490
4     1.448677  2.070418  2.692159
...        ...       ...       ...
9995  3.545720  4.251056  4.956392
9996  3.582687  4.330950  5.079214
9997  3.618327  4.413404  5.208480
9998  3.657310  4.498727  5.340144
9999  3.703950  4.587230  5.470511

[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()