# Checking a tree ensemble
# https://tidyecology.com/posts/checking-a-tree-ensemble/
#
# 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-01

## ---- setup ----
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)
}
# hand-built random forest with impurity-gain bookkeeping (as in the bagging post, plus gain)
grow <- function(idx, dep, md, mb, mtry, gain){
  if (length(idx) < 2*mb || dep >= md) return(list(node=list(leaf=TRUE, pred=mean(yv[idx])), gain=gain))
  vars <- sample(1:ncol(X), 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)
    cs <- cumsum(yo); cq <- cumsum(yo^2); tot <- cs[nL]
    for (k in mb:(nL-mb)){
      if (xo[k]==xo[k+1]) next
      sL <- cs[k]; sR <- tot-sL; g <- base - (cq[k]-sL^2/k) - ((cq[nL]-cq[k])-sR^2/(nL-k))
      if (g > bg){ bg <- g; best <- list(v=v, split=(xo[k]+xo[k+1])/2, gain=g) }
    }
  }
  if (is.null(best)) return(list(node=list(leaf=TRUE, pred=mean(yv[idx])), gain=gain))
  gain[best$v] <- gain[best$v] + best$gain; go <- X[idx,best$v] <= best$split
  L <- grow(idx[go], dep+1, md, mb, mtry, gain); R <- grow(idx[!go], dep+1, md, mb, mtry, L$gain)
  list(node=list(leaf=FALSE, v=best$v, split=best$split, left=L$node, right=R$node), gain=R$gain)
}
predict1 <- function(nd, M){
  out <- numeric(nrow(M))
  for (i in seq_len(nrow(M))){ n <- nd; while (!n$leaf) n <- if (M[i,n$v] <= n$split) n$left else n$right; out[i] <- n$pred }
  out
}
predict_forest <- function(tr, M) rowMeans(sapply(tr, function(t) predict1(t, M)))
forest <- function(B, mtry, seed=21){
  set.seed(seed); n <- nrow(X); tr <- vector("list",B); oob <- vector("list",B); G <- numeric(ncol(X))
  for (b in 1:B){ ib <- sample(n,n,replace=TRUE); r <- grow(ib,0,12,5,mtry,numeric(ncol(X)))
    tr[[b]] <- r$node; G <- G + r$gain; oob[[b]] <- setdiff(1:n, ib) }
  list(trees=tr, oob=oob, imp_gain=G)
}
d <- make_data(400, 511); X <- as.matrix(d[, paste0("x",1:8)]); yv <- d$y
rf <- forest(200, mtry = 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] + predict1(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_gain <- rf$imp_gain / sum(rf$imp_gain)
ip <- pmax(perm_imp(rf), 0); imp_perm <- ip / sum(ip)
names(imp_gain) <- names(imp_perm) <- paste0("x",1:8)
decoy_gain <- round(100*sum(imp_gain[c("x2","x3")]), 0)
decoy_perm <- round(100*sum(imp_perm[c("x2","x3")]), 0)

## ---- importance-plot ----
impd <- rbind(
  data.frame(var=names(imp_gain), imp=as.numeric(imp_gain), type="impurity"),
  data.frame(var=names(imp_perm), imp=as.numeric(imp_perm), type="permutation"))
ord <- names(sort(imp_perm)); impd$var <- factor(impd$var, levels=ord)
ggplot(impd, aes(imp, var, fill=type)) +
  geom_col(position=position_dodge(width=0.7), width=0.62) +
  scale_fill_manual(values=c(impurity=te_gold, permutation=te_forest), name=NULL) +
  scale_y_discrete(labels=c(x1="temperature (x1)", x4="moisture (x4)",
                            x2="correlated decoy (x2)", x3="correlated decoy (x3)",
                            x5="correlated decoy (x5)", x6="noise (x6)",
                            x7="noise (x7)", x8="noise (x8)")) +
  labs(title="Two importance measures, one forest, different stories",
       subtitle="Impurity importance rewards correlated decoys the model does not really need",
       x="share of importance", y="predictor") +
  theme_te()

## ---- pdp ----
gx <- seq(-2.2, 2.2, length.out = 25)
pdp <- function(rows, v = 1) sapply(gx, function(val){ M <- X[rows,,drop=FALSE]; M[,v] <- val; mean(predict_forest(rf$trees, M)) })
pd_marg <- pdp(seq_len(nrow(X)))
pd_lo <- pdp(which(d$x4 < 0)); pd_hi <- pdp(which(d$x4 > 0))
step_lo <- round(pd_lo[16] - pd_lo[10], 2)   # jump across the threshold, low moisture
step_hi <- round(pd_hi[16] - pd_hi[10], 2)   # jump across the threshold, high moisture

## ---- pdp-plot ----
pdd <- rbind(
  data.frame(x1=gx, pred=pd_marg, grp="marginal (all plots)"),
  data.frame(x1=gx, pred=pd_lo,   grp="moisture low"),
  data.frame(x1=gx, pred=pd_hi,   grp="moisture high"))
ggplot(pdd, aes(x1, pred, colour=grp)) +
  geom_vline(xintercept=0, linetype="33", colour=te_faint, linewidth=0.4) +
  geom_line(linewidth=0.9) +
  scale_colour_manual(values=c(`marginal (all plots)`=te_ink, `moisture low`=te_blue, `moisture high`=te_gold), name=NULL) +
  labs(title="A partial-dependence plot averages the interaction away",
       subtitle="The temperature threshold matters more where moisture is high",
       x="temperature (x1)", y="predicted response") +
  theme_te()

## ---- sac ----
field <- function(sx, sy, seed){ set.seed(seed); K <- 7; grid <- matrix(rnorm(K*K),K,K); gg <- seq(0,1,length.out=K)
  i <- findInterval(sx,gg,all.inside=TRUE); j <- findInterval(sy,gg,all.inside=TRUE)
  tx <- (sx-gg[i])/(gg[i+1]-gg[i]); ty <- (sy-gg[j])/(gg[j+1]-gg[j])
  (1-tx)*(1-ty)*grid[cbind(i,j)] + tx*(1-ty)*grid[cbind(i+1,j)] + (1-tx)*ty*grid[cbind(i,j+1)] + tx*ty*grid[cbind(i+1,j+1)] }
set.seed(77); n2 <- 500; sx <- runif(n2); sy <- runif(n2); xa <- rnorm(n2); xb <- rnorm(n2)
ys <- 1.5*(xa>0) + 0.8*xb + 2.4*field(sx,sy,5) + rnorm(n2,0,0.8)
X <- as.matrix(data.frame(xa, xb, sx, sy)); yv <- ys

sf <- forest(150, mtry = 2, seed = 31)                      # random bagging: out-of-bag error
S <- numeric(n2); C <- numeric(n2)
for (b in seq_along(sf$trees)){ ix <- sf$oob[[b]]; S[ix] <- S[ix] + predict1(sf$trees[[b]], X[ix,,drop=FALSE]); C[ix] <- C[ix] + 1 }
k <- C > 0; oob_err <- sqrt(mean((S[k]/C[k] - yv[k])^2))

blk <- (cut(sx,4,labels=FALSE)-1)*4 + cut(sy,4,labels=FALSE) # hold out 4x4 spatial blocks
pe <- numeric(0); ye <- numeric(0)
for (b in sort(unique(blk))){ tst <- which(blk==b); trn <- which(blk!=b); nn <- length(trn)
  set.seed(200+b); tt <- lapply(1:100, function(z) grow(sample(trn,nn,replace=TRUE),0,12,5,2,numeric(ncol(X)))$node)
  pe <- c(pe, predict_forest(tt, X[tst,,drop=FALSE])); ye <- c(ye, yv[tst]) }
cv_err <- sqrt(mean((pe - ye)^2))
oob_r <- round(oob_err,2); cv_r <- round(cv_err,2); gap <- round(100*(cv_err-oob_err)/cv_err, 0)
