library(foreign) # for loading dta files
descr <- read.dta("./data/oregon_data/oregonhie_descriptive_vars.dta")
prgm <- read.dta("./data/oregon_data/oregonhie_stateprograms_vars.dta")
s12 <- read.dta("./data/oregon_data/oregonhie_survey12m_vars.dta")
# nicely organized, one row per person; check that they match
all(s12$person_id == descr$person_id)
all(s12$person_id == prgm$person_id)
P <- descr[, c("person_id", "household_id", "numhh_list")]
P$medicaid <- as.numeric(prgm[, "ohp_all_ever_firstn_30sep2009"] == "Enrolled")
P$selected <- as.numeric(descr[, "treatment"] == "Selected")
levels(P$numhh_list) <- c("1", "2", "3+")
# 12 month is the survey that really matters
# need to control for household size interacted with survey return time
Y <- s12[, c("weight_12m", "doc_any_12m", "doc_num_mod_12m", "er_any_12m", "er_num_mod_12m", "hosp_any_12m", "hosp_num_mod_12m")]
Y$doc_any_12m <- as.numeric(Y$doc_any_12m == "Yes")
Y$er_any_12m <- as.numeric(Y$er_any_12m == "Yes")
Y$hosp_any_12m <- as.numeric(Y$hosp_any_12m == "Yes")
# smk_ever_12m - num19_12m are sources of heterogeneity, plus descr
X <- s12[, 121:147]
X$dt_returned <- factor(format(s12$dt_returned_12m, "%Y-%m"))
insurv <- which(s12$sample_12m_resp == "12m mail survey responder")
X <- X[insurv, ]
Y <- Y[insurv, ]
P <- P[insurv, ]
sapply(Y, function(y) sum(is.na(y)))
nomiss <- which(!apply(Y, 1, function(y) any(is.na(y))))
X <- X[nomiss, ]
Y <- Y[nomiss, ]
P <- P[nomiss, ]
# pull out the weights and attach doc_any to P
weights <- Y[, 1]
Y <- Y[, -1]
# replace some ridiculous values in survey and drop num19
X$hhsize_12m[X$hhsize_12m > 10] <- 10
X$num19_12m <- NULL
# organize to make it pretty for text
P$doc_any_12m <- Y$doc_any_12m # you can explore other responses if you want
P <- P[, c(1, 2, 6, 5, 4, 3)]
names(P)[6] <- "numhh"ECON 4370 / 6370 Computing for Economics
Lecture 16: Causal Inference
Introduction
We were careful to interpret \(\hat\beta\) in our regressions only as correlations, which, as you may have heard, is not causation.
Without a causal interpretation, \(\hat\beta\) is useful for (a) uncovering patterns in past data, and (b) predict future outcomes using \(\hat{\bf E}[Y \mid X=x] = G(x'\hat\beta)\), assuming the process that generates future data is the same as the one that generated past data.
However, we often need to make predictions when the future process is expected to change, say due to actions we take.
E.g. a company may change their marketing or pricing strategy based on analysis of past data, but then this could change how consumers respond.
Plan for this part of the course:
- Informal discussion of causality in the orange juice and lending applications from earlier in the course
- Introduce some concepts: counterfactual prediction, selection bias, omitted variables bias
- Potential outcomes framework
- New notation/language and different assumptions than textbook linear model …
- … but key takeaway similar to textbook linear model: “causal” interpretation of regression under an independence assumption
- Strategies for estimating causal effects:
- Randomized experiments
- Controlling for covariates using regression
- Structural modeling (revisit multinomial logit)
- Modifying ML methods for causal inference
- Randomization/“placebo” tests
- Debiased lasso; sample splitting/“double ML”
- Propensity score methods
We may jump between (3) and (4) by introducing methods in the context of particular estimation strategies (e.g. placebo tests for regression discontinuity)
- Informal discussion of causality in the orange juice and lending applications from earlier in the course
Causality: basic concepts
Counterfactuals
Making forecasts after a change to the system entails counterfactual prediction, imagining how the system will hypothetically respond to the intervention.
We’ll use the idea of a counterfactual to think about whether an effect is “causal.” More precisely, we can talk about a causal effect for a particular counterfactual outcome.
Stating a research question in terms of counterfactuals can help us avoid introducing unnecessary made-up objects into our economic analysis.
This is particularly useful for economists, since we tend to like complicated mathematical analysis and made-up objects (utility, production functions, etc.)
Example: we’re modeling demand, and we’re worried that consumers are being “tricked” by advertising and not optimizing a “true” utility function. We have a behavioral model from psychology of how this works. Should we put this in our econometric model?
Suppose the counterfactual is the change in demand after a tax (to predict tax revenues). Then maybe we don’t have to worry.
On the other hand, it could matter for welfare analysis, or if we’re predicting the effect of a policy that makes consumers better informed.
Using counterfactuals also forces us to clarify what we actually mean by a “causal” effect. For example, suppose we ask “What is the causal effect of cholesterol on heart attacks?” What do we mean?
We probably can’t raise and lower our cholesterol at will (unless we are Dwight Schrute from “The Office”). Instead, we should come up with a concrete counterfactual that we have in mind:
Administering cholesterol medication
Changing diet
Changing exercise
Rather than a literal policy experiment, we may be interested in causal effects to gain a better scientific understanding of how the world works.
In this case, the counterfactual can be a hypothetical thought experiment.
Still, it’s helpful to be as concrete as possible about the counterfactual we have in mind with a causal effect.
Before formally discussing causality and counterfactuals, let’s review an example we’ve already seen that illustrate the problem with interpreting \(\hat\beta\) causally.
Lending
We discussed a binary classification problem where we fit a logit to predict the probability of default.
Logit \(\hat\beta\) gives association between various borrower characteristics and default.
We saw that those with better credit histories actually defaulted more often.

Does this mean we prefer lending to people with worse credit histories? Doesn’t seem plausible.
An explanation is those with better histories were approved for riskier loans, which have inherently higher default probabilities.
This suggests that the correlation between better credit histories and higher default rates is not “causal.” What do we mean by this? What’s the counterfactual?
One possible counterfactual policy: change the screening procedure so that we require better credit history, keeping the type of loan (amount, collateral, etc.) fixed
Since loan amount is fixed under this counterfactual, we won’t have increased default rates due to riskier loans (higher amount, less collateral, etc.)
Thus, the causal effect of this policy change will probably be different: better credit history through more stringent screening will probably decrease defaults, rather than increase them.
Why are the correlations biased for this causal effect? We can think of this as selection bias (selecting applicants with better credit history for a riskier loan) or omitted variables bias (omitting a full description of loan type in a logit regression)
Note how the exercise of coming up with a counterfactual disciplines our thinking here. We could also come up with other ways of defining a “causal effect of credit history” using other counterfactuals in which we “manipulate credit history” in other ways:
Enrolling someone in a personal finance class
Targeted advertising using a mailing list of consumers with good credit history
Passing a law forcing banks to approve loans for people with credit history above a minimum threshold
The causal effects of these policies would probably be different!
Potential outcomes framework
We’ll introduce a framework that mathematically formalizes the notion of counterfactuals and causal effects: the potential outcomes framework.
Much of this is the same as what you may have seen with the textbook linear model (e.g. Wooldridge Introductory Econometrics), but with different notation/terminology.
We’ll use an example from health policy to make these ideas concrete.
Does Health Insurance Improve Health?
US spends more on health care as a share of GDP than other developed countries for worse health outcomes. Would outcomes improve under universal health care?
This is a causal question: does having health insurance have a positive causal effect on health?
In the data, we usually see a positive association between health insurance and health. What’s a possible causal story for this?
Why might this correlation not be causal, i.e. what’s a possible source of selection bias?
Defining causality
We’ve introduced the concept of counterfactual interventions: thought experiments in which, holding all other factors fixed, we manipulate a single variable and observe the consequences for an outcome of interest.
Now let’s formalize this using math. This is really nothing more than writing and interpreting some equations.
Let \(Y\) be an observed outcome variable (health) and \(D\) a binary variable representing two courses of treatment:
\(D=0\): does not have health insurance
\(D=1\): has health insurance
Suppose outcomes are determined as follows: \[Y = g(D,\varepsilon),\] where \(g(\cdot)\) is a unknown function and \(\varepsilon\) is unobserved factors that affect the outcome (income, etc.).
Imagine a world where we could change the treatment assignment \(D\) ceteris peribus, i.e. keeping all others factors \(\varepsilon\) fixed. Then we could calculate \(g(1,\varepsilon)\) and \(g(0,\varepsilon)\).
These are called potential outcomes and represent what outcomes counterfactually would be if we intervened by changing treatment to 1 or 0, holding fixed all other factors.
In our health insurance example:
\(g(0,\varepsilon)=\) potential outcome without health insurance
\(g(1,\varepsilon)=\) potential outcome with health insurance
If a unit is actually assigned \(D=1\), then \(Y=g(1,\varepsilon)\), so we get to observe one of the potential outcomes. However, \(g(0,\varepsilon)\) is unobserved—it is counterfactual.
We define the unit-level causal effect or unit-level treatment effect \[g(1,\varepsilon) - g(0,\varepsilon).\]
This is causal because the only reason why outcomes differ between the two states is because \(D\) changes from 0 to 1.
Causality and regression
You are probably already familiar with the special case where this model is linear: \[g(D,\varepsilon) = \alpha + D \beta + \varepsilon.\]
Then potential outcomes take the form \[g(1,\varepsilon) = \alpha + \beta + \varepsilon, \quad g(0,\varepsilon) = \alpha + \varepsilon.\]
Thus, the causal effect is captured by the slope coefficient: \[g(1,\varepsilon) - g(0,\varepsilon) = \beta.\]
This is sometimes called a homogeneous treatment effect model, since the unit level causal effect \(g(1,\varepsilon) - g(0,\varepsilon)\) is homogeneous (the same) for individuals with different \(\varepsilon\).
Causal inference and OLS
What assumptions do we need for OLS to recover the causal effect \(\beta\)?
You may recall from an introductory econometrics class that we can recover a “causal” effect if \(D\) is uncorrelated with \(\varepsilon\).
Formally, this is because \[\begin{align} \hat\beta &= \frac{\widehat{\text{Cov}}(Y,D)}{\widehat{\text{Var}}(D)} \approx \frac{\text{Cov}(Y,D)}{\text{Var}(D)} \\ &=\frac{\text{Cov}(\alpha + D\beta + \varepsilon,D)}{\text{Var}(D)} = \beta + \frac{\text{Cov}(\varepsilon,D)}{\text{Var}(D)} \end{align}\]
Thus, if \(\text{cov}(\varepsilon,D)=0\), then \(\hat\beta\) will recover the causal effect \(\beta\).
Selection bias and omitted variables bias
Suppose we collect some data \((D_1,Y_1),\ldots,(D_n,Y_n)\) and regress \(Y\) on \(D\). Can we expect \(\text{cov}(\varepsilon,D)=0\)?
It depends on the counterfactual we’re using to define \(g(D,\varepsilon)\) and \(\varepsilon\): \(\varepsilon\) represents everything we’re holding fixed in the counterfactual.
Health insurance example:
\(\varepsilon\) includes income, job status and social background (i.e. these things have a direct effect on the potential outcomes \(g(0,\varepsilon)\) and \(g(1,\varepsilon)\))
These things are also correlated with \(D\) (having health insurance).
We can think of this as selection bias: individuals select into \(D=0\) vs \(D=1\) based on their individual characteristics \(\varepsilon\)
We can also think of this as omitted variables bias: we should be adding in income, job status, social background etc. so that we are holding them fixed (we’ll discuss this strategy later on)
We also talked about selection bias in the OJ demand and loan applications: we can formalize this by interpreting \(D\), \(\varepsilon\) and \(g(0,\varepsilon)\), \(g(1,\varepsilon)\) in these examples as well.
Causal Inference vs. Prediction
The OLS selection bias decomposition \[\begin{align} \hat\beta \approx \beta + \frac{\text{Cov}(\varepsilon,D)}{\text{Var}(D)} \end{align}\] pinpoints the difference between the standard ML goal of prediction and that of causal or counterfactual prediction.
ML seeks to predict a future that looks like the past (consider how CV works). In this case, the selection bias term \(\text{Cov}(D,\varepsilon) / \text{Var}(D)\) isn’t problematic. It’s an additional way in which \(D\) is related to \(Y\) and therefore helps to predict \(Y\).
Formally, when we talk about prediction, we write down a regression equation \[ Y_i = f(X_i) + U_i \] where \(E[U_i|X_i]=0\) by assumption.
We then try to get an estimate \(\hat f(X_i)\) that approximates \(f(X_i)\), which we can use for prediction.
If \(\text{Cov}(D,\varepsilon) / \text{Var}(D)\ne 0\), then \(f(X_i)\) will be correlated with \(\varepsilon\), even though it’s uncorrelated with \(U_i\).
Thus, the “error term” and “regression function” in the lectures on predictive regression are in general, different from the “error term” \(\varepsilon\) and the function \(g(D,\varepsilon)\) in the causal model.
But in counterfactual prediction where you intervene in the system by changing \(D\), this alters the relationship between \(D,\varepsilon\), so that \(\text{Cov}(D,\varepsilon)\) estimated from past data is no longer informative about the future.
E.g. when changing your pricing policy \(D\), you want to forecast how this change alone affects demand \(Y\), as captured by \(\beta\).
If we’re considering a new policy where we just change price, then adding \(\text{Cov}(D,\varepsilon) / \text{Var}(D)\) skews your prediction.
On the other hand, if we’re just predicting how demand will change when we vary price along with whatever else we’ve been changing when we vary price in our data set (advertising promotions, etc.), we want to keep the \(\text{Cov}(D,\varepsilon) / \text{Var}(D)\) term and use it for prediction.
Heterogeneous treatment effects
The model \(g(D,\varepsilon)=\alpha+D\beta+\varepsilon\) is linear and additively separable in \(\varepsilon\), which imposes homogeneous treatment effects: \[ g(1,\varepsilon) - g(0,\varepsilon) = \beta \quad\text{for all }\varepsilon.\]
Is this realistic? Probably not. We don’t think everyone benefits equally from health insurance. The causal effect probably differs by:
Baseline health (if you’re lucky enough to be healthy and not experience adverse health events, you won’t end up using health insurance anyway)
Wealth/income (if you’re uninsured but you are wealthy enough, then you can pay out of pocket)
Often economists write down more complicated models to allow heterogeneous treatment effects:
Random coefficients: \[Y=g(D,\varepsilon)=\alpha + (\beta+\varepsilon_1)D + \varepsilon_2\]
Random utility interpretation of logit (we’ll discuss this later): \[Y=I(\alpha + \beta D \ge \varepsilon)\]
Note that these models are not additively separable in \(\varepsilon\)
OLS with heterogeneous treatment effects
It turns out that we can still interpret OLS causally in this case if we assume that \(\varepsilon\) and \(D\) are statistically independent
The assumption of independence is technically stronger than uncorrelatedness, but the interpretation in this setting is usually similar: we’re ruling out the possibility that individuals select into \(D=0\) vs \(D=1\) based on \(\varepsilon\).
Let’s see how this works. First, note that, since \(D\) is binary, we can also write the OLS coefficient \(\beta\) as a difference-in-means estimator: \[\begin{align} \hat\beta &= \frac{\widehat{\text{Cov}}(Y,D)}{\widehat{\text{Var}}(D)} \\ &= \text{... algebra ...} \\ &= \bar Y_1 - \bar Y_0 \end{align}\] where \(\bar Y_1=\frac{\sum_{i: D_i=1} Y_i}{\#\{i: D_i=1\}}\) is the sample mean for the observations with \(D_i=1\), and similarly for \(\bar Y_0\).
Thus, \[ \hat\beta = \bar Y_1-\bar Y_0 \approx E[Y|D=1] - E[Y|D=0] \] by the law of large numbers.
Now, note that \(E[Y|D=1]=E[g(1,\varepsilon)|D=1]\), since \(Y=g(D,\varepsilon)=g(1,\varepsilon)\) when \(D=1\). If we assume \(D\) and \(\varepsilon\) are independent, then \[ E[g(1,\varepsilon)|D=1] = E[g(1,\varepsilon)|D=0] = E[g(1,\varepsilon)]. \]
Applying the same reasoning to \(D=0\), and putting it all together, we get \[\begin{align} \hat\beta &= \bar Y_1-\bar Y_0 \approx E[Y|D=1] - E[Y|D=0] \\ &=E[g(1,\varepsilon)]-E[g(0,\varepsilon)] \\ &=E[g(1,\varepsilon) - g(0,\varepsilon)]. \end{align}\]
We call \(E[g(1,\varepsilon) - g(0,\varepsilon)]\) the average treatment effect, (ATE) since it is the population average of the unit-level treatment effect \(g(1,\varepsilon)-g(0,\varepsilon)\).
Strategies for estimating causal effects
Randomized experiments
Randomized control trials are considered the “gold standard” for scientific evidence because randomization eliminates selection bias.
These are also called A/B tests. Some users are shown design A of Netflix’s website, some design B. Which increases sign-ups more?
Formally, when we talk about “random assignment,” we typically mean that treatment (i.e. \(D\)) is assigned randomly and independently of any individual characteristics (i.e. \(\varepsilon\)).
Intuitively, if we randomize provision of health insurance, then having health insurance has nothing to do with income level or other individual characteristies.
This breaks any relationship between \(D\) and \(\varepsilon\), so that as \(D\) varies, \(\varepsilon\) moves independently.
With randomization, the \(\varepsilon\)s of treated people are on average the same as those of untreated people, so that \(\varepsilon\) is effectively held fixed in the aggregate across the two groups.
Application: Oregon Health Insurance Experiment (OHIE)
In 2008, Oregon expanded Medicaid to a subset of citizens, the government program that provides health insurance to people who can’t afford it.
Since demand was likely high, they implemented a lottery randomly allocating eligibility among low-income earners.
We’ll use public data from the experiment to study the causal effect of being given eligibility on usage of primary care.
This is interesting to policymakers because Oregon can use the estimate to plan for increased primary care usage when it later expands Medicaid eligibility to a wider population.
\(Y=\) indicator for whether the person visited a primary care physician during the 12 months of the study. \(D=\) indicator for program eligibility.
The data is taken from https://www.nber.org/research/data/oregon-health-insurance-experiment-data. First we load the data and do some cleaning. We use the
foreignpackage to read data in the Stata format. We’ll skip this part (code and output hidden from the html output of the.Rmdcode), but you can read it by downloading the.Rmdcode if you’re interested.
- The result is a data frame
Pthat has the variables we need. Let’s take a look:
head(P) # doc_any_12m = outcome, selected = treatment person_id household_id doc_any_12m selected medicaid numhh
1 1 100001 0 1 0 1
2 2 100002 0 1 1 1
5 5 100005 0 1 0 1
6 6 100006 1 1 0 1
8 8 102094 0 0 0 2
9 9 100009 1 0 0 1
dim(P)[1] 23107 6
- Our outcome \(Y\) is the variable
doc_any_12m. Our treatment \(D\) is the variableselected.
table(P$selected)
0 1
11629 11478
- If the experimentation is completely at random, we can estimate a causal effect by running OLS of \(Y\) (
doc_any_12m) on \(D\) (selected). We noted that this is numerically equivalent to taking a difference in sample means (although we skipped the algebra). Let’s try this out:
# regression estimate
summary(glm(doc_any_12m ~ selected, data = P))
Call:
glm(formula = doc_any_12m ~ selected, data = P)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.573480 0.004531 126.557 <2e-16 ***
selected 0.057466 0.006429 8.938 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for gaussian family taken to be 0.2387859)
Null deviance: 5536.2 on 23106 degrees of freedom
Residual deviance: 5517.1 on 23105 degrees of freedom
AIC: 32485
Number of Fisher Scoring iterations: 2
# difference-in-means estimate
ybar <- tapply(P$doc_any_12m, P$selected, mean)
ybar # ybar has sample mean for selected=1 and selected=0 0 1
0.5734801 0.6309462
ybar["1"] - ybar["0"] # matches regression coefficient on "selected" 1
0.05746606
Problems with experiments: noncompliance
Those assigned to treatment may not actually take it and vice versa. In the Oregon experiment, being granted eligibility didn’t mean they had to enroll.
We call this noncompliance.
Solution: we defined \(D\) as eligibility for treatment, rather than treatment itself. The effect of treatment eligibility is called an intent to treat (ITT) effect.
This can be fine if we are interested in a counterfactual policy involving treatment eligibility.
However, we might worry if we are predicting the outcome of a counterfactual policy that selects a different type of person (e.g. cash incentive for paid insurance vs lottery for free insurance).
We can decompose: \[ \text{ITT} = \underbrace{E(\text{treatment effect}|\text{comply})}_{\text{"local average treatment effect" (LATE)}}\cdot P(\text{comply}) \]
So the ITT weights a treatment effect by compliance probability.
It turns out that, under some assumptions, we can get an estimate of \(E(\text{treatment effect}|\text{comply})\) (the LATE) from an instrumental variables regression of \(Y\) on treatment status with treatment eligibility as the instrument.
It is common in empirical economics to use this strategy with “quasi-experimental” variation. An example (from Card, “Using Geographic Variation in College Proximity to Estimate the Return to Schooling,” 1993):
- \(Y=\) earnings
- “treatment:” attending college
- “treatment eligibility:” growing up near a college
We won’t cover instrumental variables or LATEs further here, but if you’re interested, you can refer to the book Mastering ‘Metrics’ by Angrist and Pischke from the syllabus.
Additional complications with the OHIE data
We’ve been treating the OHIE data as an experiment where individuals \(i\) are drawn and assigned to \(D_i=0\) (not allowed to sign up for Medicaid) or \(D_i=1\) (allowed to sign up for Medicaid) randomly (i.e. independently of any additional characteristics \(\varepsilon_i\)).
This isn’t quite true: individuals who are selected for Medicaid eligibility are actually allowed to sign up their whole household.
Thus, a more complete description of the experiment is that households are randomly drawn, and that each household gets multiple chances to sign up for medicaid if it has multiple members.
In particular, larger households are more likely to be eligible for the Medicaid expansion. Let’s look at this in our data (
numhhis a factor variable for household size):
table(P[, c("selected", "numhh")]) numhh
selected 1 2 3+
0 8684 2939 6
1 7525 3902 51
Thus, \(D_i\) is correlated with household size, which is part of \(\varepsilon_i\) since we’re not including it in the regression. Is this a problem? Why?
What can we do? Control for
numhh! Let’s think about this idea using the potential outcomes framework and come up with some assumptions that justify it.Note that we’re now thinking of the unit of treatment as a household, so \(D_i\) is Medicaid eligibility for household \(i\), and we’ll define \(Y_i\) to be average primary care physician visits per household member.
- Another reason to do this: dependence between regression errors within household (can also solve this problem using something called “clustering” for the standard errors; see BDS, p. 138)
Randomization conditional on observables
The preceding discussion suggests the following model for treatment allocation:
- Draw an individual household \(i\) and observe \(X_i=\) household size
- Given household size \(X_i=x\), choose some probability \(p(x)\) of assigning household \(i\) to \(D_i=1\).
- Set \(D_i=1\) with probability \(p=p(X_i)\) and \(D_i=0\) with probability \(1-p(X_i)\), independently of all other factors \(\varepsilon_i\) that describe the household.
The assumption that randomization depends only on \(X_i\) and not \(\varepsilon_i\) is called a selection on observables assumption, and \(p(x)\) is called the propensity score.
We can now go through the same analysis as before, but conditioning on \(X_i\). Main takeaway: we can still get a causal effect by regressing \(Y_i\) on \(D_i\), but we now need to include flexible controls for \(X_i\) and its interactions with \(D_i\).
Define potential outcomes:
\(g(0,X_i,\varepsilon_i)=\) potential outcome without health insurance
\(g(1,X_i,\varepsilon_i)=\) potential outcome with health insurance
As before, we observe \(Y_i=g(D_i,X_i,\varepsilon_i)\).
Same definition of unit-level treatment effect: \[ g(1,X_i,\varepsilon_i)-g(0,X_i,\varepsilon_i) \]
Apply the same arguments as before, but condition on \(X_i\). Our selection on observables assumption means that: \[ D_i \text{ is independent of }\varepsilon_i \text{ conditional on }X_i \]
Suppose we flexibly estimate a regression model of \(Y_i\) on \(D_i,X_i\): \[ E[Y_i|D_i,X_i] = f(D_i,X_i). \]
We will apply the same arguments as before to give a causal interpretation of \(f(1,x)-f(0,x)\). Note that: \[ f(1,x) =E[Y_i| D_i=1, X_i=x] =E[g(1,X_i,\varepsilon_i)| D_i=1, X_i=x]. \]
By the selection-on-observables assumption: \[\begin{align} &E[g(1,X_i,\varepsilon_i)| D_i=1, X_i=x] =E[g(1,X_i,\varepsilon_i)| D_i=0, X_i=x] \\ &=E[g(1,X_i,\varepsilon_i)| X_i=x] \end{align}\]
Applying the same arguments to \(D_i=0\), we get \[ f(1,x) - f(0,x) =E[g(1,X_i,\varepsilon_i) -g(0,X_i,\varepsilon_i)| X_i=x]. \]
This is the expectation of the unit-level treatment effect given \(X_i=x\). We call it a conditional average treatment effect (CATE).
How do we estimate a conditional average treatment effect?
Estimate a regression model \[ Y_i = f(D_i,X_i) + U_i \] using OLS, lasso, etc.
Let \(\hat f(d,x)\) be the predicted value when \(D_i=d\), \(X_i=x\). Our estimate of the CATE for \(X_i=x\) is: \[ \widehat{\text{CATE}}(x)=\hat f(1,x) - \hat f(0,x) \]
Brief note on notation
We are using the notation \(Y_i = g(D_i,X_i,\varepsilon_i)\) and assuming \(D_i\) is independent of \(\varepsilon_i\) conditional on \(X_i\).
We can also let \(u_i=(X_i,\varepsilon_i)\) and write this as \(Y_i=g(D_i,u_i)\). It is then equivalent to assume that \(D_i\) is independent of \(u_i\) conditional on \(X_i\) (after we condition on \(X_i\), the only nonrandom part of \(u_i=(X_i,\varepsilon_i)\) is \(\varepsilon_i\)).
Yet another alternative: let \(Y_i=Y_i^*(D_i)\) where \(Y_i^*(d)=g(d,X_i,\varepsilon_i)\) are the potential outcomes for \(d=0\) and \(d=1\). Then we can use the assumption that the potential outcomes \(Y_i^*(0),Y_i^*(1)\) are independent of \(D_i\) conditional on \(X_i\)
- This is sometimes called “potential outcomes notation,” since we write assumptions directly in terms of the potential outcomes.
For practical purposes, all of these systems of notation lead to the same estimators and interpretations for treatment effects of \(D_i\) in the present setting. But some people prefer particular types of notation for conceptual reasons.
For example, our notation \(Y_i=g(D_i,X_i,\varepsilon_i)\) seems to suggest that \(X_i\) is also a “treatment” that could be manipulated.
- This might not make sense in our example, where \(X_i\) is household size (we’re not changing household size in our experiment, and it’s not clear what “manipulating household size” would even entail here).
- Thus, some would argue that we should use the notation \(Y_i=g(D_i,U_i)\), or \(Y_i=Y_i^*(D_i)\), in order to make clear the logical distinction between \(D_i\) as a “treatment” and \(X_i\) as an observed variable that we can’t manipulate.
- However, for practical purposes, either notation gives the same conclusions and interpretation, as long as we’re careful not to try to estimate “treatment effects” of changing \(X_i=\) household size.
We’ll keep using the notation \(Y_i=g(D_i,X_i,\varepsilon_i)\) in these notes, but keep in mind this discussion about alternative notations since you might see other notation elsewhere.
Conditioning on household size in the OHIE data
- Let’s try this in the OHIE data. First, we’ll aggregate to the level of the household.
yhh <- tapply(P$doc_any_12m, P$household_id, mean) # average primary care visits within each household
zebra <- match(names(yhh), P$household_id) # 1st occurence of each HH in P
selectedhh <- P$selected[zebra]
numhh_hh <- P$numhh[zebra]- Regress
yhhon interactions ofselectedhhandnumhh_hh
ols_hh <- lm(yhh ~ selectedhh * numhh_hh)
summary(ols_hh)
Call:
lm(formula = yhh ~ selectedhh * numhh_hh)
Residuals:
Min 1Q Median 3Q Max
-0.6579 -0.5868 0.3421 0.4132 0.4800
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.586826 0.005080 115.508 < 2e-16 ***
selectedhh 0.071114 0.007456 9.537 < 2e-16 ***
numhh_hh2 -0.043883 0.012183 -3.602 0.000317 ***
numhh_hh3+ -0.475715 0.273384 -1.740 0.081856 .
selectedhh:numhh_hh2 -0.029237 0.016467 -1.775 0.075835 .
selectedhh:numhh_hh3+ 0.337775 0.289368 1.167 0.243109
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.4734 on 20470 degrees of freedom
Multiple R-squared: 0.007059, Adjusted R-squared: 0.006817
F-statistic: 29.11 on 5 and 20470 DF, p-value: < 2.2e-16
Since \(X_i\) is a full set of indicator variables that we’ve interacted with \(D_i\), we can read off our CATE estimate from the interaction coefficients: \[\begin{align} \hat f&(\text{selected},\text{household size}) \\ &= \beta_1 + \beta_2 \cdot \text{selected} + \beta_3 I(\text{household size }2) + \beta_4 I(\text{household size }3+) \\ &+ \beta_5 I(\text{household size }2)\cdot \text{selected} \\ &+ \beta_6 I(\text{household size }3+)\cdot \text{selected} \end{align}\]
So \(\beta_2\) gives the CATE estimate for the baseline category (household size 1), \(\beta_2+\beta_5\) gives the CATE estimate for household size 2, etc. Let’s get the CATE for household size 2:
coef(ols_hh)["selectedhh:numhh_hh2"] + coef(ols_hh)["selectedhh"]selectedhh:numhh_hh2
0.04187647
- We can also get \(\hat f(d,x)\) using
predict. Let’s check that this gives the same thing (note thatRautomatically takes care of the interaction terms):
predict(ols_hh, data.frame(selectedhh = 1, numhh_hh = "2")) - predict(ols_hh, data.frame(selectedhh = 0, numhh_hh = "2")) 1
0.04187647
When the CATE varies as a function of \(X_i=x\), we say there is observed heterogeneity. We can examine the CATE as a function of \(x\) to examine observed heterogeneity.
Here, our estimates suggest the CATE doesn’t vary much between household size one (the baseline value of
numhh_hh) and two.Our point estimate suggests that the CATE is much larger for household size \(3+\), but it’s imprecisely estimated (probably because we observe few households with this size).
What if we just want the average for the whole population? Under selection on observables, the ATE is: \[ E[f(1,X_i)-f(0,X_i)]. \] We can estimate it using \[ \frac{1}{n}\sum_{i=1}^n [\hat f(1,X_i)-\hat f(0,X_i)]. \]
Again, we can use
predictfor this in R:
treated_newx <- data.frame(selectedhh = rep(1, length(numhh_hh)), numhh_hh = numhh_hh) # x matrix with D_i replaced with 1
untreated_newx <- data.frame(selectedhh = rep(0, length(numhh_hh)), numhh_hh = numhh_hh) # x matrix with D_i replaced with 0
mean(predict(ols_hh, newdata = treated_newx) - predict(ols_hh, newdata = untreated_newx))[1] 0.06552294
Constant CATEs
If the CATE is constant, we get the regression model \[\begin{align} Y_i = f(D_i,X_i) + U_i = \beta D_i + f(0,X_i) + U_i \end{align}\] where \(\beta=f(1,X_i)-f(0,X_i)\) is the CATE (which is constant in this case and equal to the ATE).
So, we can interpret the treatment coefficient \(\beta\) as a causal effect. Note that it’s still important to flexibly control for \(X_i\): it may not enter linearly.
Let’s try this in the OHIE data:
summary(lm(yhh ~ selectedhh + numhh_hh))
Call:
lm(formula = yhh ~ selectedhh + numhh_hh)
Residuals:
Min 1Q Median 3Q Max
-0.6548 -0.5895 0.3452 0.4105 0.5168
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.589525 0.004832 121.995 < 2e-16 ***
selectedhh 0.065301 0.006647 9.824 < 2e-16 ***
numhh_hh2 -0.059905 0.008197 -7.308 2.81e-13 ***
numhh_hh3+ -0.171639 0.089598 -1.916 0.0554 .
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.4735 on 20472 degrees of freedom
Multiple R-squared: 0.006838, Adjusted R-squared: 0.006692
F-statistic: 46.98 on 3 and 20472 DF, p-value: < 2.2e-16
- The coefficient of
selectedhhgives our estimate of the treatment effect. It’s similar to our ATE estimate from before that allowed for observed heterogeneity in the CATE.
Controlling for covariates using regression
Often, we have observational data, where we are interested in the causal effect of some variable \(D_i\) that is not randomly assigned.
A common approach is to try to find control variables \(X_i\) and regress the outcome \(Y_i\) on \(D_i\) and \(X_i\).
How can we give this regression a causal interpretation? We can use the same potential outcomes framework and the same selection on observables assumption as before: \[ D_i \text{ is independent of }\varepsilon_i \text{ conditional on }X_i \]
The selection on observables assumption is sometimes also called unconfoundedness
The idea is that we have controlled for any “confounding variables” \(X_i\) that make it difficult to distinguish between treatment effects and selection.
Of course, the argument for the selection on observables assumption is now less convincing, since we don’t know how \(D_i\) is really determined in the data.
Nonetheless, it’s common to use this assumption and terminology from the treatment effects literature when interpreting regression with observational data.
Application: abortion and crime
We’ll explore the idea of using regression to control for covariates using the abortion and crime study of Donohue III and Levitt (2001), made famous by the “Freakonomics” book and franchise.
We’ll use this to introduce the “double/debiased lasso,” which adjusts the lasso with the goal of estimating causal effects in a regression with many control variables.
This application (albeit a different specification) was also used by Belloni et al. (2014) in one of the original papers on this method.
Background:
Roe v. Wade Supreme Court decision legalized abortion in U.S. nationwide in 1973. Beforehand, it had only been recently made legal in a few states.
Large decrease in crime in U.S. in 1990s
Hypothesized causal link: abort unwanted pregnancies \(\rightarrow\) parents raise children only when prepared \(\rightarrow\) children grow up to commit fewer crimes
Roe v. Wade overturned in 2022 \(\rightarrow\) more papers on abortion and crime 18 years later?
Donohue III and Levitt (2001) run regressions at the level of a state \(i\) and year \(t\). We’ll use panel data notation to reflect this: subscript by \(i\) and \(t\) (panel data refers to a data set that follows individual units \(i\) over time \(t\)).
Putting this in the causal framework:
\(Y_{it}\) crime in state \(i\) in year \(t\)
\(D_{it}\) abortions in state \(i\) in year \(t-18\)
\(X_{it}\) confounding variables: time trends, variables that might be associated with both unwanted pregnancies and crime such as poverty rate, gun laws, alcohol consumption
Does putting this into the potential outcomes framework and making a selection-on-observables assumption with these covariates make sense?
Putting aside any issues with plausibility/interpretation, we’ll go ahead and run some regressions. First, we read in the data:
data <- read.table("./data/abortion.dat", skip = 1, sep = "\t") # skip=1 skips the first line, sep="\t" says the data is tab separated
names(data) <- c(
"state", "year", "pop", "y_viol", "y_prop", "y_murd",
"a_murd", "a_viol", "a_prop", "prison", "police",
"ur", "inc", "pov", "afdc", "gun", "beer"
)Our variables include:
- prison: log of lagged prisoners per capita
- police: the log of lagged police per capita
- ur: the unemployment rate
- inc: per-capita income
- pov: the poerty rate
- AFDC: Aid to Families with Dependent Children generosity at year t-15
- gun: dummy for concealed weapons law
- beer: beer consumption per capita
We’ll control for a time trend, and state fixed effects. Let’s make these variables.
data <- data[!(data$state %in% c(2, 9, 12)), ] # drop AK, DC, HA (states are numbered alphabetically)
data <- data[data$year > 84 & data$year < 98, ] # incomplete data outside these years
data$pop <- log(data$pop)
t <- data$year - 85
s <- factor(data$state)- We’ll also control for some covariates, which we’ll put in the data frame
controls:
controls <- data.frame(data[, c(3, 10:17)])
head(controls) pop prison police ur inc pov afdc gun beer
20 8.287277 0.9526656 0.7626628 0.08908 9.703193 20.6 3077.629 1 18.7
21 8.292048 0.9952912 0.7909027 0.09833 9.745950 23.8 2805.778 1 19.3
22 8.297793 1.0584020 0.8189143 0.07775 9.762092 21.3 3455.742 1 19.4
23 8.300032 1.1438180 0.8803344 0.07208 9.781770 19.3 3210.000 1 19.4
24 8.301522 1.1219460 0.9410318 0.07025 9.802527 18.9 3789.493 1 19.4
25 8.306472 1.2144630 0.9891075 0.06775 9.814290 19.2 3436.729 1 20.1
Outcome is de-trended log crime (we’ll focus on murders) and the “treatment” is the abortion rate lagged by age groups of those committing the crime.
- For example, if 60% of violent crime were committed by 18-year-olds and 40% were committed by 19 year olds in state i, the abortion rate for violent crime at time t in state i would be constructed as .6 times the abortion rate in state i at time \(t − 18\) plus .4 times the abortion rate in state i at time \(t − 19\).
y <- data$y_murd
d <- data$a_murdWe’ll estimate a model with a constant conditional average treatment effect (no interaction terms between treatment \(D_i\) and controls \(X_i\))
- Note that
y,d,tandsare global variables (rather than being in some data frame, accessed using$). In the command below,.just includes the variables in thecontrolsdata frame.
- Note that
orig <- glm(y ~ d + t + s + ., data = controls)
summary(orig)$coef["d", ] Estimate Std. Error t value Pr(>|t|)
-2.098119e-01 4.109177e-02 -5.105936e+00 4.505925e-07
We get a negative and statistically significant effect
- Note: we should probably be taking into account heteroskedasticity and correlation of error terms across years, but Donohue III and Levitt (2001) do this and also find a statistically significant effect.
Is this plausible? Let’s explore this using a popular strategy from empirical economics: “placebo” outcomes.
Assessing the validity of a (pseudo)randomization scheme: “placebo” treatments/outcomes
In the OHIE example, we saw that treatment was not “completely at random,” but we could correct for this fairly easily by conditioning on household size.
In the abortion and crime example things certainly aren’t so clear. What can we do?
One idea: run the same specification with treatment or outcome for which we think it is unlikely that there is a nonzero treatment effect. This is sometimes called using a “placebo” treatment or outcome.
The idea is similar to the use of placebos in clinical drug trials to account for the possibility that patients are just reporting better outcomes even with ineffective treatment.
Here, we’re worried about the possibility that we, as researchers, are finding treatment effects where they don’t exist through bogus specifications and estimation strategies.
A related idea in the tech sector: “A/A testing”
Randomization is easily done across different devices visiting the website, but the same person could be visting with different devices. That person may then be exposed to both A and B.
Browser cookies are used to track behavior to measure \(Y\), but people who clear their cookies may go unmeasured. This leads to attrition bias.
On large online platforms, there’s a complex tree that decides, e.g., which webpage is shown to a user in a particular region with a particular device, etc. Improper design of the experiment can make it so that only one of many entry points in the tree lead a user to treatment page A.
But users piped through this point of the tree may be quite different from other users. Then you randomized at the wrong level of the process.
Companies use “A/A” tests to catch problems like these, where treatment and control are given treatment A, so we expected no differences in outcomes.
If we find a significant difference in outcomes, it means our randomization was done poorly.
Placebo treatments in the abortion and crime example: cell phone usage
We’ll run a “placebo exercise” for the abortion and crime data with cell phone usage as a “placebo treatment.”
First, we load some data on cellphone subscribers.
cell <- read.csv("./data/us_cellphone.csv") # data on cellphone subscribers
cellrate <- 5 * cell[, 2] / (1000 * cell[, 3]) # center on 1985 and scale by 1997-1985- Let’s run our placebo regression: same specification as before, but using cell phone usage as treatment.
phone <- cellrate[t + 1]
cell_reg <- glm(y ~ phone + s + t + ., data = controls)
summary(cell_reg)$coef["phone", ] Estimate Std. Error t value Pr(>|t|)
-3.720723e-01 6.932262e-02 -5.367257e+00 1.168637e-07
Do cellphones fight crime? Maybe by allowing for faster response times for police calls…
Another explanation: both cell phone usage and (lagged) abortions increased quadratically in our sample. In both cases, the coefficient could just be picking up this linear trend. Let’s look at a plot of abortions and cell phone usage over time:
par(mai = c(.9, .9, .1, .1))
# Abortions and cellphone adoption track very closely over time.
plot(1985:1997, tapply(d, t, mean), bty = "n", xlab = "year", ylab = "rate", pch = 21, bg = 2)
points(1985:1997, cellrate, bg = 4, pch = 21)
legend("topleft", fill = c(2, 4), legend = c("abortions", "cellphones"), bty = "n")
High dimensional controls
To correct this, let’s try adding more controls
Include time as a year specific indicator (so that we don’t impose a linear trend)
Control for state-specific effects of technology adoption (cell phone usage interacted with state fixed effects)
Add interactions and squares of all of the control variables
t <- factor(t)
interact <- glm(y ~ d + t + phone * s + .^2, data = controls)
summary(interact)$coef["d", ] Estimate Std. Error t value Pr(>|t|)
0.2797107 0.1807311 1.5476619 0.1223753
The sign of the treatment coefficient has switched, and it is now statistically insignificant.
Note that we now have “high dimensional” data, since we have a lot of controls:
dim(model.matrix(interact))[1] 624 154
If we’re worried that this will lead to poor performance of OLS based inference, we can try an approach based on a regularized estimator like the lasso.
Let’s try running lasso on this specification. We’ll use
cv.glmnetand report results for the 1se rule and the minimum CV error rule for lambda.
library(glmnet)Loading required package: Matrix
Attaching package: 'Matrix'
The following objects are masked from 'package:tidyr':
expand, pack, unpack
Loaded glmnet 5.0
set.seed(0) # set seed for cross validation
sna <- factor(s, levels = c(NA, levels(s)), exclude = NULL) # refactor state to have NA so that model.matrix() doesn't drop any levels (similar to naref() from gamlr)
DXinteract <- model.matrix(~ d + t + phone * sna + .^2 - 1, data = controls)
interact_glmnet <- cv.glmnet(DXinteract, y)
coef(interact_glmnet, s = "lambda.1se")["d", ] # treatment coefficient[1] -0.1079993
coef(interact_glmnet, s = "lambda.min")["d", ][1] -0.01977922
sum(coef(interact_glmnet, s = "lambda.1se") != 0) # number of nonzero coefficients[1] 59
sum(coef(interact_glmnet, s = "lambda.min") != 0)[1] 102
The point estimate is negative again, although smaller in magnitude than the first specification we tried (“
orig”), and it varies a lot between the two choices of \(\lambda\) (1se vs minimum CV error).We’ve been using lasso for prediction. Will it work well for estimating individual coefficients? Can we trust these estimates that we just got?
Not necessarily. Suppose our treatment is highly correlated with some control variable (for example, we saw that lagged abortions is correlated with cell phone use).
Lasso will often pick just one of these variables, since (a) lasso penalizes more complex models and (b) we don’t gain that much in terms of prediction by including both variables once we’ve included one.
Furthermore, lasso often picks the variables in unstable ways
So, we might end up with volatile estimates that exclude relevant controls.
We’ll next discuss an approach called “debiased lasso” or “double lasso” that is designed for estimation and inference on the coefficient of a single treatment variable.
- Basic idea: debias or add back in controls using a “propensity score regression” of treatment \(D_i\) on controls \(X_i\).
Double/debiased lasso
“Double/debiased lasso” refers to a related set of methods developed by several sets of coauthors (Zhang and Zhang 2014; Geer et al. 2014; Javanmard and Montanari 2014; Belloni et al. 2014).
We’ll focus on the case with constant CATEs (no interactions between \(D_i\) and \(X_i\)), although methods for heterogeneous CATEs also exist.
To motivate how this debiasing works, we augment our main regression \[ Y_i = D_i\beta + X_i'\gamma + U_i \] with a “treatment assignment regression”” of \(D_i\) on \(X_i\): \[ D_i = X_i'\delta + V_i. \]
When \(D_i\) is binary, \(E[D_i|X_i]=P(D_i=1|X_i)=X_i'\delta\) gives the propensity score (in this case, we may want to use something like logit for this regression, but we’ll stick with the least squares objective function here).
The basic idea is that we should also use the treatment assignment regression to select variables: if a variable enters this regression with nonzero \(\delta_j\), then it might be a source of selection bias.
The version of the debiased lasso from Zhang and Zhang (2014) takes the form: \[\begin{align} \hat\beta_{ZZ} &= \hat\beta_{\text{lasso}} + \frac{\sum_{i=1}^n \hat V_i \hat U_i}{\sum_{i=1}^n \hat V_i D_i} \\ &= \hat\beta_{\text{lasso}} + \frac{\sum_{i=1}^n (D_i-X_i\hat\delta_{\text{lasso}})(Y_i-D_i\hat\beta_{\text{lasso}}-X_i\hat\gamma_{\text{lasso}})}{\sum_{i=1}^n (D_i-X_i\hat\delta_{\text{lasso}})D_i} \\ &= \frac{\sum_{i=1}^n (D_i-X_i\hat\delta_{\text{lasso}})(Y_i-X_i\hat\gamma_{\text{lasso}})}{\sum_{i=1}^n (D_i-X_i\hat\delta_{\text{lasso}})D_i} \end{align}\] where \(\hat U_i\) and \(\hat V_i\) are lasso residuals from the main regression and the treatment assignment regression. The standard error under homoskedasticity (\(E[U_i^2|D_i,X_i]=\sigma^2\)) is \[\begin{align} \hat\sigma^2\cdot \frac{\sum_{i=1}^n \hat V_i^2}{\left(\sum_{i=1}^n \hat V_i D_i\right)^2} \end{align}\]
Let’s try this with our specification for the abortion and crime dta. We’ll use a choice of \(\lambda\) from cross-validation (although technically this doesn’t quite match the theory from Zhang and Zhang (2014)).
beta_hat_init_1se <- coef(interact_glmnet, s = "lambda.1se")["d", ] # initial lasso estimate
u_hat_1se <- y - predict(interact_glmnet, DXinteract, s = "lambda.1se")
Xinteract <- model.matrix(~ t + phone * sna + .^2 - 1, data = controls)
treat_interact_glmnet <- cv.glmnet(Xinteract, d)
v_hat_1se <- d - predict(treat_interact_glmnet, Xinteract, s = "lambda.1se")
(beta_hat_ZZ <- beta_hat_init_1se + sum(v_hat_1se * u_hat_1se) / sum(v_hat_1se * d)) # debiased lasso estimate[1] -0.08635144
sigma_sq_hat_1se <- mean(u_hat_1se^2)
(std_err_1se <- sqrt(sigma_sq_hat_1se * sum(v_hat_1se^2) / (sum(v_hat_1se * d))^2)) # debiased lasso standard error[1] 0.05128547
There are other versions of debiased/double lasso. The version from Belloni et al. (2014) uses a “post lasso selection” estimator, which runs OLS with the coefficients selected by lasso.
To obtain the Belloni et al. (2014) version of debiased lasso:
Run lasso of \(D_i\) on \(X_i\) (we already have this in
treat_glmnet)Run lasso of \(Y_i\) on \(X_i\) (slightly different from the regression we did above for the Zhang and Zhang (2014) debiased lasso, which included \(D_i\))
Run OLS of \(Y_i\) on \(D_i\) and all coefficients in \(X_i\) that have nonzero coefficient in either of the lasso regressions in the first two steps.
Let’s try this with our specification from the abortion and crime data.
y_on_x_interact_glmnet <- cv.glmnet(Xinteract, y)
# nonzero coefficients in regression of y on x
y_on_x_nonzero_coef_ind <- which(coef(y_on_x_interact_glmnet, s = "lambda.1se") != 0)
# nonzero coefficients in regression of d on x
treat_nonzero_coef_ind <- which(coef(treat_interact_glmnet, s = "lambda.1se") != 0)
# included variables for BCH lasso (union of nonzero coefficients in the two regressions)
BCH_coef_ind <- union(y_on_x_nonzero_coef_ind, treat_nonzero_coef_ind)
# number of selected controls (including intercept)
length(BCH_coef_ind)[1] 110
# BCH_coef_ind corresponds to indices where the design matrix includes a vector of ones, so let's add an intercept column to get the indices right
X_with_intercept <- cbind(rep(1, length(y)), Xinteract)
Xselected_BCH <- X_with_intercept[, BCH_coef_ind]
lm_BCH <- lm(y ~ d + Xselected_BCH - 1)
# treatment coefficient and standard error
coef(summary(lm_BCH))["d", ] Estimate Std. Error t value Pr(>|t|)
0.2355238 0.1470431 1.6017333 0.1098302
- We end up selecting most of the original regressors, and we get similar estimates to the original OLS regression, although the standard error is much smaller.
Other approaches to estimating treatment effects with ML
- A related idea is to replace residuals \(\hat V_i\) computed above (and similarly for \(\hat U_i\)) with “cross-validation residuals” \(\tilde V_i = D_i - X_i'\hat\gamma_{-k}\) where \(i\) is in the \(k\)th fold and \(\hat\gamma_{-k}\) is computed using all observations except for the \(k\)th fold. This is sometimes called “cross-fitting,” “double machine learning” or “orthogonal machine learning.” It turns out not to be necessary with lasso estimators, but it may reduce bias in other cases. See BDS, p. 177.
When to use debiased lasso vs OLS?
In the above example, we were able to compute the OLS estimator and standard errors despite having many regressors. We then got smaller standard errors with the debiased lasso (and one version of the debiased lasso gave us a substantively different point estimate). What should we make of this? Which estimate and standard error should we trust?
The theory of the debiased lasso was developed for cases where the number of regressors \(d\) is much greater than \(n\). When \(n>d\) and OLS estimates and CIs are asymptotically valid, the debiased lasso is asymptotically equivalent to just including all of the regressors and doing OLS.
Thus, if we are in a setting where we can use OLS and we get substantively smaller standard errors with debiased lasso than with OLS, we should probably be suspicious.
This contrasts with the usual use of (non-debiased) lasso for prediction, where we can improve on OLS when \(n>d\) so long as the regression coefficient is small.
On the other hand, if we have more regressors than observations, then we can’t run OLS at all, and debiased lasso may be a good approach for estimating individual coefficients and getting standard errorrs for them.
See Wüthrich and Zhu (2021) for some further discussion and Monte Carlo simulation evidence.
Frisch-Waugh-Lovell theorem
To get some more intuition for the debiased lasso, note that the Frisch-Waugh-Lovell (FWL) theorem says that the OLS coefficient in the regression of \(Y_i\) on \(D_i\) and \(X_i\) is numerically equivalent to the following procedure:
- Regress \(D_i\) on \(X_i\) to get residuals \(\hat V_i\).
- Regress \(Y_i\) on \(\hat V_i\) to get an estimate \(\hat\beta\).
Furthermore, in the second step, we can replace \(Y_i\) with the residuals from regreessing \(Y_i\) on \(X_i\), and we will also recover the OLS coefficient on \(D_i\) in the regression of \(Y_i\) on \(D_i\) and \(X_i\).
The basic idea of double/debiased lasso is to use lasso on each step in the FWL theorem (hence the two regressions in the “double lasso”). This helps ameliorate omitted variable bias that we would get if we just used lasso in the main regression (hence “debiased lasso”).
We won’t prove the FWL theorem here, but let’s verify it numerically in our regressions:
# coefficient on d from our original regression glm(y ~ d + t + phone*s + .^2, data=controls)
summary(interact)$coef["d", ] Estimate Std. Error t value Pr(>|t|)
0.2797107 0.1807311 1.5476619 0.1223753
y_resid <- glm(y ~ t + phone * s + .^2, data = controls)$residuals
d_resid <- glm(d ~ t + phone * s + .^2, data = controls)$residuals
# coefficient from residual formulation from FWL theorem (same as original regression)
coef(glm(y_resid ~ d_resid))[2] d_resid
0.2797107
# coefficient from other formulation from FWL theorem (same again)
coef(glm(y ~ d_resid))[2] d_resid
0.2797107
Causal trees
We’re interested in predicting the treatment effect for observation \(n+1\) using \(X_{n+1}\) (as opposed to predicting the raw outcome).
This is typically more useful than predicting the raw outcome when the goal is a rule that decides whether to treat observation \(n+1\) using covariates \(X_{n+1}\).
Applications:
- Identify individuals that would benefit most from, say, a scholarship program.
- Personalized medicine: decide how to treat a disease using covariates \(X_{n+1}\), which could include detailed genetic data.
- Marketing: decide who gets website A vs website B based on browser data \(X_{n+1}\) after A-B testing
We’ll introduce propensity score weighting
The basic idea is to transform the outcome variable so that we can predict the treatment effect for observation \(n+1\) using \(X_{n+1}\) (as opposed to predicting the raw outcome).
This idea and related methods have been proposed for regression trees/forests under the name “causal trees/forests” in some recent papers (Athey and Imbens (2016), Wager and Athey (2018)), but we’ll give it a more general treatment (the above papers include references that apply similar ideas in other settings).
To define our transformed variable using the propensity score, we’ll first review the potential outcomes framework and selection-on-observables assumption.
Potential outcomes framework
Recall the potential outcomes framework with binary treatment and the selection-on-observables assumption:
\(Y_i=g(D_i,X_i,\varepsilon_i)\)
Selection on observables: assume \(D_i\) independent of \(\varepsilon_i\) given \(X_i\)
We showed that the regression function \(E[Y_i|D_i=d,X_i=x]\) can be used to recover the conditional average treatment effect: \[\begin{align} &\text{CATE}(x) =E[\tau_i|X_i=x] \\ &=E[g(1,x,\varepsilon_i)-g(0,x,\varepsilon_i)|X_i=x]=f(1,x)-f(0,x). \end{align}\] where we’ve introduced the notation \(\tau_i\) for the unit-level treatment effect \(g(1,X_i,\varepsilon_i)-g(0,X_i,\varepsilon_i)\).
We also introduced the propensity score: \[ p(x)=P(D_i=1|X_i=x). \]
With observational data, we can estimate the propensity score by regressing \(D_i\) on \(X_i\).
We’ll focus here on an experimental setting in which \(p(x)\) is chosen by the researcher and therefore known.
Propensity score weighting
Using the propensity score, we can form a transformed outcome \[ \tilde Y_i = \frac{Y_i\cdot D_i}{p(X_i)} - \frac{Y_i\cdot (1-D_i)}{1-p(X_i)} \]
Basic idea: to predict \(\tau_{n+1}\), we do supervised learning (regression) of \(\tilde Y_i\) on \(X_i\).
So, we just replace \(Y_i\) with \(\tilde Y_i\) and then use whatever supervised learning (regression) method we would have use before (lasso, trees, forests, etc.).
Why does this work? Note that \[ E\left[\frac{Y_i\cdot D_i}{p(X_i)}|X_i=x\right] = \frac{E[g(1,x,\varepsilon_i)D_i|X_i=x]}{p(x)} \] Since \(Y_i=g(1,x,\varepsilon)\) when \(D_i=1\). Now, by the selection on observables assumption, \(g(1,x,\varepsilon_i)\) and \(D_i\) are independent conditional on \(X_i=x\), so \[ E[g(1,x,\varepsilon_i)D_i|X_i=x] =E[g(1,x,\varepsilon_i)|X_i=x]P(D_i=1|X_i=x) \] plugging this back in to the previous display, the term \(p(x)\) cancels in the numerator and denominator and we get \[ E\left[\frac{Y_i\cdot D_i}{p(X_i)}|X_i=x\right] =E[g(1,x,\varepsilon_i)|X_i=x]. \]
Now apply the same reasoning to the other term \(\frac{Y_i\cdot (1-D_i)}{1-p(X_i)}\) in \(\tilde Y_i\), to get \[ E[\tilde Y_i|X_i=x] = \text{CATE}(x). \]
Thus, we can regress \(\tilde Y_i\) on \(X_i\) to get the CATE.
Why the transformed outcome?
Alternatively, we could regress \(Y_i\) on \(X_i\) and \(D_i\) and use \(\hat f(1,x)-\hat f(0,x)\) to predict the CATE.
What’s the difference? Which is better?
A key point is that the bias-variance tradeoff that determines the optimal procedure (optimal lasso penalty, tree depth, location of tree cutpoints, etc.) is different for estimating \(\text{CATE}(x)=f(1,x)-f(0,x)\) vs estimating the regression function \(f(d,x)\) itself.
For example, suppose \(f(1,x)\) and \(f(0,x)\) both vary a lot with \(x\), but \(\text{CATE}(x)=f(1,x)-f(0,x)\) does not (i.e. raw outcomes vary a lot with \(X_i\) but treatment effects do not).
For estimating \(f(d,x)\) with regression trees, we want a more complex tree (many cutpoints and many leaves) to find heterogeneity in \(f(d,x)\)
For estimating \(\text{CATE}(x)\), we want a less complex tree with fewer leaves.
By using \(\tilde Y_i\), we directly target the CATE.
Disadvantage of propensity score weighting vs \(\hat f(1,x)-\hat f(0,x)\): the error term in the regression with the transformed outcome \(\tilde Y_i\) can have higher variance (since \(D_i\) is not included as a predictor in the regression).
Aggregate level treatment
In many applications in economics, it’s common to assign treatment at some aggregate level (e.g. development experiments at the village level)
In such settings, it’s best to do our analysis at the level the treatment was assigned, particularly when performing resampling methods such as bagging and cross-validation.
The key issue here is that we want to have independence across units when we perform bagging/cross-validation.
Example: we randomly assign a treatment (say, building a school) across villages, and then survey household.
We should resample at the village level when performing cross-validation, so that we don’t “cheat” by using households in the same village to predict each other.
Otherwise, we’ll overestimate the accuracy of our procedure when we use it to predict outcomes in a new village.
See Athey and Wager (2019), Section 1.2, for discussion in the context of trees/forests.
Estimating the propensity score
With observational data, we may be willing to assume selection-on-observables.
Then we have the same framework as above, but we don’t know \(p(x)\).
In this case, we could estimate \(p(x)\) and then use propensity score weighting.
This approach can work if we’re sufficiently flexible about modeling \(p(x)\) and \(X_i\) is low dimensional (see, for example, Hirano et al. (2003)).
However, bias in \(\hat p(x)\) will in general propogate to the regression with the transformed outcome \(\tilde Y_i\), so we should be cautious of this approach, particularly in settings where \(X_i\) is of moderate to high dimension.
Application: National Supported Work demonstration
We’ll apply this to data from the National Supported Work (NSW) demonstration, an experiment involving a job training program in the 1970s.
Variables:
re78: wage in 1978, after the program, in $1,000s (outcome variable)treated: indicator for treatmentre74: wage in 1974 (before program)re75: wage in 1974 (before program)ue74: wage in 1974 (before program)ue75: wage in 1974 (before program)- demographic indicator variables
ageeducationblackhispanicmarried
First, read in the data:
set.seed(0)
nsw_exper <- read.csv("./data/dw_experimental_data.csv")
head(nsw_exper) treated age education black hispanic married re74 re75 ue74 ue75 re78
1 FALSE 23 10 TRUE FALSE FALSE 0 0 TRUE TRUE 0.000000
2 FALSE 26 12 FALSE FALSE FALSE 0 0 TRUE TRUE 12.383680
3 FALSE 22 9 TRUE FALSE FALSE 0 0 TRUE TRUE 0.000000
4 FALSE 18 9 TRUE FALSE FALSE 0 0 TRUE TRUE 10.740080
5 FALSE 45 11 TRUE FALSE FALSE 0 0 TRUE TRUE 11.796470
6 FALSE 18 9 TRUE FALSE FALSE 0 0 TRUE TRUE 9.227052
dim(nsw_exper)[1] 445 11
- Participation in the program was randomized independently of these covariates, so we can assume that the treatment is randomized with \(p(x)=p\) not depending on \(x\). Let’s check this assumption by running a logit regression:
glm_treat <- glm(treated ~ . - re78, data = nsw_exper, family = "binomial")
summary(glm_treat)
Call:
glm(formula = treated ~ . - re78, family = "binomial", data = nsw_exper)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -0.47363 0.82442 -0.575 0.5656
age 0.01426 0.01421 1.004 0.3156
education 0.04998 0.05641 0.886 0.3756
blackTRUE -0.34766 0.36065 -0.964 0.3351
hispanicTRUE -0.92849 0.50661 -1.833 0.0668 .
marriedTRUE 0.17604 0.27488 0.640 0.5219
re74 -0.03393 0.02926 -1.160 0.2462
re75 0.01221 0.04714 0.259 0.7956
ue74TRUE -0.15160 0.37164 -0.408 0.6833
ue75TRUE -0.37195 0.31773 -1.171 0.2417
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 604.2 on 444 degrees of freedom
Residual deviance: 592.5 on 435 degrees of freedom
AIC: 612.5
Number of Fisher Scoring iterations: 4
The description of the program as assigning participation independently of \(X_i\) seems to fit the data: none of the coefficients in the logit regression are statistically significant.
Using this assumption, let’s make the transformed variable \(\tilde Y_i\), using the proportion of treated observations in the data to estimate \(p\).
p_hat <- mean(nsw_exper$treated)
y_tilde <- nsw_exper$re78 * nsw_exper$treated / p_hat - nsw_exper$re78 * (1 - nsw_exper$treated) / (1 - p_hat)- Now we can estimate the CATE by regression \(\tilde Y_i\) on \(X_i\) using any of the methods we’ve learned. Let’s start with OLS:
# let's estimate a linear model for the CATE using OLS
lm_y_tilde <- lm(y_tilde ~ . - treated - re78, data = nsw_exper)
summary(lm_y_tilde)
Call:
lm(formula = y_tilde ~ . - treated - re78, data = nsw_exper)
Residuals:
Min 1Q Median 3Q Max
-66.872 -8.812 -1.850 5.066 135.924
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -14.29635 7.21074 -1.983 0.04804 *
age 0.09988 0.12449 0.802 0.42281
education 1.08410 0.48767 2.223 0.02673 *
blackTRUE -0.18558 3.19817 -0.058 0.95375
hispanicTRUE -3.38106 4.27769 -0.790 0.42973
marriedTRUE 2.72916 2.42235 1.127 0.26051
re74 0.11518 0.23891 0.482 0.62997
re75 0.06112 0.40964 0.149 0.88147
ue74TRUE 8.82304 3.26101 2.706 0.00709 **
ue75TRUE -6.61352 2.80955 -2.354 0.01902 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 17.91 on 435 degrees of freedom
Multiple R-squared: 0.04615, Adjusted R-squared: 0.02642
F-statistic: 2.339 on 9 and 435 DF, p-value: 0.01396
Not much evidence of heterogeneity in CATE, although maybe some by education and employment.
Let’s try regression trees:
tree_y_tilde <- tree(y_tilde ~ . - treated - re78 - ue74 - ue75, data = nsw_exper, mindev = 0, mincut = 10) # we won't include the unemplyment indicator since a tree can "find" it by making a cutpoint at wage just above 0
cv_tree_y_tilde <- cv.tree(tree_y_tilde)
(best_size_y_tilde <- cv_tree_y_tilde$size[which.min(cv_tree_y_tilde$dev)])[1] 2
prune.tree(tree_y_tilde, best = best_size_y_tilde)node), split, n, deviance, yval
* denotes terminal node
1) root 445 146200 1.794
2) education < 12.5 423 122900 1.005 *
3) education > 12.5 22 18000 16.960 *
The tree specification finds some heterogeneity in treatment effects by education, but doesn’t split on anything else.
Let’s try this with forests:
rf_y_tilde <- ranger(y_tilde ~ . - treated - re78 - ue74 - ue75, data = nsw_exper, write.forest = TRUE, num.tree = 200, min.node.size = 5, importance = "impurity", keep.inbag = TRUE) # we won't include the unemplyment indicator since a tree can "find" it by making a cutpoint at wage just above 0
barplot(sort(importance(rf_y_tilde), decreasing = TRUE), las = 2)
The random forest is more difficult to interpret than trees or linear regression, and the variable importance plot doesn’t tell us much (the binary indicator variables are less “important,” but this might just be because they only get one split point).
We can get some idea of what the random forest is doing by plotting predicted values against covariates.
par(mfrow = c(1, 3))
rf_y_tilde_predictions <- predict(rf_y_tilde, data = nsw_exper, type = "se") # type="se" saves standard errors, which we'll use later
plot(nsw_exper$re75, rf_y_tilde_predictions$predictions, xlab = "wage in 1975", ylab = "predicted CATE")
plot(nsw_exper$age, rf_y_tilde_predictions$predictions, xlab = "age", ylab = "predicted CATE")
plot(nsw_exper$education, rf_y_tilde_predictions$predictions, xlab = "education", ylab = "predicted CATE")
The predicted CATE varies a lot and seems to take on implausible values for many of the observations.
Predicted CATE is as low as $-10,000 or as high as $20,000 for many observations (outcome is in $1,000s)
Estimated (unconditional) ATE is
mean(y_tilde)=1.7943424 or $1,794.It seems implausible that the effect would vary so much relative to its average, or that it would be negative and large in magnitude for many individuals in the sample.
This seems to suggest that the random forest is overfitting.
Is there any evidence that \(\text{CATE}(x)\) isn’t constant? The forest is more difficult to interpret, but one way of looking at this is to look at the \(R^2\).
- A large \(R^2\) means that \(X_i\) helps predict the transformed outcome through the treatment effect, so that \(\text{CATE}(x)\) varies a lot relative to overall variation in the transformed outcome.
Ideally, we’d look at out-of-sample \(R^2\). The
ranger()function outputs something similar by computing out-of-bag \(R^2\) using the out-of-bag deviance we discussed above:
rf_y_tilde$r.squared[1] -0.04668346
The out-of-bag \(R^2\) is negative, suggesting that the \(\text{CATE}\) doesn’t vary much.
This also suggests that the forest is overfitting: a negative out-of-sample \(R^2\) means we do better by just using the (unconditional) sample mean of the transformed outcome.
Let’s look at the predicted values and standard errors computed using an out-of-bag method from Wager et al. (2014):
rf_y_tilde_lower_cis <- rf_y_tilde_predictions$predictions - 2 * rf_y_tilde_predictions$se
rf_y_tilde_upper_cis <- rf_y_tilde_predictions$predictions + 2 * rf_y_tilde_predictions$se
# proportion of lower CIs that are greater than the (unconditional) ATE estimate:
mean(rf_y_tilde_lower_cis > mean(y_tilde))[1] 0.1348315
# proportion of upper CIs that are less than the (unconditional) ATE estimate:
mean(rf_y_tilde_upper_cis < mean(y_tilde))[1] 0.2516854
# proportion of upper CIs that are less than 0
mean(rf_y_tilde_upper_cis < 0)[1] 0.1146067
- The results seem to suggest that \(\text{CATE}(x)\) is above or below the average for many values of \(x\) and that this is statistically significant (including about 11% of upper CIs below 0), which doesn’t seem to match the results we saw for out-of-bag \(R^2\).
“Honest” trees and post-selection inference
We’ll cover some ideas for getting CIs in settings that involve model selection
First, we’ll introduce a simple version of the idea in the context of regression trees.
Honest trees
We want a CI for our estimate \(\hat f(x)\) formed from a regression tree.
Naive approach:
Tree estimate \(\hat f(x)\) is the sample mean of \(Y_i\) over \(i\) such that \(X_i\) is in the same leaf \(R_\ell\) as \(x\): \[ \hat f(x)=\bar Y_{\ell}=\frac{1}{N_\ell} \sum_{X_i\in R_\ell} Y_i \] where \(N_\ell=\#\{i: X_i\in R_\ell\}\) and we use the notation \(\bar Y_{\ell}\) for the sample mean within leaf \(\ell\).
This suggests forming a standard error and CI for \(\hat f(x)\) by treating this leaf as our sample: \[ \text{se}(x)=\frac{\widehat{\text{sd}}_\ell}{\sqrt{N_\ell}} \quad \text{where} \quad \widehat{\text{sd}}_\ell^2 = \frac{1}{N_\ell}\sum_{X_i\in R_\ell} (Y_i-\bar Y_\ell)^2 \] Confidence interval: \[ \hat f(x)\pm 2\cdot\text{se}(x). \]
Two issues with the “naive approach”:
The leaf is chosen from split points based on the data \(Y_i\), leading to overfitting that is ignored by the naive CI.
The naive CI ignores bias from averaging over observations \(X_i\) where \(X_i\ne x\)
“Honest” trees address issue (1) using sample splitting.
We’ll discuss issue (2) later, but the punchline will be that we’re ignoring it by reinterpreting our CI or modifying the tree to make it “undersmooth” (similar to what we discussed for nonparametric CIs in the regression discontinuity problem).
Honest trees algorithm
- A simple version of the honest trees algorithm proposed in Athey and Imbens (2016) is as follows.
Split the sample into two folds. Grow and prune a tree using observations in fold 1 (i.e. grow a large tree and use cost-complexity pruning).
Using the tree computed from fold 1, form estimates and CIs using the observations in fold 2: \[ \hat f(x) = \bar Y_{2,\ell} = \frac{1}{N_{2,\ell}}\sum_{X_i\in R_\ell, i \text{ in fold }2} Y_i \] where \(N_{2,\ell}=\#\{i: X_i\in R_\ell, X_i \text{ in fold }2\}\) and \(\bar Y_{2,\ell}\) denotes the sample mean of observations in fold 2 and leaf \(\ell\), \[ \text{se}(x)=\frac{\widehat{\text{sd}}_{2,\ell}}{\sqrt{N_{2,\ell}}} \quad \text{where} \quad \widehat{\text{sd}}_{2,\ell}^2 = \frac{1}{N_{2,\ell}}\sum_{X_i\in R_{2,\ell}} \]
Illustration in simple example
To illustrate the issues with using the same data to choose the fold and form CIs, let’s consider a simple example.
We’ll grow a tree with just a data set with a single covariate \(X\) and \(E[Y_i|X_i]=0\).
We’ll grow the tree out to
mincut=20so that we have a reasonable number of observations per leaf to form a CI, but we won’t bother with cost-complexity pruning.
set.seed(0)
n <- 1000
x <- runif(n)
y <- rnorm(n)
simple_tree <- tree(y ~ x, mindev = 0, mincut = 20)
plot(y ~ x, xlim = c(0, 1))
new_x <- seq(0, 1, length = 1000)
lines(new_x, predict(simple_tree, newdata = data.frame(x = new_x)), col = "red", lwd = 2)
From the plot, it looks like our estimate wiggles around a lot, even though our true regression function is constant.
We forced the tree to be somewhat “overgrown” by setting
mindev=0, so we should expect some overfitting (although we’ve constrained it by settingmincut=20).Nonetheless, we’d like our CI to contain the true regression function (here, the constant function \(0\)) “95% of the time”
Let’s construct the “naive CI” for each point \(X_i=x\) and see how many of them contain zero.
leaves <- predict(simple_tree, type = "where") # type="where" outputs the leaf for each new data point, rather than the prediction
estimates <- rep(NA, times = length(leaves))
ses <- rep(NA, times = length(leaves))
for (i in 1:length(leaves))
{
estimates[i] <- mean(y[leaves == leaves[i]])
ses[i] <- sd(y[leaves == leaves[i]]) / sqrt(sum(leaves == leaves[i]))
}
# proportion of CIs that contain 0 (the true regression function)
mean(estimates + 2 * ses > 0 & estimates - 2 * ses < 0)[1] 0.664
The CIs seem to by undercovering. Why?
Suppose we happen to have \(Y_i>0\) for several observations with nearby \(X_i\).
The tree will find this by grouping these observations together in a leaf.
The naive CI does not reflect the fact that the cutpoints were designed to group large \(Y_i\)’s together.
Now let’s try this with honest trees.
fold1 <- sample(n, size = round(n / 2), replace = FALSE)
honest_tree <- tree(y ~ x, mindev = 0, mincut = 20, subset = fold1)
x_fold2 <- x[-fold1]
y_fold2 <- y[-fold1]
fold2_leaves <- predict(honest_tree, newdata = data.frame(x = x_fold2), type = "where") # type="where" outputs the leaf for each new data point, rather than the prediction
honest_estimates <- rep(NA, times = length(fold2_leaves))
honest_ses <- rep(NA, times = length(fold2_leaves))
for (i in 1:length(fold2_leaves))
{
honest_estimates[i] <- mean(y_fold2[fold2_leaves == fold2_leaves[i]])
honest_ses[i] <- sd(y_fold2[fold2_leaves == fold2_leaves[i]]) / sqrt(sum(fold2_leaves == fold2_leaves[i]))
}
# proportion of CIs that contain 0 (the true regression function)
mean(honest_estimates + 2 * honest_ses > 0 & honest_estimates - 2 * honest_ses < 0)[1] 0.956
- Using sample splitting to form an “honest” tree seems to help with coverage!
Random forests
A disadvantage of sample splitting is that we lose data: we use fold 1 to grow the tree, and then we only use observations in fold 2 in our final estimates.
However, we can reverse the order of the split and use fold 2 to grow our tree and fold 2 to get our estimates.
This gives a random forest (a very simple one with two trees). More generally, we can form larger forests by growing many “honest trees.”
By always using a different sample to grow the tree and form our final estimates, we the issues with using the same data to form split points and estimates, which was a problem for our CIs.
This is related to the idea of using out-of-bag observations to compute standard errors, which we tried using the
rangerpackage in our application to the NSW data.Standard errors are no longer as simple as before, since we’re averaging many trees, but formulas are available in Wager and Athey (2018), and are implemented in R packages by these authors.
Post-selection inference
Honest trees are an application of the general idea of using sample splitting to deal with the issue of post-selection inference (doing inference on a model that has been selected) based on the data
We can also apply this to other versions of model selection, such as lasso (where we interpret lasso as selecting which coefficients are used in a regression model)
General algorithm:
Split the data into two folds. Use fold 1 to select the model:
For regression trees: use fold 1 to grow and prune a tree using cost-complexity pruning and cross-validation (as described above)
For lasso: use fold 1 to run lasso with cross-validation. Save the identities of the nonzero coefficients as the “selected model”
Report estimates and CIs formed from the “selected model” from step 1
For regression trees: estimates and CIs formed from observations in fold 2 averaged over each leaf with the tree formed in step 1 (as described above)
For lasso: run OLS on the “selected model” from step 1, by regressing \(Y_i\) on the selected covariates (the ones with nonzero coefficients in step 1), using the data from fold 2 and reporting the usual estimates and standard errors
Interpreting post-selection CIs
The post-selection CI described above is a CI for an object that is itself random: it depends on the model selection procedure in the first fold.
For example, recall that our regression tree for the CATE after cost-complexity pruning only had two leaves, with a single split on education:
prune.tree(tree_y_tilde, best = best_size_y_tilde)node), split, n, deviance, yval
* denotes terminal node
1) root 445 146200 1.794
2) education < 12.5 423 122900 1.005 *
3) education > 12.5 22 18000 16.960 *
Suppose we got this tree from fold 1 of our sample, and we formed a CI from an “honest tree” by taking the sample mean within each leaf using fold 2. How should we interpret this?
While the regression tree is, in principle, an estimate of the average treatment effect conditional on all covariates (age, education, previous wages, etc.), it’s safer to interpret the procedure as giving a CI for averages within each leaf node.
So, in this case, we’d interpret the procedure as giving us average treatment effect estimates and CIs conditional on education \(<12.5\) and education \(>12.5\).
If we reran the procedure again with different data, we’d choose a different model based on fold 1, and we’d have a post-selection CI for a treatment effect that averages over some other leaf.
One way of thinking of this is: we use fold 1 to find interesting variables to split on, and then we examine treatment effect heterogeneity along these variables in step 2.
Note that we need to be particularly cautious if we are relying on regression to control for covariates (i.e. if we don’t have experimental data so that we aren’t weighting by a known propensity score).
In this example, we only split on education, so we clearly aren’t controlling for other variables!
A similar comment holds for post-selection inference in lasso: we might omit relevant control variables (which is why the “double/debiased lasso” procedures we discussed in a previous lecture add some variables back in).
Application: CATEs in NSW data
Let’s apply a simple version of the honest tree idea to estimate CATEs in the NSW data using the transformed outcome.
We’ll randomly choose half of our data to be the first fold, which we’ll use to build our tree:
set.seed(0)
fold1 <- sample(length(y_tilde), size = round(length(y_tilde) / 2), replace = FALSE)
tree_y_tilde_fold1 <- tree(y_tilde ~ . - treated - re78 - ue74 - ue75, data = nsw_exper, subset = fold1)
summary(tree_y_tilde_fold1)
Regression tree:
tree(formula = y_tilde ~ . - treated - re78 - ue74 - ue75, data = nsw_exper,
subset = fold1)
Variables actually used in tree construction:
[1] "education" "age" "re74" "re75"
Number of terminal nodes: 6
Residual mean deviance: 328.4 = 70930 / 216
Distribution of residuals:
Min. 1st Qu. Median Mean 3rd Qu. Max.
-37.42000 -8.60200 0.02131 0.00000 4.01200 113.90000
- Next, we’ll construct our “honest” estimates and CIs, using the observations that are not in fold 1:
nsw_exper_fold2 <- nsw_exper[-fold1, ]
y_tilde_fold2 <- y_tilde[-fold1]
nsw_fold2_leaves <- predict(tree_y_tilde_fold1, data = nsw_exper_fold2, type = "where") # type="where" outputs the leaf for each new data point, rather than the prediction
nsw_honest_estimates <- rep(NA, times = length(nsw_fold2_leaves))
nsw_honest_ses <- rep(NA, times = length(nsw_fold2_leaves))
for (i in 1:length(nsw_fold2_leaves))
{
nsw_honest_estimates[i] <- mean(y_tilde_fold2[nsw_fold2_leaves == nsw_fold2_leaves[i]])
nsw_honest_ses[i] <- sd(y_tilde_fold2[nsw_fold2_leaves == nsw_fold2_leaves[i]]) / sqrt(sum(nsw_fold2_leaves == nsw_fold2_leaves[i]))
}
nsw_honest_lower_cis <- nsw_honest_estimates - 2 * nsw_honest_ses
nsw_honest_upper_cis <- nsw_honest_estimates + 2 * nsw_honest_ses
# proportion of lower CIs that are greater than the (unconditional) ATE estimate:
mean(nsw_honest_lower_cis > mean(y_tilde))[1] 0.03153153
# proportion of upper CIs that are less than the (unconditional) ATE estimate:
mean(nsw_honest_upper_cis < mean(y_tilde))[1] 0
# proportion of upper CIs that are less than 0
mean(nsw_honest_upper_cis < 0)[1] 0
With the honest CIs, we find little evidence of treatment effect heterogeneity: almost all CIs contain the estimate of the unconditional ATE.
Note that our CIs average over each of the 6 leaves, so, even though we get a CIC for each observation, there are really only 6 CIs. Here are the estimates and standard errors by leaf:
unique_leaves <- unique(nsw_fold2_leaves)
for (i in 1:length(unique_leaves))
{
# The leaves in unique_leaves were extracted from predict() with the "where" option. This gives a number which corresponds to the row of tree_y_tilde_fild1$frame which describes this leaf, with the row name giving the leaf label used in the tree printout.
cat("leaf label:", rownames(tree_y_tilde_fold1$frame)[unique_leaves[i]], " estimate: ", unique(nsw_honest_estimates[nsw_fold2_leaves == unique_leaves[i]]), " std. err.:", unique(nsw_honest_ses[nsw_fold2_leaves == unique_leaves[i]]), " obs. in leaf:", sum(nsw_fold2_leaves == unique_leaves[i]), "\n")
}leaf label: 4 estimate: -0.6018746 std. err.: 1.406771 obs. in leaf: 117
leaf label: 44 estimate: 5.174653 std. err.: 5.312938 obs. in leaf: 23
leaf label: 10 estimate: 1.379577 std. err.: 1.767224 obs. in leaf: 57
leaf label: 3 estimate: 1.40549 std. err.: 4.104053 obs. in leaf: 9
leaf label: 23 estimate: -8.713118 std. err.: 8.355731 obs. in leaf: 9
leaf label: 45 estimate: 14.28563 std. err.: 5.475782 obs. in leaf: 7
- The leaf labels correspond to the ones in the tree printout:
tree_y_tilde_fold1node), split, n, deviance, yval
* denotes terminal node
1) root 222 84090 2.8720
2) education < 12.5 213 71480 1.8890
4) education < 10.5 117 22740 -0.6436 *
5) education > 10.5 96 47080 4.9770
10) age < 25.5 57 8129 1.7200 *
11) age > 25.5 39 37460 9.7370
22) re74 < 2.17518 30 33240 13.8600
44) re75 < 1.04371 23 12190 8.6020 *
45) re75 > 1.04371 7 18330 31.1400 *
23) re74 > 2.17518 9 2009 -4.0120 *
3) education > 12.5 9 7536 26.1300 *
As we discussed above, it’s best to interpret these as estimates and CIs for the average treatment effect within each leaf (e.g. for the leaf labeled 4 we get an estimate of the average treatment effect for individuals with 10 years or less of education).
Note also that some leaves contain very few observations, so we should be cautious when interpreting these CIs (the normal approximation probably isn’t very reliable).