# Bagging and random forests, by hand
# https://tidyecology.com/posts/bagging-and-random-forests/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-09-27

## ---- setup ----
library(ggplot2)
te_ink<-"#16241d"; te_body<-"#2c3a31"; te_forest<-"#275139"; te_label<-"#46604a"
te_paper<-"#f5f4ee"; te_line<-"#dad9ca"; te_faint<-"#5d6b61"
te_gold<-"#cda23f"; te_green<-"#2f8f63"; te_red<-"#b5534e"; te_lowc<-"#c9b458"; te_highc<-"#1d5b4e"
theme_te<-function(base_size=12){
  theme_minimal(base_size=base_size)+
  theme(text=element_text(colour=te_body),
    plot.title=element_text(colour=te_ink,size=rel(1.05)),
    plot.subtitle=element_text(colour=te_faint,size=rel(0.9)),
    axis.title=element_text(colour=te_label), axis.text=element_text(colour=te_faint),
    panel.grid.major=element_line(colour=te_line,linewidth=0.3), panel.grid.minor=element_blank(),
    plot.background=element_rect(fill="#f5f4ee",colour=NA), panel.background=element_rect(fill="#f5f4ee",colour=NA),
    legend.position="bottom", strip.text=element_text(colour=te_ink))
}

make_data <- function(n, seed){
  set.seed(seed)
  g1 <- rnorm(n); x1 <- g1 + rnorm(n,0,0.6); x2 <- g1 + rnorm(n,0,0.6); x3 <- g1 + rnorm(n,0,0.6)
  g2 <- rnorm(n); x4 <- g2 + rnorm(n,0,0.6); x5 <- g2 + rnorm(n,0,0.6)
  x6 <- rnorm(n); x7 <- rnorm(n); x8 <- rnorm(n)
  f <- 2.2*(x1 > 0) + 0.9*x4 + 1.3*(x1 > 0)*(x4 > 0)
  y <- f + rnorm(n, 0, 1.1)
  data.frame(y, x1, x2, x3, x4, x5, x6, x7, x8, f)
}
d  <- make_data(400, 511)
te <- make_data(4000, 999)   # large independent test set
X <- as.matrix(d[, paste0("x",1:8)]); Xte <- as.matrix(te[, paste0("x",1:8)]); yv <- d$y
rmse <- function(a,b) sqrt(mean((a-b)^2))
noise_floor <- rmse(te$f, te$y)

## ---- forest ----
grow1 <- function(idx, depth, maxdepth, minbucket, mtry){
  if (length(idx) < 2*minbucket || depth >= maxdepth) return(list(leaf=TRUE, pred=mean(yv[idx])))
  vars <- sample(1:8, mtry); base <- sum((yv[idx]-mean(yv[idx]))^2); best <- NULL; bg <- 1e-9
  for (v in vars){
    xs <- X[idx,v]; o <- order(xs); xo <- xs[o]; yo <- yv[idx][o]; nL <- length(idx)
    csum <- cumsum(yo); csq <- cumsum(yo^2); tot <- csum[nL]
    for (k in minbucket:(nL-minbucket)){
      if (xo[k] == xo[k+1]) next
      sL <- csum[k]; sR <- tot - sL
      sseL <- csq[k] - sL^2/k; sseR <- (csq[nL]-csq[k]) - sR^2/(nL-k)
      g <- base - sseL - sseR
      if (g > bg){ bg <- g; best <- list(v=v, split=(xo[k]+xo[k+1])/2) }
    }
  }
  if (is.null(best)) return(list(leaf=TRUE, pred=mean(yv[idx])))
  go <- X[idx, best$v] <= best$split
  list(leaf=FALSE, v=best$v, split=best$split,
       left  = grow1(idx[go],  depth+1, maxdepth, minbucket, mtry),
       right = grow1(idx[!go], depth+1, maxdepth, minbucket, mtry))
}
pred1 <- function(node, M){
  out <- numeric(nrow(M))
  for (i in seq_len(nrow(M))){ nn <- node
    while (!nn$leaf) nn <- if (M[i,nn$v] <= nn$split) nn$left else nn$right
    out[i] <- nn$pred }
  out
}
forest_fit <- function(B, mtry, maxdepth=12, minbucket=5, seed=1){
  set.seed(seed); n <- nrow(X); trees <- vector("list",B); oob <- vector("list",B)
  for (b in 1:B){ ib <- sample(n, n, replace=TRUE)
    trees[[b]] <- grow1(ib, 0, maxdepth, minbucket, mtry); oob[[b]] <- setdiff(1:n, ib) }
  list(trees=trees, oob=oob)
}
predmat <- function(ens, M) sapply(ens$trees, function(t) pred1(t, M))

B <- 200
bag <- forest_fit(B, mtry = 8, seed = 21)   # bagging
rf  <- forest_fit(B, mtry = 3, seed = 21)   # random forest
Pbag <- predmat(bag, Xte); Prf <- predmat(rf, Xte)

single_rmse <- round(rmse(Pbag[,1], te$y), 3)   # one deep tree
bag_rmse <- round(rmse(rowMeans(Pbag), te$y), 3)
rf_rmse  <- round(rmse(rowMeans(Prf),  te$y), 3)
floor_r  <- round(noise_floor, 3)

## ---- variance-curve ----
Bs <- c(1,2,3,5,8,12,20,35,60,100,150,200)
vc <- sapply(Bs, function(k) rmse(rowMeans(Pbag[,1:k,drop=FALSE]), te$y))
ggplot(data.frame(B=Bs, rmse=vc), aes(B, rmse)) +
  geom_hline(yintercept = single_rmse, linetype = "22", colour = te_red, linewidth = 0.6) +
  geom_hline(yintercept = floor_r, linetype = "33", colour = te_faint, linewidth = 0.6) +
  geom_line(colour = te_forest, linewidth = 0.8) + geom_point(colour = te_forest, size = 1.3) +
  annotate("text", x = 130, y = single_rmse + 0.02, label = "single deep tree", colour = te_red, size = 3.2) +
  annotate("text", x = 130, y = floor_r - 0.02, label = "noise floor", colour = te_faint, size = 3.2) +
  labs(title = "Averaging trees cancels their variance",
       subtitle = "Test error falls with the number of trees and flattens near the floor",
       x = "number of trees", y = "test RMSE") +
  theme_te()

## ---- oob ----
oob_rmse <- function(ens, target = yv){
  n <- nrow(X); S <- numeric(n); C <- numeric(n)
  for (b in seq_along(ens$trees)){ ix <- ens$oob[[b]]; if (!length(ix)) next
    S[ix] <- S[ix] + pred1(ens$trees[[b]], X[ix,,drop=FALSE]); C[ix] <- C[ix] + 1 }
  k <- C > 0; sqrt(mean((S[k]/C[k] - target[k])^2))
}
bag_oob <- round(oob_rmse(bag), 3); rf_oob <- round(oob_rmse(rf), 3)
floor_train <- round(rmse(d$f, d$y), 3)               # noise level of the training draw
bag_oob_f  <- round(oob_rmse(bag, d$f), 3)            # error against the true signal
bag_test_f <- round(rmse(rowMeans(Pbag), te$f), 3)

## ---- decorrelation ----
avg_tree_cor <- function(Pm, m = 40){ s <- Pm[,1:m]; C <- cor(s); mean(C[upper.tri(C)]) }
cor_bag <- round(avg_tree_cor(Pbag), 3); cor_rf <- round(avg_tree_cor(Prf), 3)

## ---- importance ----
perm_imp <- function(ens){
  n <- nrow(X)
  score <- function(perm = NULL){
    S <- numeric(n); C <- numeric(n)
    for (b in seq_along(ens$trees)){ ix <- ens$oob[[b]]; if (!length(ix)) next
      M <- X[ix,,drop=FALSE]; if (!is.null(perm)) M[,perm] <- X[sample(ix), perm]
      S[ix] <- S[ix] + pred1(ens$trees[[b]], M); C[ix] <- C[ix] + 1 }
    k <- C > 0; sqrt(mean((S[k]/C[k] - yv[k])^2))
  }
  b0 <- score(); set.seed(3)
  sapply(1:8, function(j) score(j) - b0)
}
imp <- perm_imp(rf); names(imp) <- paste0("x",1:8)
imp_x1 <- round(imp["x1"],3); imp_x4 <- round(imp["x4"],3)

## ---- importance-plot ----
impd <- data.frame(var = names(imp), imp = as.numeric(imp))
impd$role <- ifelse(impd$var %in% c("x1","x4"), "driver", "decoy or noise")
impd <- impd[order(impd$imp), ]; impd$var <- factor(impd$var, levels = impd$var)
ggplot(impd, aes(imp, var, fill = role)) +
  geom_col(width = 0.68) +
  scale_fill_manual(values = c(driver = te_forest, `decoy or noise` = te_gold), name = NULL) +
  labs(title = "Permutation importance separates the drivers",
       subtitle = "Increase in out-of-bag RMSE when each predictor is shuffled",
       x = "importance", y = NULL) +
  theme_te()
