Python: Conditional Average Treatment Effects (CATEs)#

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.

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) and this notebook from EconML.

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

The data is generated as

$ \begin{align} Y_i & = g(X_i)T_i + \langle W_i,\gamma_0\rangle + \epsilon_i \\ T_i & = \langle W_i,\beta_0\rangle +\eta_i, \end{align} $

where \(W_i\sim\mathcal{N}(0,I_{d_w})\), \(X_i\sim\mathcal{U}[0,1]^{d_x}\) and \(\epsilon_i,\eta_i\sim\mathcal{U}[0,1]\). The coefficient vectors \(\gamma_0\) and \(\beta_0\) both have small random support which values are drawn independently from \(\mathcal{U}[0,1]\). Further, \(g(x)\) defines the conditional treatment effect, which is defined differently depending on the dimension of \(x\).

If \(x\) is univariate the conditional treatment effect takes the following form

\[g(x) = \exp(2x) + 3\sin(4x),\]

whereas for a two-dimensional variable \(x=(x_1,x_2)\) the conditional treatment effect is defined as

\[g(x) = \exp(2x_1) + 3\sin(4x_2).\]
[2]:
def treatment_effect_1d(x):
    te = np.exp(2 * x) + 3 * np.sin(4 * x)
    return te

def treatment_effect_2d(x):
    te = np.exp(2 * x[0]) + 3 * np.sin(4 * x[1])
    return te

def create_synthetic_data(n_samples=200, n_w=30, support_size=5, n_x=1):
    # Outcome support
    # With the next two lines we are effectively choosing the matrix gamma in the example
    support_y = np.random.choice(np.arange(n_w), size=support_size, replace=False)
    coefs_y = np.random.uniform(0, 1, size=support_size)
    # Define the function to generate the noise
    epsilon_sample = lambda n: np.random.uniform(-1, 1, size=n_samples)
    # Treatment support
    # Assuming the matrices gamma and beta have the same non-zero components
    support_t = support_y
    coefs_t = np.random.uniform(0, 1, size=support_size)
    # Define the function to generate the noise
    eta_sample = lambda n: np.random.uniform(-1, 1, size=n_samples)

    # Generate controls, covariates, treatments and outcomes
    w = np.random.normal(0, 1, size=(n_samples, n_w))
    x = np.random.uniform(0, 1, size=(n_samples, n_x))
    # Heterogeneous treatment effects
    if n_x == 1:
        te = np.array([treatment_effect_1d(x_i) for x_i in x]).reshape(-1)
    elif n_x == 2:
        te = np.array([treatment_effect_2d(x_i) for x_i in x]).reshape(-1)
    # Define treatment
    log_odds = np.dot(w[:, support_t], coefs_t) + eta_sample(n_samples)
    t_sigmoid = 1 / (1 + np.exp(-log_odds))
    t = np.array([np.random.binomial(1, p) for p in t_sigmoid])
    # Define the outcome
    y = te * t + np.dot(w[:, support_y], coefs_y) + epsilon_sample(n_samples)

    # Now we build the dataset
    y_df = pd.DataFrame({'y': y})
    if n_x == 1:
        x_df = pd.DataFrame({'x': x.reshape(-1)})
    elif n_x == 2:
        x_df = pd.DataFrame({'x_0': x[:,0],
                             'x_1': x[:,1]})
    t_df = pd.DataFrame({'t': t})
    w_df = pd.DataFrame(data=w, index=np.arange(w.shape[0]), columns=[f'w_{i}' for i in range(w.shape[1])])

    data = pd.concat([y_df, x_df, t_df, w_df], axis=1)

    covariates = list(w_df.columns.values) + list(x_df.columns.values)
    return data, covariates, te

One-dimensional Example#

We start with \(X\) being one-dimensional and create our training data.

[3]:
# DGP constants
np.random.seed(42)
n_samples = 2000
n_w = 10
support_size = 5
n_x = 1

# Create data
data, covariates, true_effect = create_synthetic_data(n_samples=n_samples, n_w=n_w, support_size=support_size, n_x=n_x)
data_dml_base = dml.DoubleMLData(data,
                                 y_col='y',
                                 d_cols='t',
                                 x_cols=covariates)

Next, define the learners for the nuisance functions and fit the IRM Model. Remark that the learners are not optimal for the linear form of this example.

[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.01,
                          n_folds=5)
print("Training IRM Model")
dml_irm.fit()
Training IRM Model
[4]:
<doubleml.double_ml_irm.DoubleMLIRM at 0x7fce809cb4c0>

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 \(g(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"]})
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.800985  0.187226   4.278164   1.973568e-05  0.433805  1.168165
1  2.317576  0.312855   7.407836   1.885192e-13  1.704020  2.931132
2  4.731110  0.199998  23.655730  2.996077e-109  4.338882  5.123338
3  4.501506  0.239412  18.802350   9.746797e-73  4.031982  4.971030
4  3.865116  0.245950  15.715036   1.485625e-52  3.382770  4.347463
5  4.114845  0.266575  15.435994   7.270658e-51  3.592051  4.637639

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.161123  2.486602  2.812081
1   2.279878  2.607058  2.934238
2   2.394024  2.725133  3.056242
3   2.504552  2.840828  3.177103
4   2.612308  2.954141  3.295974
..       ...       ...       ...
95  4.480207  4.811954  5.143701
96  4.483368  4.809714  5.136060
97  4.487456  4.808597  5.129738
98  4.491828  4.808603  5.125377
99  4.495728  4.809731  5.123734

[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_1d(new_data['x'])
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_16_0.png

Two-Dimensional Example#

It is also possible to estimate multi-dimensional conditional effects. We will use the same data-generating process as above, but let \(X\) be two-dimensional.

[9]:
# DGP constants
np.random.seed(42)
n_samples = 5000
n_w = 10
support_size = 5
n_x = 2
[10]:
# Create data
data, covariates, true_effect = create_synthetic_data(n_samples=n_samples, n_w=n_w, support_size=support_size, n_x=n_x)
data_dml_base = dml.DoubleMLData(data,
                                 y_col='y',
                                 d_cols='t',
                                 x_cols=covariates)

As univariate example estimate the IRM Model.

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

dml_irm = dml.DoubleMLIRM(data_dml_base,
                          ml_g=randomForest_reg,
                          ml_m=randomForest_class,
                          trimming_threshold=0.01,
                          n_folds=5)
print("Training IRM Model")
dml_irm.fit()
Training IRM Model
[11]:
<doubleml.double_ml_irm.DoubleMLIRM at 0x7fce7bd34b20>

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.918522  0.131696  22.161126  7.873877e-104   2.660341   3.176704
1   -3.120608  1.054239  -2.960058   3.090402e-03  -5.187383  -1.053832
2    1.318038  1.082087   1.218051   2.232625e-01  -0.803333   3.439409
3    3.774745  0.932201   4.049284   5.215985e-05   1.947219   5.602272
4    1.130398  0.959782   1.177765   2.389470e-01  -0.751201   3.011996
5   -4.077941  1.163032  -3.506302   4.584094e-04  -6.357999  -1.797883
6   -4.562939  1.255456  -3.634487   2.813619e-04  -7.024191  -2.101688
7   -8.177997  1.354252  -6.038756   1.666449e-09 -10.832931  -5.523063
8   -0.700580  1.127950  -0.621110   5.345561e-01  -2.911861   1.510701
9    0.609560  1.174950   0.518797   6.039258e-01  -1.693863   2.912983
10   1.098413  0.966290   1.136733   2.557050e-01  -0.795943   2.992769
11  -1.470745  1.004488  -1.464173   1.432101e-01  -3.439986   0.498497
12   1.010627  1.247217   0.810306   4.178032e-01  -1.434470   3.455725
13  -3.170605  1.300191  -2.438569   1.478045e-02  -5.719555  -0.621655
14   0.089005  1.139051   0.078139   9.377204e-01  -2.144041   2.322050
15   0.400864  0.984067   0.407355   6.837650e-01  -1.528343   2.330071
16   1.259400  1.007864   1.249573   2.115146e-01  -0.716461   3.235260
17   2.733362  0.825097   3.312778   9.303739e-04   1.115807   4.350918
18   2.022883  0.818387   2.471794   1.347710e-02   0.418482   3.627283
19  -1.558512  1.022898  -1.523624   1.276665e-01  -3.563846   0.446822
20  -3.528278  1.112568  -3.171292   1.526892e-03  -5.709405  -1.347152
21  -4.977858  0.954963  -5.212621   1.937605e-07  -6.850008  -3.105708
22   0.850241  0.981460   0.866302   3.863664e-01  -1.073856   2.774339
23   3.501269  1.047169   3.343557   8.332604e-04   1.448354   5.554184
24   4.303824  0.855195   5.032565   5.010997e-07   2.627263   5.980385
25   2.333297  0.839608   2.779031   5.472702e-03   0.687293   3.979301
26   0.289671  1.018622   0.284375   7.761346e-01  -1.707280   2.286622
27  -1.866836  1.127895  -1.655151   9.795718e-02  -4.078010   0.344337
28   0.395229  1.040229   0.379944   7.040032e-01  -1.644082   2.434539
29   5.367269  1.206680   4.447962   8.858836e-06   3.001640   7.732898
30   1.169674  1.297194   0.901696   3.672624e-01  -1.373401   3.712749
31   5.544617  1.055213   5.254501   1.546537e-07   3.475932   7.613303
32   2.891036  1.086825   2.660075   7.837501e-03   0.760377   5.021694
33   2.073431  1.314328   1.577560   1.147307e-01  -0.503235   4.650097
34   0.419772  1.400667   0.299695   7.644227e-01  -2.326155   3.165700
35  -3.040951  1.421273  -2.139597   3.243612e-02  -5.827275  -0.254626
36   5.035395  1.307834   3.850178   1.195214e-04   2.471460   7.599330
37   7.443807  1.401484   5.311376   1.135634e-07   4.696278  10.191336
38   7.693490  1.149053   6.695506   2.388069e-11   5.440837   9.946143
39   6.219181  1.191880   5.217959   1.882900e-07   3.882568   8.555795
40   2.128193  1.415565   1.503423   1.327939e-01  -0.646943   4.903329
41   3.653763  1.513319   2.414404   1.579703e-02   0.686987   6.620539
42   2.831182  1.531740   1.848343   6.461228e-02  -0.171708   5.834072
43  10.020911  1.277886   7.841787   5.401097e-15   7.515687  12.526134
44   4.341162  1.351137   3.212969   1.322126e-03   1.692334   6.989990
45   7.472969  1.129647   6.615314   4.099700e-11   5.258360   9.687577
46   6.723281  1.125170   5.975346   2.456675e-09   4.517449   8.929114
47   5.276243  1.425043   3.702514   2.157969e-04   2.482526   8.069960
48   0.103778  1.519023   0.068319   9.455345e-01  -2.874180   3.081736
49   3.106364  1.414534   2.196033   2.813582e-02   0.333249   5.879479

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.167832  1.996727  2.825622
1     1.209281  2.008422  2.807563
2     1.262932  2.028691  2.794449
3     1.324812  2.056623  2.788434
4     1.390877  2.091309  2.791742
...        ...       ...       ...
9995  4.098424  4.865818  5.633211
9996  4.161863  4.962507  5.763150
9997  4.219514  5.052251  5.884989
9998  4.272605  5.133962  5.995320
9999  4.322013  5.206551  6.091090

[10000 rows x 3 columns]
[15]:
import plotly.graph_objects as go

true_effect = np.array([treatment_effect_2d(x_i) for x_i in zip(x_0.ravel(), x_1.ravel())]).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()