Skip to main content

Gradient Boosting: How Strong Is This Concrete?

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.

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) 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 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
Code
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] '3.2.1.1'

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.

Code
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)
'data.frame':   1030 obs. of  9 variables:
 $ cement          : num  540 540 332 332 199 ...
 $ slag            : num  0 0 142 142 132 ...
 $ fly_ash         : num  0 0 0 0 0 0 0 0 0 0 ...
 $ water           : num  162 162 228 228 192 228 228 228 228 228 ...
 $ superplasticizer: num  2.5 2.5 0 0 0 0 0 0 0 0 ...
 $ coarse          : num  1040 1055 932 932 978 ...
 $ fine            : num  676 676 594 594 826 ...
 $ age             : num  28 28 270 365 360 90 365 28 28 28 ...
 $ strength        : num  80 61.9 40.3 41.1 44.3 ...

The download took 1.0 seconds for 33.6 KB. There are 1,030 concrete samples, with no missing values (0 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
Code
n_dup <- sum(duplicated(concrete))

25 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.

Code
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))
train  test 
  824   206 

2. Look at the data

Code
summary(concrete$strength)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  2.332  23.707  34.443  35.818  46.136  82.599 

The strength runs from 2.3 to 82.6 MPa, with a mean of 35.8 and a standard deviation of 16.7. 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:

Code
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()

Look age – 2. Look at the data

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:

Code
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")

Look slag – 2. Look at the data

Code
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 0.5 MPa more strength in young concrete, 2.4 at 28 days and 6.6 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\) = 35.6 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.

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\):

Code
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:

Code
hand$trees[[1]]
n= 824 

node), split, n, deviance, yval
      * denotes terminal node

1) root 824 229110.200  5.173855e-16  
  2) age< 21 252  38264.030 -1.238405e+01  
    4) cement< 354.5 177  13384.450 -1.742980e+01 *
    5) cement>=354.5 75   9738.268 -4.760845e-01 *
  3) age>=21 572 135171.600  5.455910e+00  
    6) cement< 352.5 433  66719.190  5.821498e-01 *
    7) cement>=352.5 139  26127.370  2.063820e+01 *

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 age. The last number on a leaf line is the average residual in that group, for instance -17.4 MPa in the group the constant overestimates most and 20.6 in the one it underestimates most. The model adds \(\nu = 0.3\) of those numbers to its predictions.

The error after the first rounds:

Code
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")
Trees Training RMSE Test RMSE
0 16.67 16.79
1 14.42 14.78
2 12.84 12.90
3 11.59 11.60
5 10.03 10.21
10 7.52 8.07
20 5.81 6.60
50 4.57 5.61
100 3.80 5.16

(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 16.7 MPa for the constant model to 14.4 after one tree, 11.6 after three and 3.8 after 100. The chart shows the residuals, the mistakes still left, shrinking:

Code
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()

By hand residuals – Step 7: boosting by hand

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.

Code
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:

Code
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()

Learning rate and number of trees

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 4.98 MPa. The middle rate (0.1) needs a few hundred trees and gets lower, to 4.48 MPa. The smallest rate (0.02) is still improving after the 1,500 trees tried here (4.62 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.

Code
# 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")

Overfitting: training error against validation error

The training error keeps falling, down to 0.90 MPa after 409 trees. The validation error stops improving at 379 trees (4.74 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.

Code
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"))
Learning rate Depth Min. child weight Row sampling Trees CV RMSE
0.10 4 1 1.0 888 4.22
0.10 4 1 0.7 435 4.28
0.10 4 5 1.0 799 4.28
0.05 6 5 0.7 651 4.28
0.05 4 5 0.7 837 4.30
0.05 4 1 0.7 597 4.30
0.10 4 5 0.7 508 4.30
0.05 4 5 1.0 1418 4.31

The best combination is a learning rate of 0.1, depth 4, minimum child weight 1 and row sampling of 1, with 888 trees and a cross-validated RMSE of 4.22 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:

Code
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")
Depth Best CV RMSE
2 4.40
4 4.22
6 4.28

5. Fitting the final model

We fit the model to all the training data with the chosen settings and number of trees:

Code
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
##### xgb.Booster
call:
  xgb.train(params = params, data = d_train, nrounds = best$trees)
# of features: 8 
# of rounds:  888 

The model is a sum of 888 trees. Here are the first three, each only a few levels deep:

Code
trees <- xgb.model.dt.tree(model = fit, trees = 1:3)
head(trees[, c("Tree", "Node", "Feature", "Split", "Yes", "No", "Gain")], 9)
    Tree  Node          Feature  Split    Yes     No       Gain
   <int> <int>           <char>  <num> <char> <char>      <num>
1:     0     0              age  28.00    0-1    0-2 55492.1250
2:     0     1 superplasticizer   7.79    0-3    0-4 11249.4492
3:     0     2            water 175.60    0-5    0-6 32350.2051
4:     0     3             fine 613.20    0-7    0-8  4442.5703
5:     0     4           coarse 967.08    0-9   0-10  3304.6191
6:     0     5           coarse 947.04   0-11   0-12 10169.9805
7:     0     6              age  56.00   0-13   0-14  8357.7705
8:     0     7            water 189.29   0-15   0-16   942.2425
9:     0     8              age   7.00   0-17   0-18  1388.1641

Nobody can read 888 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), pruned by cross-validation.
  • A random forest (ranger) with its default settings (500 trees).
  • Gradient boosting, tuned as above.
Code
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 MAE R2
Linear regression 10.43 8.41 0.61
Single tree 9.60 7.45 0.67
Random forest 5.66 4.43 0.89
Gradient boosting 3.93 2.78 0.95

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 10.43 MPa. The single tree is 9.60. The random forest reaches 5.66, and gradient boosting 3.93 MPa (\(R^2\) = .95). Gradient boosting’s typical mistake is 2.8 MPa, against a standard deviation of 16.8 MPa in the test strengths.

Code
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()

Predicted observed – 6. Does it beat simpler models? The test set

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 206 samples, so each of these numbers has some noise; the gap between boosting and the forest (1.72 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.
Code
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")

Importance – Which predictors matter? Gain against permutation

Code
rank_gain <- names(sort(gain, decreasing = TRUE)); rank_perm <- names(sort(permutation, decreasing = TRUE))

By gain the order is Age (days), Cement, Water; by permutation it is Age (days), Cement, Water. The top predictor, age (days), accounts for 37% of the permutation importance: shuffling it raises the test RMSE by 12.1 MPa. The two measures give the same order here, 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)\]

Code
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])
Code
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()

Pdp – Which way? Partial dependence

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:

Code
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")

Pdp interaction – Which way? Partial dependence

Code
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 290 kg changes the predicted strength by 5.3 MPa at 3 days, 18.0 MPa at 28 days and 14.3 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):

Code
shap <- predict(fit, x_test, predcontrib = TRUE)
colnames(shap)
[1] "cement"           "slag"             "fly_ash"          "water"            "superplasticizer" "coarse"           "fine"             "age"              "(Intercept)"     
Code
# 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)
[1] TRUE

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:

Code
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")

Shap two – One sample at a time: SHAP values

Code
base <- shap[1, "(Intercept)"]

Start from the average prediction, 35.6 MPa. For the strongest sample, the bars to the right push the prediction up, to 74.9 MPa, and for the weakest the bars to the left pull it down to 5.0 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:

Code
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")

Shap summary – One sample at a time: SHAP values

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 Age (days), Cement, Water.


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.

Code
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()

Extrapolation – 8. Caveats

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 25 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 206 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.

Method:

We predicted the compressive strength of concrete (MPa) from seven mix ingredients and age, using gradient boosting with squared-error loss (xgboost, version 3.2.1.1; Chen & Guestrin, 2016). The 1,030 samples (Yeh, 1998) were split at random into a training set (n = 824) and a test set (n = 206). 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 0.1, a maximum depth of 4, a minimum child weight of 1, row sampling of 1, column sampling of 0.8 and 888 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 3.93 MPa, an MAE of 2.78 MPa and R² = .95. This was better than linear regression (RMSE = 10.43, R² = .61) and a single regression tree (RMSE = 9.60, R² = .67), and better than an untuned random forest (RMSE = 5.66, R² = .89). The most important predictors were age (days), cement, water (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

RMSE MAE R2
Linear regression 10.43 8.41 0.61
Single tree 9.60 7.45 0.67
Random forest 5.66 4.43 0.89
Gradient boosting 3.93 2.78 0.95

Note. N = 206 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