Week 11: Trees and Forests

PS 818 - Data Analysis with Statistical Models

Anton Strezhnev

University of Wisconsin-Madison

November 16, 2026

Trees and Forests

\[ \DeclareMathOperator*{\argmin}{arg\,min} \DeclareMathOperator*{\argmax}{arg\,max} \]

Previously

  • Flexible regression
    • Basis expansions: polynomials, step functions, splines
    • More flexibility \(\leadsto\) less bias, more variance
  • Regularization
    • Penalized regression: ridge (\(L_2\)) and lasso (\(L_1\))
    • Penalties are priors
    • Choose the penalty by cross-validation
  • Many predictors: predicting the 2020 vote in the CES with 1,898 columns

This week

  • Trees
    • Recursive partitioning: regression trees
  • Ensembles of trees
    • Bagging and random forests: average many trees
    • Boosting: add up many small trees fit to residuals of the previous trees
    • BART: a sum of small trees keeping the trees small via priors on the tree paramters.
  • Running example: “many predictors” in the CES survey data.

Going forward

  • Week 12 - Flexible Regression: Kernels and Gaussian Processes
  • Week 13 - Causal Inference with Flexible Regression
  • Week 14 - Working with “Big” Datasets

The data

  • The same data as Week 10: 2020 Biden and Trump voters in the 2023 CES. 1 = Trump, 0 = Biden.
ces_raw <- read_dta("../week8/data/CCES23_Common_OUTPUT.dta.gz") # the file from Week 8
ces <- ces_raw %>%
  mutate(age = 2023 - birthyr) %>%
  filter(presvote20post %in% 1:2, age <= 90) %>% # Biden or Trump voters
  mutate(trump = as.numeric(presvote20post == 2),
         w = commonweight / mean(commonweight)) # survey weights, rescaled to average 1
covs <- c("gender4", "educ", "race", "hispanic", "inputstate", "region", "urbancity", "employ", "student", "marstat",
          "child18", "ownhome", "faminc_new", "religpew", "pew_bornagain", "pew_religimp", "pew_churatd", "pew_prayer",
          "milstat_1", "milstat_3", "healthins_2", "sexuality", "immstat", "internethome",
          "CC23_300_1", "CC23_300_2", "CC23_300_3", "CC23_300_4", "CC23_305_4", "CC23_305_6")
ces_covs <- ces %>% select(all_of(covs)) %>%
  mutate(across(everything(), ~ fct_na_value_to_level(fct_drop(as_factor(.x)), "missing")))
dat <- bind_cols(ces %>% select(trump, w, age), ces_covs) %>%
  mutate(vote = factor(trump, levels = 0:1, labels = c("Biden", "Trump")))
fml <- reformulate(c("age", covs), "trump") # trump ~ age + gender4 + educ + ...

The data

  • Trees take the raw variables. No dummies, interactions, or basis functions.
dim(dat)
[1] 17675    34
  • The same 10 folds and the same (weighted) error as Week 10
set.seed(53703)
folds <- sample(rep(1:10, length.out = nrow(dat)))
wmse <- function(err, w = dat$w) sum(w * err^2) / sum(w) # weighted mean squared error
cv_pred <- function(fit_fun) { # fit_fun: (train, test) -> predictions for test
  pred <- numeric(nrow(dat))
  for (k in 1:10) pred[folds == k] <- fit_fun(dat[folds != k, ], dat[folds == k, ])
  pred
}

Regression trees

  • A tree \(T\) partitions the covariate space into \(|T|\) non-overlapping hyper-rectangles \(R_1, \dotsc, R_{|T|}\)

    • These are the leaves
    • Each leaf predicts a constant \(\mu_m\). Collect them in \(M = (\mu_1, \dotsc, \mu_{|T|})\)

    \[g(x; T, M) = \sum_{m=1}^{|T|} \mu_m \mathbf{1}(x \in R_m)\]

  • For squared error, the best constant is the mean of \(Y\) among the observations in the leaf: \(\hat{\mu}_m = \bar{Y}_m\).

  • This is a step function, but the regions are chosen from the data.

  • Searching over every possible partition is computationally infeasible. Instead, trees are grown greedily by splitting on one variable at a time (Breiman et al. 1984).

  • For an introduction aimed at political scientists, see Montgomery and Olivella (2018).

Recursive binary splitting

  • For a continuous variable \(X_j\) and a cutpoint \(s\), a split divides the observations into

    \[R_{\text{left}}(j, s) = \{x : x_j < s\} \quad \text{and} \quad R_{\text{right}}(j, s) = \{x : x_j \ge s\}\]

  • Choose the variable and the cutpoint that minimize the residual sum of squares after the split:

    \[\min_{j, s} \bigg[\sum_{i: X_i \in R_{\text{left}}(j,s)} (Y_i - \bar{Y}_{\text{left}})^2 + \sum_{i: X_i \in R_{\text{right}}(j,s)} (Y_i - \bar{Y}_{\text{right}})^2\bigg]\]

  • Then repeat within each of the two regions, and so on, until a stopping rule (e.g. a minimum number of observations per leaf).

  • Greedy: each split is the best one available at the stage of the algorithm.

    • Can’t accept a less optimal split in one stage to get a more optimal one later.

A regression tree on age

  • Every possible cutpoint for age (all respondents)
split_rss <- function(x, s, y = dat$trump, w = dat$w) { # weighted RSS after splitting x at s
  left <- x < s
  sum(w[left] * (y[left] - weighted.mean(y[left], w[left]))^2) +
    sum(w[!left] * (y[!left] - weighted.mean(y[!left], w[!left]))^2)
}
cuts <- seq(21.5, 89.5, by = 1)
rss_age <- map_dbl(cuts, ~ split_rss(dat$age, .x))
cuts[which.min(rss_age)]
[1] 46.5

A regression tree on age

  • Keep splitting (each leaf needs at least 50 respondents), then prune back by cross-validation
age_tree <- rpart(trump ~ age, data = dat, weights = w,
                  control = rpart.control(cp = 0, minbucket = 50, xval = folds))
age_tree <- prune(age_tree, cp = age_tree$cptable[which.min(age_tree$cptable[, "xerror"]), "CP"])
sum(age_tree$frame$var == "<leaf>") # number of leaves
[1] 17
  • rpart takes our fold assignments through xval.

A regression tree on age

  • The tree selects a set of cutpoints automatically

Categorical predictors

  • For a categorical variable with \(L\) levels, a split allocates some levels to the left side of the tree and the rest to the right of the tree.
    • There are \(2^{L-1} - 1\) ways to do this. For state (\(L = 51\)), that’s about \(10^{15}\).
  • One trick is to sort the levels by their mean outcome.
  • Alternatively, just pass in all the unordered dummies (“one-hot encoding”) and let the model treat each as a distinct variable.

One tree for Trump vote

  • A regression tree for trump with all 31 predictors grown only two levels deep.
tree2 <- rpart(fml, data = dat, weights = w, control = rpart.control(maxdepth = 2, cp = 0))

Reading a tree

  • Each box shows the share voting Trump and the share of respondents in the box.

  • The first split is on religious tradition.

  • The second split depends on the first:

    • Among Christians, the next split is race.
    • Among all other respondents, the next split is religious tradition again.
  • The trees can find interactions

    • In this tree, race only matters as a predictor among Christians.

One more level

tree3 <- rpart(fml, data = dat, weights = w, control = rpart.control(maxdepth = 3, cp = 0))

How big should the tree be?

  • We can keep splitting until every leaf is tiny.

    • Small leaves \(\leadsto\) low bias, but very high variance (each leaf mean is based on a handful of respondents).
  • Cost-complexity pruning (Breiman et al. 1984): grow a big tree \(T_0\), then find the subtree \(T \subseteq T_0\) that minimizes

    \[\sum_{m=1}^{|T|} \sum_{i: X_i \in R_m} (Y_i - \bar{Y}_m)^2 + \alpha |T|\]

    where \(|T|\) is the number of leaves.

  • Another form of penalized regression - here, the penalty is on the number of leaves.

    • \(\alpha = 0\): the full tree. \(\alpha \to \infty\): no splits at all (the intercept).
    • Choose \(\alpha\) by cross-validation. rpart calls \(\alpha / \text{RSS}_{\text{root}}\) the complexity parameter cp.

Pruning by cross-validation

big_tree <- rpart(fml, data = dat, weights = w,
                  control = rpart.control(cp = 0, minbucket = 10, xval = folds))
cp_table <- as_tibble(big_tree$cptable) %>% mutate(leaves = nsplit + 1)
cp_best <- cp_table$CP[which.min(cp_table$xerror)]
cp_table %>% slice(c(1, which.min(xerror), n())) %>% select(CP, leaves, xerror)
# A tibble: 3 × 3
       CP leaves xerror
    <dbl>  <dbl>  <dbl>
1 0.0812       1  1.00 
2 0.00218     24  0.738
3 0          810  0.925
  • xerror is the CV error relative to the intercept-only model. The full tree has 810 leaves. Cross-validation retains 24.

Pruning by cross-validation

The pruned tree

  • The CV error of the pruned tree
pred_tree <- cv_pred(function(train, test) {
  predict(rpart(fml, data = train, weights = w, control = rpart.control(cp = cp_best, minbucket = 10, xval = 0)), test)
})
pred_deep <- cv_pred(function(train, test) {
  predict(rpart(fml, data = train, weights = w, control = rpart.control(cp = 0, minbucket = 10, xval = 0)), test)
})
c(pruned_tree = wmse(dat$trump - pred_tree), full_tree = wmse(dat$trump - pred_deep))
pruned_tree   full_tree 
      0.184       0.230 
  • The full tree overfits badly. Pruning it back to 24 leaves cuts the CV error substantially.

Trees: pros and cons

  • Pros
    • Small trees are easy to read and explain
    • Interactions and non-linearities are found automatically
  • Cons
    • Step functions are a poor approximation to smooth relationships
    • High variance: a small change in the data can change what gets split on!

Trees are unstable

  • Growing the same tree on bootstrapped samples of the data gives different results!
set.seed(818)
boot_trees <- map(1:2, function(b) {
  idx <- sample(nrow(dat), replace = TRUE)
  rpart(fml, data = dat[idx, ], weights = w, control = rpart.control(maxdepth = 2, cp = 0))
})
  • We’re splitting first on different variables across these draws.

Bagging

  • Bootstrap aggregation (Breiman 1996): grow a deep tree on each of \(B\) bootstrap samples, and average their predictions

    \[\hat{f}_{\text{bag}}(x) = \frac{1}{B}\sum_{b=1}^B \hat{f}^{*b}(x)\]

  • Each tree has low bias and high variance. Averaging keeps the low bias and reduces the variance.

  • How much? If each tree’s prediction has variance \(\tau^2\) and any two trees have correlation \(\rho\):

    \[\text{Var}\big(\hat{f}_{\text{bag}}(x)\big) = \rho \tau^2 + \frac{1 - \rho}{B}\tau^2\]

  • Bagged trees are correlated

    • On every bootstrap sample, the same strong predictors (race, religion) are the ones that the method splits on first.

Random forests

  • Random forests (Breiman 2001): bagging plus at each split only a random subset of \(m_{\text{try}}\) of the \(p\) predictors are candidates for splits.

  • Strong predictors can’t take the top split in every tree.

    • Trees are less correlated \(\leadsto\) smaller \(\rho\) \(\leadsto\) lower variance of the average.
    • Each individual tree is worse, but the forest tends to do better.
  • \(m_{\text{try}}\) as a tuning parameter - common default is \(m_{\text{try}} = p/3\)

    • Also need to set the minimum node size

Out-of-bag error

  • Each bootstrap sample leaves out about \((1 - 1/N)^N \approx e^{-1} \approx 37\%\) of the observations.

  • Out-of-bag (OOB) prediction: predict each observation using only the trees that it wasn’t used to estimate.

    • A built-in estimate of out-of-sample error that doesn’t need additional resampling!
    • “Cross-validation” is built in to the bootstrapping procedure.
  • Alternatively, we’ll often fit each tree to a subsample: a random fraction of the data (e.g. half), drawn without replacement. Same idea, and the other half is out of bag. Why?

    • No duplicates: each tree is fit to distinct observations.
    • Smaller subsamples overlap less, so the trees are less correlated.
    • Subsampled forests have some nice theoretical properties for inference (Athey, Tibshirani, and Wager 2019).

Random forests with grf

  • grf (Athey, Tibshirani, and Wager 2019) fits random forests.
    • We’ll code each factor’s levels in order of their weighted mean outcome in the training data and treat those as numeric values that the tree can split on.
encode <- function(train, newdata = train) { # numeric matrix; factor levels sorted by mean outcome in train
  map_dfc(c("age", covs), function(v) {
    if (!is.factor(newdata[[v]])) return(tibble(!!v := newdata[[v]]))
    lev_order <- train %>% group_by(lev = .data[[v]]) %>% summarize(m = weighted.mean(trump, w)) %>% arrange(m)
    tibble(!!v := match(as.character(newdata[[v]]), as.character(lev_order$lev)))
  }) %>% as.matrix()
}
X_all <- encode(dat)
rf_oob <- regression_forest(X_all, dat$trump, sample.weights = dat$w, mtry = 5, num.trees = 500,
                            honesty = FALSE, ci.group.size = 1, seed = 818)
wmse(dat$trump - predict(rf_oob)$predictions) # predict() with no new data: out-of-bag
[1] 0.162
  • Each tree is grown on half the data, without replacement, and considers mtry = 5 of the 31 predictors at each split.

Random forests with grf

  • Some grf options to know about:
    • sample.weights: used in the splits and the leaf means. sample.fraction = 0.5: each tree’s subsample.
    • min.node.size = 5: minimum node size - trees are grown deep and aren’t pruned.
    • honesty = FALSE: by default, grf grows honest trees, choosing the splits on one half of the subsample and estimating the leaf means on the other. Crucial for inference, but we’ll leave off for now.

Random forests: choosing mtry

rf_fit <- function(train, test, mtry) { # the factor coding is learned on the training folds only
  fit <- regression_forest(encode(train), train$trump, sample.weights = train$w, mtry = mtry, num.trees = 500,
                           honesty = FALSE, ci.group.size = 1, seed = 818)
  predict(fit, encode(train, test))$predictions
}
mtry_grid <- c(1, 3, 5, 10, 20, 31) # 31 = bagging
pred_rf_grid <- map(mtry_grid, function(m) cv_pred(function(train, test) rf_fit(train, test, m)))
rf_cv <- tibble(mtry = mtry_grid, cv_error = map_dbl(pred_rf_grid, ~ wmse(dat$trump - .x)))
rf_cv
# A tibble: 6 × 2
   mtry cv_error
  <dbl>    <dbl>
1     1    0.200
2     3    0.171
3     5    0.162
4    10    0.161
5    20    0.162
6    31    0.163

Random forests: choosing mtry

Variable importance

  • How do we figure out which predictors are “relevant” in a forest?

  • Split-based importance: how often the trees split on \(X_j\) (grf weights splits near the top more heavily).

  • Impurity importance, the total reduction in RSS from splits on \(X_j\).

  • Permutation importance: randomly shuffle \(X_j\) in held-out data, and measure how much the prediction error goes up.

    • Shuffling breaks the relationship between \(X_j\) and \(Y\) (and between \(X_j\) and the other predictors).
  • Split-based measures can be biased towards predictors with many possible split points (Strobl et al. 2007). Permutation importance on held-out data avoids that, but it’s noisier. Correlated predictors can also stand in for each other when one is shuffled.

Variable importance

  • Permutation importance on fold 1, for a forest grown on folds 2-10
mtry_best <- rf_cv$mtry[which.min(rf_cv$cv_error)]
train <- dat[folds != 1, ]; test <- dat[folds == 1, ]
rf_imp <- regression_forest(encode(train), train$trump, sample.weights = train$w, mtry = mtry_best,
                            num.trees = 500, honesty = FALSE, ci.group.size = 1, seed = 818)
X_test <- encode(train, test)
err_test <- wmse(test$trump - predict(rf_imp, X_test)$predictions, test$w)
set.seed(818)
imp <- list(split = setNames(variable_importance(rf_imp)[, 1], colnames(X_test)),
            permutation = map_dbl(set_names(colnames(X_test)), function(v) {
              X_perm <- X_test; X_perm[, v] <- sample(X_perm[, v]) # shuffle one predictor
              wmse(test$trump - predict(rf_imp, X_perm)$predictions, test$w) - err_test
            }))

Variable importance

  • Both agree on the top three: race, the importance of religion, and religious tradition.

Partial dependence

  • How do we plot the relationship between predictor and outcome? There’s no coefficient to interpret!

  • The partial dependence of \(f\) on age (Friedman 2001): set everyone’s age to \(a\), predict, and average

    \[\bar{f}_{\text{age}}(a) = \frac{1}{N} \sum_{i=1}^N \hat{f}(a, X_{i,-\text{age}})\]

  • Partial dependence is standardization: the same formula as the back-door adjustment in causal inference (Zhao and Hastie 2021).

    • If the other predictors block every back-door path from age to the vote, it’s the causal effect of age.
    • But some predictors are post-treatment to age!
  • We’ll rarely interpret these causally, but they can be useful diagnostic tools!

Partial dependence

rf_full <- regression_forest(X_all, dat$trump, sample.weights = dat$w, mtry = mtry_best, num.trees = 500,
                             honesty = FALSE, ci.group.size = 1, seed = 818)
set.seed(60639)
pd_sample <- sample(nrow(dat), 2000) # average over 2,000 respondents to save time
pd_ages <- seq(21, 90, by = 3)
pd_rf <- map_dbl(pd_ages, function(a) {
  X_pd <- X_all[pd_sample, ]; X_pd[, "age"] <- a # everyone gets age a
  weighted.mean(predict(rf_full, X_pd)$predictions, dat$w[pd_sample])
})

Boosting

  • Bagging and random forests grow trees independently and average them.

  • Boosting grows trees sequentially. Each tree is fit to whatever the previous trees didn’t explain (James et al. 2013):

    1. Start with \(\hat{f}(x) = \bar{Y}\) and residuals \(r_i = Y_i - \bar{Y}\).
    2. For \(b = 1, \dotsc, B\):
      • Fit a small tree \(\hat{f}^b(x) = g(x; \hat{T}_b, \hat{M}_b)\) (depth \(d\)) to the residuals \(r\)
      • Update \(\hat{f}(x) \leftarrow \hat{f}(x) + \nu \hat{f}^b(x)\) and \(r_i \leftarrow r_i - \nu \hat{f}^b(X_i)\)
    3. The fit is \(\hat{f}(x) = \bar{Y} + \nu \sum_{b=1}^B g(x; \hat{T}_b, \hat{M}_b)\)
  • Three tuning parameters:

    • \(B\), the number of trees. Unlike random forests, boosting overfits if \(B\) is too large.
    • \(\nu\), the shrinkage - how much should each tree contribute to the prediction, typically \(0.01\) to \(0.1\).
    • \(d\), the depth of each tree

Boosting

  • Train on folds 2-10 and keep fold 1 as a test set. Depth-2 trees, \(\nu = 0.1\), \(B = 300\)
train <- dat[folds != 1, ]; test <- dat[folds == 1, ]
nu <- 0.1; B <- 300
fit_train <- rep(weighted.mean(train$trump, train$w), nrow(train))
fit_test <- rep(weighted.mean(train$trump, train$w), nrow(test))
boost_trees <- list(); err_train <- err_test <- numeric(B)
for (b in 1:B) {
  train$r <- train$trump - fit_train # current residuals
  boost_trees[[b]] <- rpart(update(fml, r ~ .), data = train, weights = w,
                            control = rpart.control(maxdepth = 2, cp = 0, xval = 0))
  fit_train <- fit_train + nu * predict(boost_trees[[b]], train)
  fit_test <- fit_test + nu * predict(boost_trees[[b]], test)
  err_train[b] <- wmse(train$trump - fit_train, train$w)
  err_test[b] <- wmse(test$trump - fit_test, test$w)
}

Boosting: the first two trees

  • The first tree fits the outcome. The second tree fits to what the first tree didn’t explain.

Boosting: later trees

  • Later trees fit to what the main predictors fail to explain.

Boosting: error

Boosting and regularization

  • Each step moves the fit a small amount in the direction of a single tree.
  • Boosting is regularized in two ways:
    • Shrinkage: \(\nu < 1\) means no single tree takes over.
    • Early stopping: \(B\) chosen by cross-validation.
  • Gradient boosting (Friedman 2001) replaces the residuals with the negative gradient of any loss function: the log-likelihood of a logit for binary outcomes, a Poisson for counts, etc.
    • For a normal regression model, the negative gradient is the residual.

Boosting with gbm

  • gbm grows each tree on a random half of the training data (bag.fraction = 0.5). Depth \(d \in \{1, 3, 6\}\), up to 2,000 trees, \(\nu = 0.05\)
ntree_grid <- seq(50, 2000, by = 50)
gbm_cv <- function(depth) {
  pred <- matrix(NA, nrow(dat), length(ntree_grid))
  for (k in 1:10) {
    train <- dat[folds != k, ]
    set.seed(818)
    fit <- gbm(fml, data = train, weights = w, distribution = "gaussian", n.trees = 2000,
               interaction.depth = depth, shrinkage = 0.05, bag.fraction = 0.5, n.minobsinnode = 10)
    pred[folds == k, ] <- predict(fit, dat[folds == k, ], n.trees = ntree_grid)
  }
  pred
}
pred_gbm <- map(c(1, 3, 6), gbm_cv)
gbm_err <- map_dfr(set_names(pred_gbm, c(1, 3, 6)), .id = "depth",
                   ~ tibble(trees = ntree_grid, cv_error = apply(.x, 2, function(p) wmse(dat$trump - p))))
gbm_err %>% group_by(depth) %>% slice_min(cv_error)
# A tibble: 3 × 3
# Groups:   depth [3]
  depth trees cv_error
  <chr> <dbl>    <dbl>
1 1      1800    0.171
2 3       600    0.165
3 6       300    0.163

Boosting with gbm

Bayesian Additive Regression Trees

  • BART (Chipman, George, and McCulloch 2010) is also a sum of small trees, but with a full probability model:

    \[Y_i = \sum_{b=1}^{B} g(X_i; T_b, M_b) + \epsilon_i, \quad \epsilon_i \sim \text{Normal}(0, \sigma^2)\]

    • Each \(g(\cdot\,; T_b, M_b)\) is a tree as before: \(T_b\) is its structure (the splits) and \(M_b\) the values \(\mu_m\) in its leaves.
  • Instead of a learning rate and early stopping, priors keep each tree small and avoid having one tree dominate the fit:

    • A node at depth \(d\) splits with prior probability \(0.95(1 + d)^{-2}\). Most trees have 2 or 3 leaves (prior probability \(\approx 0.83\)).
    • Leaf values are regularized with a \(\text{Normal}(0, \sigma^2_\mu)\) prior. \(\sigma_\mu\) shrinks as the number of trees \(B\) grows (more regularization to counter more flexibility from additional trees)
    • A scaled inverse-\(\chi^2\) prior on \(\sigma^2\).
  • Penalties are priors: the tree prior prunes and the leaf prior shrinks.

Fitting BART

  • MCMC by Bayesian backfitting: a Gibbs sampler that updates one tree at a time, given the partial residuals of the other \(B - 1\) trees.

    • Like boosting, each tree is fit to what the others miss.
    • New tree structures are proposed (grow a leaf, prune a split, change a split rule) and accepted or rejected with Metropolis-Hastings.
  • For a binary outcome, use a probit link: \(\Pr(Y_i = 1 | X_i) = \Phi\big(\sum_b g(X_i; T_b, M_b)\big)\), with a latent normal variable for each observation.

  • The output is a set of posterior draws of \(f(x)\), so we get uncertainty for any prediction or summary of the fit.

  • The default priors tend to work well (Chipman, George, and McCulloch 2010; Hill, Linero, and Murray 2020).

BART with dbarts

  • Check the sampler: 4 chains on the full data, tracking a few functions of the fit
bart_chains <- bart(as.data.frame(dat[, c("age", covs)]), dat$trump, x.test = as.data.frame(dat[1:3, c("age", covs)]),
                    ntree = 200, nskip = 500, ndpost = 1000, nchain = 4, nthread = 4, combinechains = FALSE,
                    verbose = FALSE, seed = 818)
avg_share <- apply(pnorm(bart_chains$yhat.train), c(1, 2), weighted.mean, w = dat$w) # chain x draw
n_splits <- apply(bart_chains$varcount, c(1, 2), sum)                                  # splits across all 200 trees
draws <- array(c(t(avg_share), aperm(pnorm(bart_chains$yhat.test), c(2, 1, 3)), t(n_splits)), dim = c(1000, 4, 5),
               dimnames = list(NULL, NULL, c("avg_share", "resp_1", "resp_2", "resp_3", "n_splits")))
rm(bart_chains) # the full set of draws is large
  • resp_1-resp_3: predicted probabilities for the same three respondents as the bootstrap slide.

BART: traceplots

BART: convergence diagnostics

  • \(\hat{R}\) and effective sample sizes
bart_diag <- posterior::summarise_draws(posterior::as_draws_array(draws), "mean",
                                        ~ posterior::quantile2(.x, probs = c(.025, .975)), "rhat", "ess_bulk", "ess_tail")
bart_diag %>% kable(digits = 3)
variable mean q2.5 q97.5 rhat ess_bulk ess_tail
avg_share 0.478 0.472 0.484 1.01 610.0 2052.5
resp_1 0.187 0.097 0.299 1.06 73.7 166.8
resp_2 0.276 0.148 0.433 1.05 115.5 214.3
resp_3 0.047 0.014 0.106 1.23 12.5 31.3
n_splits 326.377 304.000 351.000 1.09 33.2 136.6

Reading the diagnostics

  • The average predicted share mixes well: \(\hat{R}\) = 1.01, and 610 effective draws out of 4,000.

  • Individual predictions and the number of splits mix much more slowly: \(\hat{R}\) up to 1.23, and as few as 13 effective draws.

    • Each tree changes by one small step (grow, prune, change a rule) per iteration, so the tree structures explore the posterior slowly.
    • Credible intervals for individual respondents would need longer, or more, chains.

BART: cross-validated error

bart_fit <- function(train, test) {
  fit <- bart(as.data.frame(train[, c("age", covs)]), train$trump, x.test = as.data.frame(test[, c("age", covs)]),
              ntree = 200, nskip = 500, ndpost = 1000, verbose = FALSE, seed = 818)
  colMeans(pnorm(fit$yhat.test)) # yhat is on the probit scale: average Pr(Y = 1) over posterior draws
}
pred_bart <- cv_pred(bart_fit)
wmse(dat$trump - pred_bart)
[1] 0.161
  • 200 trees, 500 burn-in and 1,000 posterior draws, and the default priors.

BART: partial dependence with uncertainty

bart_full <- bart(as.data.frame(dat[, c("age", covs)]), dat$trump, ntree = 200, nskip = 500, ndpost = 1000,
                  verbose = FALSE, seed = 818, keeptrees = TRUE)
pd_bart <- map_dfr(pd_ages, function(a) {
  newdata <- as.data.frame(dat[pd_sample, c("age", covs)]) %>% mutate(age = a)
  draws <- predict(bart_full, newdata, type = "ev") %*% dat$w[pd_sample] / sum(dat$w[pd_sample]) # one PD per draw
  tibble(age = a, est = mean(draws), lo = quantile(draws, .025), hi = quantile(draws, .975))
})

Comparing everything

Method CV error CV accuracy
Intercept only 0.2492 53.0%
Least squares, 1,898 columns (Week 10) 0.1917 73.6%
Ridge (Week 10) 0.1692 75.8%
Lasso (Week 10) 0.1667 75.8%
Single tree, pruned by CV 0.1841 72.6%
Bagging (mtry = 31) 0.1631 76.3%
Random forest (mtry = 10) 0.1606 76.9%
Boosting (depth 6) 0.1635 75.9%
BART 0.1607 76.3%
  • Same 10 folds for every method. Accuracy: predict Trump when the predicted probability is above 0.5.
  • Tuning parameters (\(\lambda\), cp, mtry, \(B\) and \(d\)) were chosen by the same CV error, so every row is a bit optimistic.

Summary

  • Trees partition the predictors into rectangles and predict a constant in each.
    • No assumptions on functional form - enough splits can uncover deep interactions.
    • Interpretable, but high variance.
    • And risk overfitting if grown too deep!
  • Ensembles sacrifice interpretability for greater accuracy:
    • Averages of trees: Grow many deep trees on bootstrap samples and average the predictions
      • De-correlate them by using subsets of predictors at each split
    • Sums of trees - Grow many small trees and add them together.
      • Each tree explains a different part of the outcome.
      • BART: Regularization through Bayesian priors on the tree parameters

Next week

  • Flexible regression: kernels and Gaussian processes

    • Infinite-dimensional function spaces
    • Kernel ridge regression
    • Gaussian process regression: a prior over functions
  • Class meets Monday. Wednesday is cancelled for Thanksgiving.

  • Readings: Hainmueller and Hazlett (2014); Chapters 2 and 4 of Rasmussen and Williams (2006)

References

Athey, Susan, Julie Tibshirani, and Stefan Wager. 2019. “Generalized Random Forests.” The Annals of Statistics 47 (2): 1148–78. https://doi.org/10.1214/18-AOS1709.
Breiman, Leo. 1996. “Bagging Predictors.” Machine Learning 24 (2): 123–40. https://doi.org/10.1007/BF00058655.
———. 2001. “Random Forests.” Machine Learning 45 (1): 5–32. https://doi.org/10.1023/A:1010933404324.
Breiman, Leo, Jerome H. Friedman, Richard A. Olshen, and Charles J. Stone. 1984. Classification and Regression Trees. Belmont, CA: Wadsworth.
Chipman, Hugh A., Edward I. George, and Robert E. McCulloch. 2010. “BART: Bayesian Additive Regression Trees.” The Annals of Applied Statistics 4 (1): 266–98. https://doi.org/10.1214/09-AOAS285.
Friedman, Jerome H. 2001. “Greedy Function Approximation: A Gradient Boosting Machine.” The Annals of Statistics 29 (5): 1189–1232. https://doi.org/10.1214/aos/1013203451.
Hainmueller, Jens, and Chad Hazlett. 2014. “Kernel Regularized Least Squares: Reducing Misspecification Bias with a Flexible and Interpretable Machine Learning Approach.” Political Analysis 22 (2): 143–68. https://doi.org/10.1093/pan/mpt019.
Hastie, Trevor, Robert Tibshirani, and Jerome Friedman. 2009. The Elements of Statistical Learning: Data Mining, Inference, and Prediction. 2nd ed. New York: Springer. https://doi.org/10.1007/978-0-387-84858-7.
Hill, Jennifer, Antonio Linero, and Jared Murray. 2020. “Bayesian Additive Regression Trees: A Review and Look Forward.” Annual Review of Statistics and Its Application 7: 251–78. https://doi.org/10.1146/annurev-statistics-031219-041110.
James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani. 2013. An Introduction to Statistical Learning. New York: Springer. https://doi.org/10.1007/978-1-4614-7138-7.
Montgomery, Jacob M., and Santiago Olivella. 2018. “Tree-Based Models for Political Science Data.” American Journal of Political Science 62 (3): 729–44. https://doi.org/10.1111/ajps.12361.
Rasmussen, Carl Edward, and Christopher K. I. Williams. 2006. Gaussian Processes for Machine Learning. Cambridge, MA: MIT Press.
Strobl, Carolin, Anne-Laure Boulesteix, Achim Zeileis, and Torsten Hothorn. 2007. “Bias in Random Forest Variable Importance Measures: Illustrations, Sources and a Solution.” BMC Bioinformatics 8: 25. https://doi.org/10.1186/1471-2105-8-25.
Zhao, Qingyuan, and Trevor Hastie. 2021. “Causal Interpretations of Black-Box Models.” Journal of Business & Economic Statistics 39: 272–81. https://doi.org/10.1080/07350015.2019.1624293.