# Boosted regression trees, by hand
# https://tidyecology.com/posts/boosted-regression-trees/
#
# 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-10-15

## ---- setup ----
library(rpart); library(ggplot2)
te_ink<-"#16241d"; te_body<-"#2c3a31"; te_forest<-"#275139"; te_label<-"#46604a"
te_line<-"#dad9ca"; te_faint<-"#5d6b61"; te_gold<-"#cda23f"; te_red<-"#b5534e"; te_blue<-"#3f6f8f"
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)
  data.frame(y = f + rnorm(n,0,1.1), x1,x2,x3,x4,x5,x6,x7,x8, f)
}
d  <- make_data(400, 511)
te <- make_data(4000, 999)
preds <- paste0("x",1:8); fo <- as.formula(paste("r ~", paste(preds, collapse=" + ")))
rmse <- function(a,b) sqrt(mean((a-b)^2)); floor_r <- round(rmse(te$f, te$y), 3)

## ---- boost ----
boost <- function(dtr, M, lr, depth = 2){
  Fx <- rep(mean(dtr$y), nrow(dtr)); trees <- vector("list", M)
  for (m in 1:M){
    dd <- dtr; dd$r <- dtr$y - Fx                       # current residuals
    t <- rpart(fo, dd, method = "anova",
               control = rpart.control(maxdepth = depth, cp = 0, minsplit = 10, xval = 0, maxsurrogate = 0))
    trees[[m]] <- t; Fx <- Fx + lr * predict(t, dtr)    # add a shrunken correction
  }
  list(trees = trees, lr = lr, init = mean(dtr$y))
}
# fitted value after each successive tree, so we can read the error at any number of trees
fit_path <- function(bm, nd){
  Pm <- sapply(bm$trees, function(t) predict(t, nd))    # one column per tree
  bm$init + bm$lr * t(apply(Pm, 1, cumsum))             # column m = fit using the first m trees
}

## ---- lr-tradeoff ----
Ms <- c(1,2,5,10,20,40,70,120,200,350,600,1000)
curve_for <- function(lr){
  bm <- boost(d, max(Ms), lr, depth = 2)
  path <- fit_path(bm, te)
  te_err <- sapply(Ms, function(m) rmse(path[, m], te$y))
  all_err <- apply(path, 2, rmse, b = te$y)              # test error at every tree count, not only the grid
  data.frame(M = Ms, rmse = te_err, lr = factor(lr), M_all = which.min(all_err), rmse_all = min(all_err))
}
set.seed(1)
cv <- do.call(rbind, lapply(c(0.30, 0.05, 0.01), curve_for))
best <- do.call(rbind, lapply(split(cv, cv$lr), function(g) g[which.min(g$rmse), ]))
best_fast <- best[best$lr=="0.3",]; best_mid <- best[best$lr=="0.05",]; best_slow <- best[best$lr=="0.01",]

## ---- boost-curves ----
ggplot(cv, aes(M, rmse, colour = lr)) +
  geom_hline(yintercept = floor_r, linetype = "33", colour = te_faint, linewidth = 0.5) +
  geom_line(linewidth = 0.8) + geom_point(size = 1) +
  geom_point(data = best, size = 3, shape = 21, fill = "white", stroke = 1) +
  scale_x_log10() +
  scale_colour_manual(values = c(`0.3` = te_red, `0.05` = te_gold, `0.01` = te_forest),
                      name = "learning rate") +
  annotate("text", x = 3, y = floor_r - 0.015, label = "noise floor", colour = te_faint, size = 3.1) +
  labs(title = "More trees is not always better",
       subtitle = "Test error dips then rises; the minimum shifts right as the rate falls",
       x = "number of trees (log scale)", y = "test RMSE") +
  theme_te()

## ---- overfit ----
bm_fast <- boost(d, 1000, lr = 0.30, depth = 2)
Mg <- c(1,2,5,10,20,40,70,120,200,350,600,1000)
path_tr <- fit_path(bm_fast, d); path_te <- fit_path(bm_fast, te)   # column m = fit using first m trees
of <- data.frame(M = rep(Mg, 2),
  rmse = c(sapply(Mg, function(m) rmse(path_tr[,m], d$y)),
           sapply(Mg, function(m) rmse(path_te[,m], te$y))),
  set = rep(c("training","test"), each = length(Mg)))
train_end <- round(rmse(path_tr[,1000], d$y), 3)   # after all 1000 trees
test_end  <- round(rmse(path_te[,1000], te$y), 3)

## ---- overfit-plot ----
ggplot(of, aes(M, rmse, colour = set)) +
  geom_line(linewidth = 0.9) + geom_point(size = 1.2) +
  scale_x_log10() +
  scale_colour_manual(values = c(training = te_gold, test = te_forest), name = NULL) +
  labs(title = "Training error is not test error",
       subtitle = "Fast rate: the sample is memorised while test error turns back up",
       x = "number of trees (log scale)", y = "RMSE") +
  theme_te()

## ---- depth ----
best_at <- function(depth){
  bm <- boost(d, 600, lr = 0.05, depth = depth)
  path <- fit_path(bm, te); min(sapply(c(50,100,200,350,600), function(m) rmse(path[,m], te$y)))
}
rmse_stump <- round(best_at(1), 3); rmse_depth2 <- round(best_at(2), 3)
