---
title: "Gradient Boosting: How Strong Is This Concrete?"
description: "Gradient boosting for a continuous outcome in R with xgboost, on the UCI concrete data: boosting by hand, learning rate, tree depth and number of trees chosen by cross-validation, a test-set comparison with linear regression, a single tree and a random forest, importance, partial dependence, SHAP values and APA reporting."
author: ""
---
```{r options, echo=FALSE, warning=FALSE, message=FALSE}
directory<-if (rstudioapi::isAvailable()) paste0(dirname(rstudioapi::getActiveDocumentContext()$path),"/") else ""
source(paste0(directory, "R/code_options.R"))
# no knitr cache: the page downloads its data each time it runs (in a second or two),
# and a cached chunk would quietly keep an old download
knitr::opts_chunk$set(fig.height = 4.5, cache = FALSE)
```
## The question: what makes concrete strong?
Concrete is cement, water, sand, gravel and a few extras such as blast furnace slag, fly ash (both left over from other industries) and a chemical "superplasticizer" that makes the mix flow. Engineers want to know how strong a mix will be **before** they pour it, because the strength is tested by crushing a sample, and by then the mix has already set for 28 days.
This page asks: **how well can we predict the compressive strength of concrete (in megapascals, MPa) from what is in the mix and how old it is, and which ingredients matter most?**
The relationship is not simple, for two reasons:
- **It is nonlinear.** Concrete gains strength quickly in the first weeks, then more and more slowly. Doubling the age does not double the strength.
- **It has interactions.** Slag, for example, adds almost nothing to young concrete, because it reacts slowly, and a lot to concrete that has had a month or more to set.
A straight-line regression ([see the regression page](EXAMPLE_REGULARIZED_REGRESSION.Rmd)) misses both. **Gradient boosting** finds them on its own. It builds a prediction from hundreds of small decision trees, **one after another**, each one correcting the mistakes of those before it. It is one of the most accurate methods for tables of numbers, and the one that wins many prediction contests.
Gradient boosting and a [random forest](EXAMPLE_RANDOM_FOREST.Rmd) both add up many trees, but in opposite ways:
| | Random forest | Gradient boosting |
|---|---|---|
| Trees are grown | independently, in parallel | one after another |
| Each tree is | deep, and fitted to the data | small, and fitted to the mistakes so far |
| Trees are combined by | averaging | adding up, each scaled down |
| Main danger | few: more trees never overfit | too many trees overfit |
```{r packages}
library(xgboost) # gradient boosting
library(rpart) # a single tree, and the small trees for boosting by hand
library(ranger) # random forest
library(readxl) # the data come as an Excel file
library(ggplot2)
# colors in the site order, the same in every chart
colours <- c("#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300")
# number formats for the text
f1 <- function(x) formatC(x, format = "f", digits = 1)
f2 <- function(x) formatC(x, format = "f", digits = 2)
nz <- function(x, d = 2) sub("^0", "", formatC(x, format = "f", digits = d)) # no leading zero
pct <- function(x, d = 0) paste0(formatC(100 * x, format = "f", digits = d), "%")
num <- function(x) trimws(format(x, big.mark = ","))
packageVersion("xgboost")
```
---
## 1. The data
The data are the **Concrete Compressive Strength** data of I-Cheng Yeh (1998), kept by the UCI Machine Learning Repository. They are free to use (license CC BY 4.0) and need no login. The download is a zip of about 34 KB and takes about a second.
```{r download}
t0 <- Sys.time()
zip <- tempfile(fileext = ".zip")
download.file("https://archive.ics.uci.edu/static/public/165/concrete+compressive+strength.zip",
zip, mode = "wb", quiet = TRUE)
xls <- unzip(zip, files = "Concrete_Data.xls", exdir = tempdir())
concrete <- as.data.frame(read_excel(xls))
seconds <- as.numeric(difftime(Sys.time(), t0, units = "secs"))
kb <- file.size(zip) / 1024
# the original column names are long; short names are easier to work with
names(concrete) <- c("cement", "slag", "fly_ash", "water", "superplasticizer",
"coarse", "fine", "age", "strength")
nice <- c(cement = "Cement", slag = "Blast furnace slag", fly_ash = "Fly ash", water = "Water",
superplasticizer = "Superplasticizer", coarse = "Coarse aggregate",
fine = "Fine aggregate", age = "Age (days)")
str(concrete)
```
The download took `r f1(seconds)` seconds for `r f1(kb)` KB. There are `r num(nrow(concrete))` concrete samples, with no missing values (`r sum(is.na(concrete))` missing cells).
| Variable | Meaning | Unit |
|---|---|---|
| `strength` | **Outcome**: compressive strength | MPa |
| `cement`, `slag`, `fly_ash` | Cement, blast furnace slag, fly ash in one cubic meter of mix | kg |
| `water`, `superplasticizer` | Water and superplasticizer in one cubic meter of mix | kg |
| `coarse`, `fine` | Gravel (coarse aggregate) and sand (fine aggregate) | kg |
| `age` | Days since the concrete was poured | days |
```{r duplicates}
n_dup <- sum(duplicated(concrete))
```
`r n_dup` rows are exact copies of another row. They may be real repeated tests of the same mix, so we keep them, but they matter later (section 8).
### Training and test data
Before looking at anything else, we put 20% of the samples away as a **test set**. We use it **once**, at the end (section 6), to see how the finished models do on concrete they have never seen. Everything before that (choosing the settings, the number of trees) uses only the training data.
```{r split}
set.seed(2026)
test_rows <- sample(nrow(concrete), round(0.20 * nrow(concrete)))
train <- concrete[-test_rows, ]
test <- concrete[ test_rows, ]
predictors <- setdiff(names(concrete), "strength")
# xgboost wants the predictors as a numeric matrix. nthread = 1 keeps results reproducible
x_train <- as.matrix(train[predictors]); x_test <- as.matrix(test[predictors])
d_train <- xgb.DMatrix(x_train, label = train$strength, nthread = 1)
d_test <- xgb.DMatrix(x_test, label = test$strength, nthread = 1)
c(train = nrow(train), test = nrow(test))
```
---
## 2. Look at the data
```{r outcome}
summary(concrete$strength)
```
The strength runs from `r f1(min(concrete$strength))` to `r f1(max(concrete$strength))` MPa, with a mean of `r f1(mean(concrete$strength))` and a standard deviation of `r f1(sd(concrete$strength))`. **That standard deviation is the error of the dumbest prediction**: guessing the mean for every sample. Any model has to do better than this.
First, age:
```{r look_age, fig.height = 4}
ggplot(train, aes(age, strength)) +
geom_point(colour = colours[1], alpha = 0.4) +
geom_smooth(method = "loess", formula = y ~ x, colour = colours[2], se = FALSE) +
scale_x_log10(breaks = c(1, 3, 7, 14, 28, 56, 90, 180, 365)) +
labs(x = "Age (days, log scale)", y = "Strength (MPa)") +
theme_bw()
```
Strength climbs steeply during the first month and then flattens: a curve, not a line. The spread at any one age is large, which is the effect of the mix.
Next, slag. It reacts slowly, so its effect should depend on the age. We draw it separately for young, 28-day and old concrete:
```{r look_slag, fig.height = 4}
train$age_group <- cut(train$age, c(0, 14, 28, Inf), labels = c("Up to 14 days", "28 days", "Over 28 days"))
ggplot(train, aes(slag, strength, colour = age_group)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm", formula = y ~ x, se = FALSE) +
scale_colour_manual(values = colours[1:3]) +
labs(x = "Blast furnace slag (kg per m³)", y = "Strength (MPa)", colour = NULL) +
theme_bw() + theme(legend.position = "bottom")
slopes <- sapply(split(train, train$age_group), function(d) coef(lm(strength ~ slag, d))[["slag"]])
train$age_group <- NULL
```
The three lines have different slopes: an extra 100 kg of slag goes with `r f1(100 * slopes[["Up to 14 days"]])` MPa more strength in young concrete, `r f1(100 * slopes[["28 days"]])` at 28 days and `r f1(100 * slopes[["Over 28 days"]])` in older concrete. (These are raw slopes, which also carry the effect of the other ingredients.) That is an **interaction** between slag and age. A linear regression would need us to guess and add each such term by hand. Boosted trees find them by themselves.
---
## 3. The model step by step, with formulas
### Step 1: start from a constant
The simplest possible prediction is the same number for every sample. For squared error it is the **mean** of the outcome:
$$F_0(x) = \bar{y}$$
Here $F_0$ = `r f1(mean(train$strength))` MPa for everyone.
### Step 2: the mistakes of the current model
The model is not good, so it makes mistakes. Boosting measures them with a **loss function**, a number that is large when the predictions are bad. For a continuous outcome the usual loss is half the squared error:
$$L(y, F) = \tfrac{1}{2}\,(y - F(x))^2$$
To make the model better, we need to know in which direction to change each prediction. That direction is the **negative gradient** of the loss with respect to the prediction. For squared error it is simply:
$$-\frac{\partial L}{\partial F(x_i)} = y_i - F(x_i) = r_i$$
**The negative gradient is the residual**: the actual strength minus the predicted strength. A positive residual says "predict higher for this sample", a negative one "predict lower". This is why the method is called *gradient* boosting: with another loss (absolute error, Poisson deviance...) the same recipe works, and only the "residual" changes.
### Step 3: fit a small tree to the mistakes
A small regression tree $h_1$ is fitted with the **residuals as its outcome**. It finds groups of samples that the current model gets wrong in the same direction (for instance young, low-cement concrete, which $F_0$ overestimates), and predicts the average residual of each group. [How a single tree finds its groups is explained on the decision tree page](EXAMPLE_DECISION_TREE.rmd).
### Step 4: add the tree, scaled down
The new tree is **added to the model**, but only a fraction of it, the **learning rate** $\nu$ (also called shrinkage or `eta`, typically 0.01 to 0.3):
$$F_1(x) = F_0(x) + \nu \, h_1(x)$$
Why not add all of it, with $\nu = 1$? Because each tree is fitted to the noise as well as the signal. Taking only a small step each time makes the model learn the pattern that many trees agree on, and not the accident of one.
### Step 5: repeat
Compute the new residuals $y - F_1(x)$, fit a tree $h_2$ to them, and add it. After $M$ rounds:
$$F_m(x) = F_{m-1}(x) + \nu \, h_m(x) \qquad\Longrightarrow\qquad F_M(x) = \bar{y} + \nu \sum_{m=1}^{M} h_m(x)$$
The final prediction is the constant plus the sum of all the scaled trees. Every tree is small, but together they can draw a very flexible curve.
### Step 6: what xgboost adds
`xgboost` ("extreme gradient boosting") follows the same recipe with two refinements. It uses the **second derivative** of the loss as well (a better step than the gradient alone), and it **penalizes** complex trees. Each tree is chosen to minimize
$$\sum_i \left[ g_i f(x_i) + \tfrac{1}{2} h_i f(x_i)^2 \right] + \gamma T + \tfrac{1}{2}\lambda \sum_j w_j^2$$
where $g_i$ and $h_i$ are the first and second derivatives of the loss for sample $i$, $T$ is the number of leaves, $w_j$ the value in leaf $j$, and $\gamma$ and $\lambda$ are penalties. For squared error $g_i = F(x_i) - y_i$ (minus the residual) and $h_i = 1$, so the best value in a leaf is
$$w_j = \frac{\sum_{i \in \text{leaf } j} r_i}{n_j + \lambda}$$
the **average residual in the leaf**, pulled towards zero by $\lambda$ (the `lambda` setting). The sum of $h_i$ in a leaf, here just the number of samples $n_j$, is what the setting `min_child_weight` limits: leaves resting on very few samples are not allowed.
### Step 7: boosting by hand
We can do all this with `rpart`, in a few lines. Each tree is **small** (two levels, so at most four leaves), and the learning rate is $\nu = 0.3$:
```{r by_hand_fun}
boost_by_hand <- function(train, test, nu, M, depth = 2) {
f_train <- rep(mean(train$strength), nrow(train)) # step 1: the constant
f_test <- rep(mean(train$strength), nrow(test))
residuals <- matrix(NA, nrow(train), M + 1) # the residuals after every step
residuals[, 1] <- train$strength - f_train
rmse <- data.frame(trees = 0:M, train = NA, test = NA)
rmse[1, 2:3] <- c(sd(train$strength) * sqrt((nrow(train) - 1) / nrow(train)),
sqrt(mean((test$strength - f_test)^2)))
trees <- list()
for (m in 1:M) {
d <- train[predictors]
d$r <- train$strength - f_train # step 2: the residuals
trees[[m]] <- rpart(r ~ ., d, control = rpart.control(maxdepth = depth, cp = 0, xval = 0)) # step 3
f_train <- f_train + nu * predict(trees[[m]], train) # step 4: add, scaled down
f_test <- f_test + nu * predict(trees[[m]], test)
residuals[, m + 1] <- train$strength - f_train
rmse[m + 1, 2:3] <- c(sqrt(mean(residuals[, m + 1]^2)), sqrt(mean((test$strength - f_test)^2)))
}
list(rmse = rmse, residuals = residuals, trees = trees)
}
hand <- boost_by_hand(train, test, nu = 0.3, M = 100)
```
This is the whole algorithm. We can now look at what happens. The first tree, fitted to the residuals of the constant model:
```{r first_tree}
hand$trees[[1]]
```
Each line is a split, and the number after `n` is the number of samples in the group. The first split is on the variable `r as.character(hand$trees[[1]]$frame$var[1])`. The last number on a leaf line is the average residual in that group, for instance `r f1(min(hand$trees[[1]]$frame$yval))` MPa in the group the constant overestimates most and `r f1(max(hand$trees[[1]]$frame$yval))` in the one it underestimates most. The model adds $\nu = 0.3$ of those numbers to its predictions.
The error after the first rounds:
```{r by_hand_table}
r <- hand$rmse
by_hand_steps <- r[r$trees %in% c(0, 1, 2, 3, 5, 10, 20, 50, 100), ]
names(by_hand_steps) <- c("Trees", "Training RMSE", "Test RMSE")
knitr::kable(by_hand_steps, digits = 2, row.names = FALSE, align = "rrr")
```
(The test RMSE is shown only to see the principle at work; no choice is based on it.) RMSE is the root mean squared error, in MPa: the typical size of a mistake. It falls from `r f1(r$train[1])` MPa for the constant model to `r f1(r$train[2])` after one tree, `r f1(r$train[4])` after three and `r f1(r$train[101])` after 100. The chart shows the residuals, the **mistakes still left**, shrinking:
```{r by_hand_residuals, fig.height = 4}
steps <- c(0, 1, 3, 20)
res_long <- do.call(rbind, lapply(steps, function(s)
data.frame(step = factor(paste(s, if (s == 1) "tree" else "trees"),
levels = paste(steps, ifelse(steps == 1, "tree", "trees"))),
residual = hand$residuals[, s + 1])))
ggplot(res_long, aes(residual)) +
geom_histogram(binwidth = 2.5, fill = colours[1], colour = "white") +
facet_wrap(~ step, nrow = 1) +
labs(x = "Residual: actual minus predicted strength (MPa)", y = "Samples") +
theme_bw()
```
With no trees the residuals are wide, the spread of the strength itself. Each tree takes a bite out of them, until only the part no tree can explain is left. Over the 100 trees the training error keeps falling; the question is whether the test error does too. That is the question of the next sections.
---
## 4. The settings
A boosted model has a few settings (**hyperparameters**) that the data cannot tell us. Each one controls how fast the model learns and how complex it can become:
| Setting (`xgboost` name) | What it does | Typical values | Too low | Too high |
|---|---|---|---|---|
| Number of trees (`nrounds`) | How many correction rounds | 100 to several thousand | Underfits | Overfits |
| Learning rate (`eta`) | How much of each tree is added | 0.01 to 0.3 | Needs very many trees | Jumpy; overfits sooner |
| Tree depth (`max_depth`) | Levels per tree. Depth 1 is a stump (no interactions), depth 2 allows two-way interactions, and so on | 2 to 8 | Misses interactions | Overfits; slow |
| Row sampling (`subsample`) | Share of the samples used for each tree | 0.5 to 1 | More noise | No randomness against overfitting |
| Column sampling (`colsample_bytree`) | Share of the predictors used for each tree | 0.5 to 1 | Trees too weak | Trees too alike |
| Minimum child weight (`min_child_weight`) | Fewest samples a leaf may rest on (for squared error) | 1 to 10 | Leaves fitted to noise | Underfits |
| Penalties (`lambda`, `gamma`) | Shrink leaf values (`lambda`) and ask a split to pay for itself (`gamma`) | 0 to 10 | | Underfits |
The settings **work together**. A smaller learning rate needs more trees; deeper trees need fewer. A good rule: set the learning rate low enough to be smooth (0.05 to 0.1), and let cross-validation choose the number of trees.
### Learning rate and number of trees
To compare settings without touching the test set, we use **5-fold cross-validation** on the training data: the training samples are split into five parts; the model is fitted five times, each time to four parts, and the error is measured on the fifth. `xgb.cv()` does it, and gives the error after every tree. We give it the same folds each time, so that the settings are compared on the same data.
```{r folds}
set.seed(1)
folds <- split(sample(nrow(train)), rep(1:5, length.out = nrow(train)))
# cross-validation for a set of settings: returns the error after every tree
cv_run <- function(nrounds, early = NULL, ...) {
params <- list(objective = "reg:squarederror", nthread = 1, ...)
xgb.cv(params = params, data = d_train, nrounds = nrounds, folds = folds,
early_stopping_rounds = early, verbose = 0)
}
```
Three learning rates, with trees of depth 4:
```{r learning_rate, fig.height = 4.5}
rates <- c(0.5, 0.1, 0.02)
lr_log <- do.call(rbind, lapply(rates, function(e) {
cv <- cv_run(1500, eta = e, max_depth = 4)
data.frame(eta = factor(e, levels = rates), trees = cv$evaluation_log$iter,
rmse = cv$evaluation_log$test_rmse_mean)
}))
lr_best <- aggregate(rmse ~ eta, lr_log, min)
ggplot(lr_log, aes(trees, rmse, colour = eta)) +
geom_line(linewidth = 0.8) +
scale_x_log10() +
scale_colour_manual(values = colours[1:3]) +
coord_cartesian(ylim = c(3.5, 10)) +
labs(x = "Number of trees (log scale)", y = "Cross-validated RMSE (MPa)", colour = "Learning rate") +
theme_bw()
```
The highest rate (0.5) learns fastest: it is the best of the three for the first hundred trees or so, but it flattens at `r f2(lr_best$rmse[1])` MPa. The middle rate (0.1) needs a few hundred trees and gets lower, to `r f2(lr_best$rmse[2])` MPa. The smallest rate (0.02) is still improving after the 1,500 trees tried here (`r f2(lr_best$rmse[3])` MPa) and would need many more. **A small learning rate lets the model go further, but costs trees and time**; a middle value is a good compromise.
### Overfitting: training error against validation error
A model with enough trees can learn the training data by heart, noise included. The training error then keeps falling, while the error on new data stops improving, and may turn up. To see it, we use larger trees (depth 6), where it happens sooner, and watch both errors tree by tree. The cross-validation error is the error on the part left out, the **validation error**.
```{r overfitting, fig.height = 4.5}
# early_stopping_rounds = 30: stop when the validation error has not improved for 30 trees
cv_depth6 <- cv_run(3000, early = 30, eta = 0.1, max_depth = 6)
log6 <- cv_depth6$evaluation_log
best_n6 <- cv_depth6$early_stop$best_iteration
curve <- rbind(data.frame(trees = log6$iter, rmse = log6$train_rmse_mean, data = "Training"),
data.frame(trees = log6$iter, rmse = log6$test_rmse_mean, data = "Validation (cross-validation)"))
ggplot(curve, aes(trees, rmse, colour = data)) +
geom_line(linewidth = 0.8) +
geom_vline(xintercept = best_n6, linetype = "dashed", colour = "grey40") +
annotate("text", x = best_n6, y = 7.5, label = paste(best_n6, "trees"),
hjust = 1.1, colour = "grey20") +
scale_colour_manual(values = colours[1:2]) +
coord_cartesian(ylim = c(0, 8)) +
labs(x = "Number of trees", y = "RMSE (MPa)", colour = NULL) +
theme_bw() + theme(legend.position = "bottom")
```
The training error keeps falling, down to `r f2(tail(log6$train_rmse_mean, 1))` MPa after `r num(max(log6$iter))` trees. The validation error stops improving at `r best_n6` trees (`r f2(cv_depth6$early_stop$best_score)` MPa), and does not improve after that. The gap between the two lines is the **overfitting**: the model is better at the samples it has seen than at new ones.
**Early stopping** uses this: stop adding trees when the validation error has not improved for a number of rounds (here 30), and keep the number of trees that was best. The number of trees is therefore **not set by hand but found by cross-validation**. This is the usual way to choose it.
### A small tuning grid
We now look at the other settings together. Trying every combination is costly, so we use a small grid: three learning rates, three depths, two minimum child weights and two row sampling rates, 36 combinations. For each, the number of trees is chosen by early stopping, and the cross-validated RMSE at that number is recorded. The column sampling is fixed at 0.8.
```{r grid}
grid <- expand.grid(eta = c(0.3, 0.1, 0.05), max_depth = c(2, 4, 6),
min_child_weight = c(1, 5), subsample = c(0.7, 1))
grid$trees <- NA; grid$rmse <- NA
for (i in seq_len(nrow(grid))) {
cv <- cv_run(3000, early = 30, eta = grid$eta[i], max_depth = grid$max_depth[i],
min_child_weight = grid$min_child_weight[i], subsample = grid$subsample[i],
colsample_bytree = 0.8)
grid$trees[i] <- cv$early_stop$best_iteration
grid$rmse[i] <- cv$early_stop$best_score
}
grid <- grid[order(grid$rmse), ]
best <- grid[1, ]
knitr::kable(head(grid, 8), digits = 2, row.names = FALSE, align = "rrrrrr",
col.names = c("Learning rate", "Depth", "Min. child weight", "Row sampling", "Trees", "CV RMSE"))
```
The best combination is a learning rate of `r best$eta`, depth `r best$max_depth`, minimum child weight `r best$min_child_weight` and row sampling of `r best$subsample`, with `r num(best$trees)` trees and a cross-validated RMSE of `r f2(best$rmse)` MPa. Look at the other rows too: several settings give almost the same error. The grid is small and the cross-validation itself has noise, so **do not read too much into the exact winner**; what matters is the region: trees of depth 4, and a learning rate of 0.05 to 0.1. The best result by depth:
```{r grid_depth}
by_depth <- aggregate(rmse ~ max_depth, grid, min)
by_depth$rmse <- round(by_depth$rmse, 2)
names(by_depth) <- c("Depth", "Best CV RMSE")
knitr::kable(by_depth, row.names = FALSE, align = "rr")
```
---
## 5. Fitting the final model
We fit the model to **all** the training data with the chosen settings and number of trees:
```{r fit}
params <- list(objective = "reg:squarederror", nthread = 1, eta = best$eta,
max_depth = best$max_depth, min_child_weight = best$min_child_weight,
subsample = best$subsample, colsample_bytree = 0.8)
set.seed(3) # the row and column sampling are random
fit <- xgb.train(params = params, data = d_train, nrounds = best$trees)
fit
```
The model is a sum of `r num(best$trees)` trees. Here are the first three, each only a few levels deep:
```{r tree_dump}
trees <- xgb.model.dt.tree(model = fit, trees = 1:3)
head(trees[, c("Tree", "Node", "Feature", "Split", "Yes", "No", "Gain")], 9)
```
Nobody can read `r num(best$trees)` trees, so we cannot explain the model by looking at its parts. Section 7 explains it by looking at what it **does**.
---
## 6. Does it beat simpler models? The test set
We now use the test set, once. The competitors, all fitted to the same training data:
- **Linear regression** with the eight predictors, no interactions or curves.
- **A single regression tree** ([CART](EXAMPLE_DECISION_TREE.rmd)), pruned by cross-validation.
- **A random forest** ([`ranger`](EXAMPLE_RANDOM_FOREST.Rmd)) with its default settings (500 trees).
- **Gradient boosting**, tuned as above.
```{r compare}
linear <- lm(strength ~ ., train)
set.seed(4)
tree <- rpart(strength ~ ., train)
tree <- prune(tree, cp = tree$cptable[which.min(tree$cptable[, "xerror"]), "CP"])
forest <- ranger(strength ~ ., train, seed = 5, num.threads = 1)
predictions <- data.frame(
`Linear regression` = predict(linear, test),
`Single tree` = predict(tree, test),
`Random forest` = predict(forest, test)$predictions,
`Gradient boosting` = predict(fit, x_test),
check.names = FALSE)
# the three measures: the error on the strength scale, and the share of variance explained
metrics <- function(y, p) c(RMSE = sqrt(mean((y - p)^2)), MAE = mean(abs(y - p)),
R2 = 1 - sum((y - p)^2) / sum((y - mean(y))^2))
results <- t(sapply(predictions, function(p) metrics(test$strength, p)))
knitr::kable(results, digits = 2, align = "rrr")
```
RMSE and MAE (mean absolute error) are in MPa: smaller is better. $R^2 = 1 - \text{SSE}/\text{SST}$ is the share of the variance of the test strengths that the model explains. Linear regression is a baseline: its test RMSE is `r f2(results["Linear regression", "RMSE"])` MPa. The single tree is `r f2(results["Single tree", "RMSE"])`. The random forest reaches `r f2(results["Random forest", "RMSE"])`, and gradient boosting `r f2(results["Gradient boosting", "RMSE"])` MPa ($R^2$ = `r nz(results["Gradient boosting", "R2"])`). Gradient boosting's typical mistake is `r f1(results["Gradient boosting", "MAE"])` MPa, against a standard deviation of `r f1(sd(test$strength))` MPa in the test strengths.
```{r predicted_observed, fig.height = 6}
po <- do.call(rbind, lapply(names(predictions), function(m)
data.frame(model = factor(m, levels = names(predictions)), observed = test$strength, predicted = predictions[[m]])))
ggplot(po, aes(predicted, observed)) +
geom_abline(colour = "grey40") +
geom_point(colour = colours[1], alpha = 0.6) +
facet_wrap(~ model) +
coord_equal() +
labs(x = "Predicted strength (MPa)", y = "Actual strength (MPa)") +
theme_bw()
```
The closer the points to the diagonal, the better the model. The straight line misses the curve; the single tree can only make a few steps; the forest follows the diagonal better, and the boosted model stays closest to it.
**Two cautions.** First, the test set has only `r nrow(test)` samples, so each of these numbers has some noise; the gap between boosting and the forest (`r f2(results["Random forest", "RMSE"] - results["Gradient boosting", "RMSE"])` MPa) is large, but a gap of a few hundredths of a MPa would mean little. Second, the random forest was **not tuned** here and boosting was; a tuned forest would come closer. The honest summary is not "boosting always wins" but that **ensembles of trees beat the simple models** when the relationship is curved and has interactions, and that boosting, with some tuning, did best here.
---
## 7. Interpreting the model
A boosted model is a black box in the sense that no single number says what a variable does. Three tools open it, from the whole model down to one sample.
### Which predictors matter? Gain against permutation
There are two common ways to rank the predictors.
- **Gain** is built into xgboost: the total improvement in the loss from all the splits on a predictor, as a share of the total. It is computed on the training data and says what the model **used**.
- **Permutation importance** shuffles one predictor in the test set, so that it carries no information, and measures how much the error **increases**. It says what the model **needs** on new data. We write it by hand; it is only a loop.
```{r importance}
gain <- as.data.frame(xgb.importance(model = fit))
gain <- setNames(gain$Gain, gain$Feature)[predictors]
set.seed(6)
baseline <- sqrt(mean((test$strength - predict(fit, x_test))^2))
permutation <- sapply(predictors, function(v) mean(replicate(20, {
shuffled <- x_test
shuffled[, v] <- sample(shuffled[, v])
sqrt(mean((test$strength - predict(fit, shuffled))^2)) - baseline
})))
importance <- rbind(data.frame(predictor = predictors, share = gain / sum(gain), method = "Gain"),
data.frame(predictor = predictors, share = permutation / sum(permutation), method = "Permutation"))
importance$predictor <- factor(nice[importance$predictor], levels = nice[names(sort(permutation))])
ggplot(importance, aes(share, predictor, fill = method)) +
geom_col(position = position_dodge(width = 0.8), width = 0.7) +
scale_fill_manual(values = colours[1:2], guide = guide_legend(reverse = TRUE)) +
scale_x_continuous(labels = scales::percent, expand = expansion(mult = c(0, 0.05))) +
labs(x = "Share of the total importance", y = NULL, fill = NULL) +
theme_bw() + theme(legend.position = "bottom")
rank_gain <- names(sort(gain, decreasing = TRUE)); rank_perm <- names(sort(permutation, decreasing = TRUE))
```
By gain the order is `r paste(nice[rank_gain][1:3], collapse = ", ")`; by permutation it is `r paste(nice[rank_perm][1:3], collapse = ", ")`. The top predictor, `r tolower(nice[rank_perm[1]])`, accounts for `r pct(permutation[[rank_perm[1]]] / sum(permutation))` of the permutation importance: shuffling it raises the test RMSE by `r f1(permutation[[rank_perm[1]]])` MPa. The two measures `r if (identical(rank_gain, rank_perm)) "give the same order here" else "agree on the main players and differ on the smaller ones"`, but they need not. Gain tends to favor predictors with many possible split points, and both measures share the credit unfairly between predictors that are correlated (here water and superplasticizer, for example). **Importance says how much the model uses a predictor, not in which direction, and not whether changing it would change the strength.**
### Which way? Partial dependence
A **partial dependence** plot shows the average prediction as one predictor moves across its range. For each value $v$, we set the predictor to $v$ in **every** training sample, predict, and average:
$$\text{PD}(v) = \frac{1}{n} \sum_{i=1}^{n} \hat{F}\left(v,\; x_{i,\text{other}}\right)$$
```{r pdp_fun}
partial_dependence <- function(fit, x, feature, grid) {
data.frame(value = grid,
prediction = sapply(grid, function(v) { x[, feature] <- v; mean(predict(fit, x)) }))
}
top4 <- rank_perm[1:4]
pd <- do.call(rbind, lapply(top4, function(v) {
grid <- seq(quantile(train[[v]], 0.01), quantile(train[[v]], 0.99), length.out = 40)
cbind(feature = nice[[v]], partial_dependence(fit, x_train, v, grid))
}))
pd$feature <- factor(pd$feature, levels = nice[top4])
```
```{r pdp, fig.height = 5.5}
ggplot(pd, aes(value, prediction)) +
geom_line(colour = colours[1], linewidth = 0.9) +
facet_wrap(~ feature, scales = "free_x") +
labs(x = "Value of the predictor", y = "Average predicted strength (MPa)") +
theme_bw()
```
These are the shapes the straight line could not draw. Strength rises quickly with age and then flattens; it rises with cement; it falls with water. Where a curve is flat, the model sees no further change. The curve is only a summary of the average: if the effect of a predictor depends on another (an interaction), the average hides it. A partial dependence for **two** predictors at once shows it. Here is the effect of slag, with the age set to 3 days, 28 days and one year for every sample:
```{r pdp_interaction, fig.height = 4}
slag_grid <- seq(0, quantile(train$slag, 0.99), length.out = 40)
pd_int <- do.call(rbind, lapply(c(3, 28, 365), function(a) {
x_age <- x_train; x_age[, "age"] <- a # every sample gets this age
cbind(age = paste(a, "days"), partial_dependence(fit, x_age, "slag", slag_grid))
}))
pd_int$age <- factor(pd_int$age, levels = c("3 days", "28 days", "365 days"))
ggplot(pd_int, aes(value, prediction, colour = age)) +
geom_line(linewidth = 0.9) +
scale_colour_manual(values = colours[1:3]) +
labs(x = "Blast furnace slag (kg per m³)", y = "Average predicted strength (MPa)", colour = "Age") +
theme_bw() + theme(legend.position = "bottom")
rise <- tapply(pd_int$prediction, pd_int$age, function(p) p[length(p)] - p[1])
```
The lines are far from parallel: going from no slag to `r num(round(max(slag_grid)))` kg changes the predicted strength by `r f1(rise[["3 days"]])` MPa at 3 days, `r f1(rise[["28 days"]])` MPa at 28 days and `r f1(rise[["365 days"]])` MPa at one year. The model has found the interaction of section 2 without being told.
### One sample at a time: SHAP values
**SHAP values** (SHapley Additive exPlanations; Lundberg & Lee, 2017) split the prediction for one sample among the predictors, so that
$$\hat{F}(x) = \underbrace{\phi_0}_{\text{average prediction}} + \phi_{\text{cement}} + \phi_{\text{water}} + \dots + \phi_{\text{age}}$$
Each $\phi_j$ is the contribution of predictor $j$ for this sample: how many MPa it moves the prediction up or down from the average. For tree models they can be computed exactly and quickly, and `xgboost` does it with `predict(..., predcontrib = TRUE)`:
```{r shap}
shap <- predict(fit, x_test, predcontrib = TRUE)
colnames(shap)
# the contributions and the (Intercept) column (the average prediction) add up to the prediction
all.equal(unname(rowSums(shap)), unname(predict(fit, x_test)), tolerance = 1e-4)
```
The last column, `(Intercept)`, is $\phi_0$. The check shows that for every test sample, the contributions add up to the prediction. Here are two samples: the one the model predicts to be strongest, and the one it predicts to be weakest:
```{r shap_two, fig.height = 5}
pred_test <- unname(predict(fit, x_test))
two <- c(strong = which.max(pred_test), weak = which.min(pred_test))
shap_two <- do.call(rbind, lapply(names(two), function(k) {
i <- two[[k]]
data.frame(sample = factor(k, levels = c("strong", "weak"),
labels = c(paste0("Strongest predicted: ", f1(pred_test[i]), " MPa"),
paste0("Weakest predicted: ", f1(pred_test[i]), " MPa"))),
label = paste0(nice[predictors], " = ", sapply(x_test[i, predictors], function(v) format(v, digits = 3))),
shap = shap[i, predictors])
}))
shap_two$direction <- factor(ifelse(shap_two$shap > 0, "Raises", "Lowers"), levels = c("Raises", "Lowers"))
shap_two$label <- reorder(shap_two$label, abs(shap_two$shap))
ggplot(shap_two, aes(shap, label, fill = direction)) +
geom_col() +
geom_vline(xintercept = 0, colour = "grey40") +
facet_wrap(~ sample, scales = "free_y", ncol = 1) +
scale_fill_manual(values = colours[1:2]) +
labs(x = "Contribution to the prediction (MPa)", y = NULL, fill = "Prediction") +
theme_bw() + theme(legend.position = "bottom")
base <- shap[1, "(Intercept)"]
```
Start from the average prediction, `r f1(base)` MPa. For the strongest sample, the bars to the right push the prediction up, to `r f1(pred_test[two[["strong"]]])` MPa, and for the weakest the bars to the left pull it down to `r f1(pred_test[two[["weak"]]])` MPa. The labels show the value of each predictor in that sample, so each bar can be read as a sentence ("with this much water, the prediction goes down by so many MPa").
Averaging the size of the SHAP values over all test samples gives a **global** importance that, unlike gain, is based on what the model does for each sample. Plotting all of them shows the **direction** too:
```{r shap_summary, fig.height = 5.5}
shap_all <- as.data.frame(shap[, predictors])
mean_abs <- sort(colMeans(abs(shap_all)), decreasing = TRUE)
long <- do.call(rbind, lapply(predictors, function(v)
data.frame(feature = nice[[v]], shap = shap_all[[v]],
value = factor(ifelse(test[[v]] > median(train[[v]]), "High", "Low"), levels = c("Low", "High")))))
long$feature <- factor(long$feature, levels = rev(nice[names(mean_abs)]))
set.seed(7)
ggplot(long, aes(shap, feature, colour = value)) +
geom_vline(xintercept = 0, colour = "grey40") +
geom_jitter(height = 0.2, alpha = 0.7) +
scale_colour_manual(values = colours[1:2]) +
labs(x = "SHAP value: contribution to the prediction (MPa)", y = NULL,
colour = "Value of the predictor\n(against the training median)") +
theme_bw() + theme(legend.position = "bottom")
```
Each point is one test sample. High values of cement (orange) sit on the right: they push the strength up. High values of water sit on the left. For age, the picture is more mixed, because the effect of age is not a straight line: young concrete is pulled down by more MPa than old concrete is pushed up. Ordered by mean size, the top predictors are `r paste(nice[names(mean_abs)][1:3], collapse = ", ")`.
---
## 8. Caveats
**Tuning sensitivity.** Boosting is more sensitive to its settings than a random forest. A learning rate that is too high, or too many deep trees, can overfit badly, as the charts above show. Always choose the number of trees by cross-validation or a validation set, never by what looks good on the training data, and never on the test set. The tuning grid here is small; with more computing time one would search more finely (random search, or Bayesian optimization).
**Extrapolation.** A tree predicts an average of samples it has seen, so the prediction **stays flat outside the range of the data**. A boosted model cannot predict that concrete with more cement than any in the data will be even stronger; and the model knows nothing about concrete older than a year. A linear model would extrapolate (not necessarily well). Be careful with mixes unlike the training data.
```{r extrapolation, fig.height = 3.5}
g <- seq(300, 700, length.out = 60)
ext <- partial_dependence(fit, x_train, "cement", g)
ggplot(ext, aes(value, prediction)) +
geom_line(colour = colours[1], linewidth = 0.9) +
geom_vline(xintercept = max(train$cement), linetype = "dashed", colour = "grey40") +
annotate("text", x = max(train$cement), y = min(ext$prediction), label = "most cement in the data",
hjust = 1.05, vjust = -0.5, colour = "grey20") +
labs(x = "Cement (kg per m³)", y = "Average predicted strength (MPa)") +
theme_bw()
```
Beyond the dashed line the prediction is a flat line: it is not a forecast, it is only what the model does at the edge of what it knows.
**Importance is not causation.** The predictors in these data are related to each other: engineers add superplasticizer **in order to** use less water, and mixes with slag are designed differently from those without. So a large importance or a steep partial dependence for water does not mean that adding water to a given concrete will lower its strength by that amount. The model shows what **goes with** strength in these data, which is what prediction needs. Causal questions need an experiment or a causal design.
**Other things to keep in mind.**
- The data are one study, from one laboratory: the model describes **these** mixes and materials. Cement from other suppliers may behave differently.
- The `r n_dup` duplicated rows may sit in both the training and the validation parts of a cross-validation fold, which makes the validation error a little too optimistic. The test set may share a few of them too.
- The test result rests on `r nrow(test)` samples and one random split. Repeating the split, or using nested cross-validation, would give a more stable estimate.
- Boosting predicts the **average** strength for a mix. It does not by itself give a prediction interval; for safety decisions you need one (for example from quantile loss, or conformal prediction).
---
## 9. Reporting the results in APA style
Report a predictive model as you would any other: what was predicted and from what, how the data were split, how the settings were chosen, and how well the model did **on data it had not seen**.
```{r apa_numbers, include=FALSE}
res <- results
```
**Method:**
> We predicted the compressive strength of concrete (MPa) from seven mix ingredients and age, using gradient boosting with squared-error loss (xgboost, version `r as.character(packageVersion("xgboost"))`; Chen & Guestrin, 2016). The `r num(nrow(concrete))` samples (Yeh, 1998) were split at random into a training set (*n* = `r num(nrow(train))`) and a test set (*n* = `r num(nrow(test))`). The settings were chosen on the training set by five-fold cross-validation over a grid of 36 combinations of learning rate, tree depth, minimum child weight and row sampling; the number of trees was chosen by early stopping. The selected model had a learning rate of `r best$eta`, a maximum depth of `r best$max_depth`, a minimum child weight of `r best$min_child_weight`, row sampling of `r best$subsample`, column sampling of 0.8 and `r num(best$trees)` trees. We compared it on the test set with linear regression, a pruned regression tree and a random forest with default settings (ranger; Wright & Ziegler, 2017). Predictors were explained with gain, permutation importance, partial dependence and SHAP values (Lundberg & Lee, 2017).
**Results:**
> On the test set, gradient boosting predicted concrete strength with an RMSE of `r f2(res["Gradient boosting", "RMSE"])` MPa, an MAE of `r f2(res["Gradient boosting", "MAE"])` MPa and *R*² = `r nz(res["Gradient boosting", "R2"])`. This was better than linear regression (RMSE = `r f2(res["Linear regression", "RMSE"])`, *R*² = `r nz(res["Linear regression", "R2"])`) and a single regression tree (RMSE = `r f2(res["Single tree", "RMSE"])`, *R*² = `r nz(res["Single tree", "R2"])`), and `r if (res["Gradient boosting", "RMSE"] < res["Random forest", "RMSE"]) "better than" else "similar to"` an untuned random forest (RMSE = `r f2(res["Random forest", "RMSE"])`, *R*² = `r nz(res["Random forest", "R2"])`). The most important predictors were `r paste(tolower(nice[rank_perm][1:3]), collapse = ", ")` (permutation importance), and the partial dependence plots showed that strength rose steeply with age at first and then leveled off.
**Table 1**
*Test-Set Performance of Four Models Predicting the Compressive Strength of Concrete*
```{r apa_table, echo=FALSE}
knitr::kable(results, digits = 2, align = "rrr")
```
*Note.* *N* = `r num(nrow(test))` test samples. RMSE = root mean squared error; MAE = mean absolute error (both in MPa); *R*² = 1 − SSE/SST on the test set.
**Points to remember:**
- Say that the performance is measured on a test set (or by cross-validation) and **never** on the data used for fitting.
- Report the error in the units of the outcome (RMSE, MAE), and $R^2$ if it helps; compare with a simple baseline, not only with "nothing".
- Report all the settings, the number of trees and how they were chosen, and the package versions.
- Set and report the random seed: boosting with row and column sampling is random.
- Say what the importance and the partial dependence mean, and that they are not causal effects.
- Cite R, the packages (`citation("xgboost")`) and the data.
---
## 10. Summary
| | |
|---|---|
| **When** | A continuous outcome, a table of numbers, curved effects and interactions you do not want to specify by hand |
| **Idea** | Start from the mean; fit a small tree to the residuals; add it, scaled by a learning rate; repeat |
| **Loss and gradient** | Squared error: the negative gradient is the residual. Other losses give other "residuals" |
| **How (R)** | `xgb.train(params, xgb.DMatrix(x, label = y), nrounds)`; `xgb.cv()` for cross-validation and early stopping |
| **Main settings** | Learning rate, number of trees, depth, row and column sampling, minimum child weight, penalties |
| **Overfitting** | Too many trees overfit: choose the number of trees by cross-validation with early stopping |
| **Compare with** | A baseline model, and a random forest; judge on a test set with RMSE, MAE and $R^2$ |
| **Interpretation** | Gain and permutation importance; partial dependence; SHAP values with `predict(..., predcontrib = TRUE)` |
| **Cautions** | Sensitive to tuning; flat outside the range of the data; importance is not causation |
---
## References
Breiman, L. (2001). Random forests. *Machine Learning*, *45*(1), 5–32. https://doi.org/10.1023/A:1010933404324
Chen, T., & Guestrin, C. (2016). XGBoost: A scalable tree boosting system. In *Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining* (pp. 785–794). ACM. https://doi.org/10.1145/2939672.2939785
Chen, T., He, T., Benesty, M., Khotilovich, V., Tang, Y., Cho, H., Chen, K., Mitchell, R., Cano, I., Zhou, T., Li, M., Xie, J., Lin, M., Geng, Y., Li, Y., & Yuan, J. (2026). *xgboost: Extreme gradient boosting* (R package version 3.2.1.1). https://CRAN.R-project.org/package=xgboost
Friedman, J. H. (2001). Greedy function approximation: A gradient boosting machine. *The Annals of Statistics*, *29*(5), 1189–1232. https://doi.org/10.1214/aos/1013203451
Hastie, T., Tibshirani, R., & Friedman, J. (2009). *The elements of statistical learning: Data mining, inference, and prediction* (2nd ed.). Springer.
Lundberg, S. M., & Lee, S.-I. (2017). A unified approach to interpreting model predictions. In *Advances in Neural Information Processing Systems* (Vol. 30, pp. 4765–4774).
Molnar, C. (2022). *Interpretable machine learning: A guide for making black box models explainable* (2nd ed.). https://christophm.github.io/interpretable-ml-book/
Therneau, T., & Atkinson, B. (2026). *rpart: Recursive partitioning and regression trees* (R package version 4.1.27). https://CRAN.R-project.org/package=rpart
Wright, M. N., & Ziegler, A. (2017). ranger: A fast implementation of random forests for high dimensional data in C++ and R. *Journal of Statistical Software*, *77*(1), 1–17. https://doi.org/10.18637/jss.v077.i01
Yeh, I.-C. (1998). Modeling of strength of high-performance concrete using artificial neural networks. *Cement and Concrete Research*, *28*(12), 1797–1808. https://doi.org/10.1016/S0008-8846(98)00165-3
Yeh, I.-C. (2007). *Concrete compressive strength* [Data set]. UCI Machine Learning Repository. https://doi.org/10.24432/C5PK67