-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathestimators.py
More file actions
168 lines (146 loc) · 5.87 KB
/
estimators.py
File metadata and controls
168 lines (146 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# -*- coding: utf-8 -*-
import numpy as np
from sklearn.linear_model import LinearRegression, RidgeCV
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
def get_ps_y01_hat(zhat, w, y, regularize=True):
"""predict ps, y0 and y1 with logistic and linear regressions"""
w = w.reshape((-1, ))
y = y.reshape((-1, ))
n, _ = zhat.shape
if regularize:
lr = LogisticRegressionCV(solver='lbfgs', cv=5)
else:
lr = LogisticRegression(solver='lbfgs', penalty='none')
lr.fit(zhat, w)
ps_hat = lr.predict_proba(zhat)[:, 1]
if len(np.unique(y)) == 2:
if regularize:
lr = LogisticRegressionCV(solver='lbfgs', cv=5)
else:
lr = LogisticRegression(solver='lbfgs', penalty='none')
else:
if regularize:
lr = RidgeCV(alphas=(0.1, 1.0, 10.0))
else:
lr = LinearRegression()
lr.fit(zhat[np.equal(w, np.ones(n)), :], y[np.equal(w, np.ones(n))])
y1_hat = lr.predict(zhat)
lr.fit(zhat[np.equal(w, np.zeros(n)), :], y[np.equal(w, np.zeros(n))])
y0_hat = lr.predict(zhat)
y0_hat = y0_hat.reshape((-1, 1))
y1_hat = y1_hat.reshape((-1, 1))
return ps_hat, y0_hat, y1_hat
def tau_residuals(y, w, y_hat=None, ps_hat=None,
confounders=None, method="glm",
regularize=True):
"""Residuals on residuals regression for ATE estimation (a la Robinson (1988))
if method == "glm": provide fitted values y1_hat, y0_hat and ps_hat
for the two response surfaces and the propensity scores respectively
if method == "grf": no need to provide any fitted values but need to provide confounders matrix"""
y = y.reshape((-1, ))
y_hat = y_hat.reshape((-1, ))
w = w.reshape((-1, ))
assert y_hat.shape == y.shape
assert w.shape == y.shape
if method == "glm":
if regularize:
lr = RidgeCV(alphas=(0.1, 1.0, 10.0), fit_intercept=False)
else:
lr = LinearRegression(fit_intercept=False)
lr.fit((w - ps_hat).reshape((-1, 1)), (y - y_hat).reshape((-1, 1)))
tau = float(lr.coef_)
elif method == "grf":
raise NotImplementedError("Causal forest estimation not implemented here yet.")
else:
raise ValueError("'method' should be choosed between 'glm' and 'grf' in 'tau_dr', got %s", method)
return tau
def tau_dr(y, w, y0_hat=None, y1_hat=None, ps_hat=None,
confounders=None, method="glm",
regularize=True):
"""Doubly robust ATE estimation
if method == "glm": provide fitted values y1_hat, y0_hat and ps_hat
for the two response surfaces and the propensity scores respectively
if method == "grf": no need to provide any fitted values but need to provide confounders matrix"""
y = y.reshape((-1, ))
y0_hat = y0_hat.reshape((-1, ))
y1_hat = y1_hat.reshape((-1, ))
w = w.reshape((-1, ))
assert y0_hat.shape == y.shape
assert y1_hat.shape == y.shape
assert w.shape == y.shape
if method == "glm":
tau_i = y1_hat - y0_hat + w*(y-y1_hat)/np.maximum(1e-12, ps_hat) -\
(1-w)*(y-y0_hat)/np.maximum(1e-12, (1-ps_hat))
tau = np.mean(tau_i)
elif method == "grf":
raise NotImplementedError("Causal forest estimation not implemented here yet.")
else:
raise ValueError("'method' should be choosed between 'glm' and 'grf' in 'tau_dr', got %s", method)
return tau
def tau_ols(Z_hat, w, y, regularize=True):
"""ATE estimation via OLS regression"""
assert w.shape == y.shape
y = y.reshape((-1, ))
ZW = np.concatenate((Z_hat, w.reshape((-1, 1))), axis = 1)
if len(np.unique(y)) == 2:
if regularize:
lr = LogisticRegressionCV(solver='lbfgs', cv=5)
else:
lr = LogisticRegression(solver='lbfgs', penalty='none')
lr.fit(ZW, y)
tau = lr.coef_[0, -1]
else:
if regularize:
lr = RidgeCV(alphas=(0.1, 1.0, 10.0))
else:
lr = LinearRegression()
lr.fit(ZW, y)
tau = lr.coef_[-1]
return tau
def tau_ols_ps(zhat, w, y, regularize=True):
"""ATE estimation via OLS regression with PS as additional covariate.
Difference with tau_ols: add estimated propensity
scores as additional predictor"""
assert w.shape == y.shape
w = w.reshape((-1, ))
y = y.reshape((-1, ))
if regularize:
lr = LogisticRegressionCV(solver='lbfgs', cv=5)
else:
lr = LogisticRegression(solver='lbfgs', penalty='none')
lr.fit(zhat, w)
ps_hat = lr.predict_proba(zhat)
ZpsW = np.concatenate((zhat, ps_hat, w.reshape((-1, 1))), axis = 1)
if len(np.unique(y)) == 2:
if regularize:
lr = LogisticRegressionCV(solver='lbfgs', cv=5)
else:
lr = LogisticRegression(solver='lbfgs', penalty='none')
lr.fit(ZpsW, y)
tau = lr.coef_[0, -1]
else:
if regularize:
lr = RidgeCV(alphas=(0.1, 1.0, 10.0))
else:
lr = LinearRegression()
lr.fit(ZpsW, y)
tau = lr.coef_[-1]
return tau
def compute_estimates(zhat, w, y, regularize=True, nuisance=False):
"""Compute tau_dr, tau_ols, tau_ols_ps, tau_resid
on given confounders matrix and w and y."""
tau_hat = dict()
ps_hat, y0_hat, y1_hat = get_ps_y01_hat(zhat, w, y, regularize)
tau_hat['tau_ols'] = tau_ols(zhat, w, y, regularize)
tau_hat['tau_ols_ps'] = tau_ols_ps(zhat, w, y, regularize)
tau_hat['tau_dr'] = tau_dr(y, w, y0_hat, y1_hat, ps_hat, regularize=regularize)
if regularize:
lr = RidgeCV(alphas=(0.1, 1.0, 10.0))
else:
lr = LinearRegression()
lr.fit(zhat, y)
y_hat = lr.predict(zhat)
tau_hat['tau_resid'] = tau_residuals(y, w, y_hat, ps_hat, regularize=regularize)
if nuisance:
return tau_hat, {'ps_hat': ps_hat, 'y0_hat': y0_hat, 'y1_hat': y1_hat}
return tau_hat