Skip to content

Commit 0c66575

Browse files
Benjamin T. VincentdrbenvincentOriolAbril
authored
Regression discontinuity example (#308)
* create truncated regression example * delete truncated regression example from main branch * create truncated regression example * delete truncated regression example from main branch * create truncated regression example * delete truncated regression example from main branch * initial commit * obey the law in terms of numpy random number generation + az style * improvements to schematic figure * replace image with non transparent background * fix embedded image Co-authored-by: Oriol Abril-Pla <[email protected]> * fix embedded image - not sure why this didn't register before * address all review comments - change notebook tag - remove plt.tight_layout() - ax.legend() -> plt.legend() * make code cell visible * remove 2 unused lines * add explanation tag * add technical note re posterior predictive sampling * addressing Luciano's suggested edits * increase clarity of sentence in introduction * add another explanatory markdown cell on the effect posterior * fix typo Co-authored-by: Benjamin T. Vincent <[email protected]> Co-authored-by: Oriol Abril-Pla <[email protected]>
1 parent 37f60d4 commit 0c66575

File tree

3 files changed

+1115
-0
lines changed

3 files changed

+1115
-0
lines changed

examples/case_studies/regression_discontinuity.ipynb

+871
Large diffs are not rendered by default.
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
---
2+
jupytext:
3+
notebook_metadata_filter: substitutions
4+
text_representation:
5+
extension: .md
6+
format_name: myst
7+
format_version: 0.13
8+
jupytext_version: 1.13.7
9+
kernelspec:
10+
display_name: pymc-dev-py39
11+
language: python
12+
name: pymc-dev-py39
13+
---
14+
15+
(regression_discontinuity)=
16+
# Regression discontinuity design analysis
17+
18+
:::{post} April, 2022
19+
:tags: regression, causal inference, quasi experimental design, counterfactuals
20+
:category: beginner, explanation
21+
:author: Benjamin T. Vincent
22+
:::
23+
24+
[Quasi experiments](https://en.wikipedia.org/wiki/Quasi-experiment) involve experimental interventions and quantitative measures. However, quasi-experiments do _not_ involve random assignment of units (e.g. cells, people, companies, schools, states) to test or control groups. This inability to conduct random assignment poses problems when making causal claims as it makes it harder to argue that any difference between a control and test group are because of an intervention and not because of a confounding factor.
25+
26+
The [regression discontinuity design](https://en.wikipedia.org/wiki/Regression_discontinuity_design) is a particular form of quasi experimental design. It consists of a control and test group, but assignment of units to conditions is chosen based upon a threshold criteria, not randomly.
27+
28+
:::{figure-md} fig-target
29+
30+
![regression discontinuity design schematic](regression_discontinuity.png)
31+
32+
A schematic diagram of the regression discontinuity design. The dashed green line shows where we would have expected the post test scores of the test group to be if they had not recieved the treatment. Image taken from [https://conjointly.com/kb/regression-discontinuity-design/](https://conjointly.com/kb/regression-discontinuity-design/).
33+
:::
34+
35+
Units with very low scores are likely to differ systematically along some dimensions than units with very high scores. For example, if we look at students who achieve the highest, and students who achieve the lowest, in all likelihood there are confounding variables. Students with high scores are likely to have come from more priviledged backgrounds than those with the lowest scores.
36+
37+
If we gave extra tuition (our experimental intervention) to students scoring in the lowest half of scores then we can easily imagine that we have large differences in some measure of privilege between test and control groups. At a first glance, this would seem to make the regression discontinuity design useless - the whole point of random assignment is to reduce or eliminate systematic biases between control and test groups. But use of a threshold would seem to maximise the differences in confounding variables between groups. Isn't this an odd thing to do?
38+
39+
The key point however is that it is much less likely that students scoring just below and just above the threshold systematically differ in their degree of privilege. And so _if_ we find evidence of a meaningful discontinuity in a post-test score in those just above and just below the threshold, then it is much more plausible that the intervention (applied according to the threshold criteria) was causally responsible.
40+
41+
## Sharp v.s. fuzzy regression discontinuity designs
42+
Note that regression discontinuity designs fall into two categories. This notebook focusses on _sharp_ regression discontinuity designs, but it is important to understand both sharp and fuzzy variants:
43+
44+
- **Sharp:** Here, the assignment to control or treatment groups is purely dictated by the threshold. There is no uncertainty in which units are in which group.
45+
- **Fuzzy:** In some situations there may not be a sharp boundary between control and treatment based upon the threshold. This could happen for example if experimenters are not strict in assigning units to groups based on the threshold. Alternatively, there could be non-compliance on the side of the actual units being studied. For example, patients may not always be fully compliant in taking medication, so some unknown proportion of patients assigned to the test group may actually be in the control group because of non compliance.
46+
47+
```{code-cell} ipython3
48+
import arviz as az
49+
import matplotlib.pyplot as plt
50+
import numpy as np
51+
import pandas as pd
52+
import pymc as pm
53+
```
54+
55+
```{code-cell} ipython3
56+
RANDOM_SEED = 123
57+
rng = np.random.default_rng(RANDOM_SEED)
58+
az.style.use("arviz-darkgrid")
59+
%config InlineBackend.figure_format = 'retina'
60+
```
61+
62+
## Generate simulated data
63+
Note that here we assume that there is negligible/zero measurement noise, but that there is some variability in the true values from pre- to post-test. It is possible to take into account measurement noise on the pre- and post-test results, but we do not engage with that in this notebook.
64+
65+
```{code-cell} ipython3
66+
:tags: [hide-input]
67+
68+
# define true parameters
69+
threshold = 0.0
70+
treatment_effect = 0.7
71+
N = 1000
72+
sd = 0.3 # represents change between pre and post test with zero measurement error
73+
74+
# No measurement error, but random change from pre to post
75+
df = (
76+
pd.DataFrame.from_dict({"x": rng.normal(size=N)})
77+
.assign(treated=lambda x: x.x < threshold)
78+
.assign(y=lambda x: x.x + rng.normal(loc=0, scale=sd, size=N) + treatment_effect * x.treated)
79+
)
80+
81+
df
82+
```
83+
84+
```{code-cell} ipython3
85+
:tags: [hide-input]
86+
87+
def plot_data(df):
88+
fig, ax = plt.subplots(figsize=(12, 7))
89+
ax.plot(df.x[~df.treated], df.y[~df.treated], "o", alpha=0.3, label="untreated")
90+
ax.plot(df.x[df.treated], df.y[df.treated], "o", alpha=0.3, label="treated")
91+
ax.axvline(x=threshold, color="k", ls="--", lw=3, label="treatment threshold")
92+
ax.set(xlabel=r"observed $x$ (pre-test)", ylabel=r"observed $y$ (post-test)")
93+
ax.legend()
94+
return ax
95+
96+
97+
plot_data(df);
98+
```
99+
100+
+++ {"tags": []}
101+
102+
## Sharp regression discontinuity model
103+
104+
We can define our Bayesian regression discontinuity model as:
105+
106+
$$
107+
\begin{aligned}
108+
\Delta & \sim \text{Cauchy}(0, 1) \\
109+
\sigma & \sim \text{HalfNormal}(0, 1) \\
110+
\mu & = x_i + \underbrace{\Delta \cdot treated_i}_{\text{treatment effect}} \\
111+
y_i & \sim \text{Normal}(\mu, \sigma)
112+
\end{aligned}
113+
$$
114+
115+
where:
116+
- $\Delta$ is the size of the discontinuity,
117+
- $\sigma$ is the standard deviation of change in the pre- to post-test scores,
118+
- $x_i$ and $y_i$ are observed pre- and post-test measures for unit $i$, and
119+
- $treated_i$ is an observed indicator variable (0 for control group, 1 for test group).
120+
121+
Notes:
122+
- We make the simplifying assumption of no measurement error.
123+
- Here, we confine ourselves to the sitation where we use the same measure (e.g. heart rate, educational attainment, upper arm circumference) for both the pre-test ($x$) and post-test ($y$). So the _untreated_ post-test measure can be modelled as $y \sim \text{Normal}(\mu=x, \sigma)$.
124+
- In the case that the pre- and post-test measuring instruments where not identical, then we would want to build slope and intercept parameters into $\mu$ to capture the 'exchange rate' between the pre- and post-test measures.
125+
- We assume we have accurately observed whether a unit has been treated or not. That is, this model assumes a sharp discontinuity with no uncertainty.
126+
127+
```{code-cell} ipython3
128+
with pm.Model() as model:
129+
x = pm.MutableData("x", df.x, dims="obs_id")
130+
treated = pm.MutableData("treated", df.treated, dims="obs_id")
131+
sigma = pm.HalfNormal("sigma", 1)
132+
delta = pm.Cauchy("effect", alpha=0, beta=1)
133+
mu = pm.Deterministic("mu", x + (delta * treated), dims="obs_id")
134+
pm.Normal("y", mu=mu, sigma=sigma, observed=df.y, dims="obs_id")
135+
136+
pm.model_to_graphviz(model)
137+
```
138+
139+
## Inference
140+
141+
```{code-cell} ipython3
142+
with model:
143+
idata = pm.sample(random_seed=RANDOM_SEED)
144+
```
145+
146+
We can see that we get no sampling warnings, and that plotting the MCMC traces shows no issues.
147+
148+
```{code-cell} ipython3
149+
az.plot_trace(idata, var_names=["effect", "sigma"]);
150+
```
151+
152+
We can also see that we are able to accurately recover the true discontinuity magnitude (left) and the standard deviation of the change in units between pre- and post-test (right).
153+
154+
```{code-cell} ipython3
155+
az.plot_posterior(
156+
idata, var_names=["effect", "sigma"], ref_val=[treatment_effect, sd], hdi_prob=0.95
157+
);
158+
```
159+
160+
The most important thing is the posterior over the `effect` parameter. We can use that to base a judgement about the strength of the effect (e.g. through the 95% credible interval) or the presence/absence of an effect (e.g. through a Bayes Factor or ROPE).
161+
162+
+++ {"tags": []}
163+
164+
## Counterfactual questions
165+
166+
We can use posterior prediction to ask what would we expect to see if:
167+
- no units were exposed to the treatment (blue shaded region, which is very narrow)
168+
- all units were exposed to the treatment (orange shaded region).
169+
170+
_Technical note:_ Formally we are doing posterior prediction of `y`. Running `pm.sample_posterior_predictive` multiple times with different random seeds will result in new and different samples of `y` each time. However, this is not the case (we are not formally doing posterior prediction) for `mu`. This is because `mu` is a deterministic function (`mu = x + delta*treated`), so for our already obtained posterior samples of `delta`, the values of `mu` will be entirely determined by the values of `x` and `treated` data).
171+
172+
```{code-cell} ipython3
173+
:tags: []
174+
175+
# MODEL EXPECTATION WITHOUT TREATMENT ------------------------------------
176+
# probe data
177+
_x = np.linspace(np.min(df.x), np.max(df.x), 500)
178+
_treated = np.zeros(_x.shape)
179+
180+
# posterior prediction (see technical note above)
181+
with model:
182+
pm.set_data({"x": _x, "treated": _treated})
183+
ppc = pm.sample_posterior_predictive(idata, var_names=["mu", "y"])
184+
185+
# plotting
186+
ax = plot_data(df)
187+
az.plot_hdi(
188+
_x,
189+
ppc.posterior_predictive["mu"],
190+
color="C0",
191+
hdi_prob=0.95,
192+
ax=ax,
193+
fill_kwargs={"label": r"$\mu$ untreated"},
194+
)
195+
196+
# MODEL EXPECTATION WITH TREATMENT ---------------------------------------
197+
# probe data
198+
_x = np.linspace(np.min(df.x), np.max(df.x), 500)
199+
_treated = np.ones(_x.shape)
200+
201+
# posterior prediction (see technical note above)
202+
with model:
203+
pm.set_data({"x": _x, "treated": _treated})
204+
ppc = pm.sample_posterior_predictive(idata, var_names=["mu", "y"])
205+
206+
# plotting
207+
az.plot_hdi(
208+
_x,
209+
ppc.posterior_predictive["mu"],
210+
color="C1",
211+
hdi_prob=0.95,
212+
ax=ax,
213+
fill_kwargs={"label": r"$\mu$ treated"},
214+
)
215+
ax.legend()
216+
```
217+
218+
The blue shaded region shows the 95% credible region of the expected value of the post-test measurement for a range of possible pre-test measures, in the case of no treatment. This is actually infinitely narrow because this particular model assumes $\mu=x$ (see above).
219+
220+
The orange shaded region shows the 95% credible region of the expected value of the post-test measurement for a range of possible pre-test measures in the case of treatment.
221+
222+
Both are actually very interesting as examples of counterfactual inference. We did not observe any units that were untreated below the threshold, nor any treated units above the treshold. But assuming our model is a good description of reality, we can ask the counterfactual questions "What if a unit above the threshold was treated?" and "What if a unit below the treshold was treated?"
223+
224+
+++
225+
226+
## Summary
227+
In this notebook we have merely touched the surface of how to analyse data from regression discontinuity designs. Arguably, we have restricted our focus to almost the simplest possible case so that we can focus upon the core properties of the approach which allows causal claims to be made.
228+
229+
+++
230+
231+
## Authors
232+
- Authored by [Benjamin T. Vincent](https://github.com/drbenvincent) in April 2022
233+
234+
+++
235+
236+
## Watermark
237+
238+
```{code-cell} ipython3
239+
%load_ext watermark
240+
%watermark -n -u -v -iv -w -p aesara,aeppl,xarray
241+
```
242+
243+
:::{include} ../page_footer.md
244+
:::

0 commit comments

Comments
 (0)