Beyond the GLM, part 2: correlated features, two stages and black boxes
glm-to-comprehensive-pricing-chalk-2.RmdRendered from docs/guides/glm-to-comprehensive-pricing-chalk-2.qmd.
The code runs each time the site is built, so the output below is
current.
Part 2 of the guide to CAS Monograph 16, From GLMs to
Comprehensive Insurance Pricing: Techniques and Challenges (Chalk,
Deacon, Guillen and Martinelli, 2025), the R twin of the Python guide glm-to-comprehensive-pricing-chalk-2.md.
Part 1 covers
chapters 3 to 6 and tells which examples the guide reproduces, where the
data comes from and how the numbers are checked. This part covers
chapters 7 to 10. Table and section numbers are the monograph’s.
CI runs every R chunk that has a text block after it
(R/prospicio/tests/test-guides.R) and requires the Python
guide’s text. The data are the same draws (read from
examples/data/), and the models run on the same Rust code
with the same LightGBM parameters.
The chunk below rebuilds what part 1 built: the simulated portfolio
(20,000 policies, folds from the policy number, folds 7 to 9 for
testing), the pseudo-R2 helper and cross-validation loop, the baseline
GLM and boosting formulas, the age steps that the lasso keeps, and the
out-of-fold target encoding of make (target_encode(), with
encode_target() for rows outside the training folds). Part
1 explains each piece.
library(prospicio)
# The data files, found from the repository root (CI) or from docs/guides (Quarto).
find_data <- function(name, dir = getwd()) {
repeat {
path <- file.path(dir, "examples", "data", name)
if (file.exists(path)) return(path)
parent <- dirname(dir)
if (identical(parent, dir)) stop("examples/data/", name, " not found", call. = FALSE)
dir <- parent
}
}
pf <- utils::read.csv(find_data("chalk_portfolio.csv"), comment.char = "#")
toys <- utils::read.csv(find_data("chalk_toys.csv"), comment.char = "#")
n <- nrow(pf)
pf$region <- factor(pf$region, levels = c("A", "B", "C", "D", "E", "F"))
pf$power <- factor(pf$power, levels = c("low", "mid", "high"))
make_effect <- toys$y[toys$example == "make_effect"]
region_effect <- c(A = 0, B = 0.15, C = -0.2, D = 0, E = 0, F = 0.3)
true_lp <- with(pf, log(0.25) + 0.9 * exp(-(age - 18) / 6) + 0.0015 * pmax(age - 60, 0)^1.5 -
0.08 * pmin(veh_age, 6) + unname(region_effect[as.character(region)]) + make_effect[make + 1] +
0.25 * (power == "high") + 0.6 * (power == "high" & age < 25))
pf$fold <- (seq_len(n) - 1) %% 10
train <- pf$fold < 7
truth <- exp(true_lp) * pf$exposure
pseudo_r2 <- function(y, mu, expo) {
null <- expo * sum(y) / sum(expo)
1 - family_deviance("poisson", y, mu) / family_deviance("poisson", y, null)
}
# Python's list of formatted numbers: ['0.100', '0.200'].
py_list <- function(x, digits) {
paste0("[", paste0("'", sprintf(paste0("%.", digits, "f"), x), "'", collapse = ", "), "]")
}
# Trees see region and power as the codes of their levels in alphabetical order.
tree_codes <- function(d) {
d$region_code <- match(as.character(d$region), c("A", "B", "C", "D", "E", "F")) - 1
d$power_code <- match(as.character(d$power), c("high", "low", "mid")) - 1
d
}
pf <- tree_codes(pf)
f_base <- claims ~ age + veh_age + region + power + offset(log(exposure))
f_tree <- claims ~ age + veh_age + region_code + power_code + make + noise + offset(log(exposure))
gbm_params <- list(num_leaves = 7, min_data_in_leaf = 200, num_threads = 1)
gbm_fit <- function(formula, d, rounds = 150) {
booster_fit(formula, d, n_rounds = rounds, learning_rate = 0.05, params = gbm_params, seed = 1)
}
cells <- aggregate(cbind(claims, exposure) ~ age + fold, pf, sum)
cells <- cells[order(cells$age * 10 + cells$fold), ]
knots <- seq(20, 77, by = 3)
step_names <- paste0("age_stp_", knots)
for (a in knots) cells[[paste0("age_stp_", a)]] <- as.numeric(cells$age >= a)
cells_tr <- cells[cells$fold < 7, ]
f_steps <- reformulate(c(step_names, "offset(log(exposure))"), "claims")
lams <- elastic_net_fit(f_steps, cells_tr, alpha = 0.99, nlambda = 25, lambda_min_ratio = 1e-3)@lambda
cvp <- elastic_net_cv(f_steps, cells_tr, alpha = 0.99, lambda = lams, foldid = cells_tr$fold + 1)
kept <- knots[cvp$fit@coefficients[step_names, which(lams == cvp$lambda_min)] != 0]
expected <- numeric(n)
for (j in 0:6) {
fit_j <- glm_fit(f_base, pf[train & pf$fold != j, ])
expected[pf$fold == j] <- predict(fit_j, pf[pf$fold == j, ])
}
expected[!train] <- predict(glm_fit(f_base, pf[train, ]), pf[!train, ])
make_level <- as.character(pf$make)
# Per policy, the log of the make's shrunk actual-to-expected ratio: a training row in fold j is
# encoded from the training folds other than j (and other than the held-out fold), every other row
# from all training folds but the held-out one.
make_feature <- function(K, held_out = -1) {
src <- which(train & pf$fold != held_out)
splits <- lapply(setdiff(0:6, held_out), function(j) {
list(train = which(pf$fold[src] != j), test = which(pf$fold[src] == j))
})
enc <- target_encode(make_level[src], pf$claims[src], expected[src], splits, K, pf$exposure[src])
te <- encode_target(enc$encoding, make_level)
te[src] <- enc$rows
log(te)
}
cat(sprintf("%d policies, %.0f claims; age steps kept by the lasso at [%s]\n",
n, sum(pf$claims), paste(kept, collapse = ", ")))## 20000 policies, 3659 claims; age steps kept by the lasso at [20, 23, 26, 29, 32, 62, 65, 77]
1. Highly correlated variables (chapter 7)
A GLM can split the joint effect of two near-identical features in
many ways (section 7.2), so small changes in the data move the
coefficients. The portfolio’s exper is driver age less 17
less a small random amount: correlation 0.997 with age and no effect of
its own. The chunk fits both on each of the seven cross-validation
training sets, with and without a penalty (section 7.4):
library(gt)
f_corr <- claims ~ age + exper + offset(log(exposure))
fits_by <- list(
GLM = function(d) coef(glm_fit(f_corr, d)),
ridge = function(d) elastic_net_fit(f_corr, d, alpha = 0, lambda = 0.01)@coefficients[, 1],
lasso = function(d) elastic_net_fit(f_corr, d, alpha = 1, lambda = 0.001)@coefficients[, 1]
)
summary_rows <- lapply(names(fits_by), function(name) {
coefs <- t(vapply(0:6, function(k) fits_by[[name]](pf[train & pf$fold != k, ])[c("age", "exper")],
double(2)))
data.frame(fit = name, `age min` = min(coefs[, 1]), `age max` = max(coefs[, 1]),
`exper min` = min(coefs[, 2]), `exper max` = max(coefs[, 2]),
sum = mean(rowSums(coefs)), check.names = FALSE)
})
gt(do.call(rbind, summary_rows), rowname_col = "fit") |>
tab_header("Age and experience fitted together", "Coefficient over the seven training sets") |>
fmt_number(decimals = 4, force_sign = TRUE)| Age and experience fitted together | |||||
| Coefficient over the seven training sets | |||||
| age min | age max | exper min | exper max | sum | |
|---|---|---|---|---|---|
| GLM | −0.0540 | −0.0409 | +0.0340 | +0.0467 | −0.0072 |
| ridge | −0.0061 | −0.0052 | −0.0016 | −0.0010 | −0.0070 |
| lasso | −0.0074 | −0.0066 | 0.0000 | 0.0000 | −0.0070 |
The unpenalized coefficients change much between training sets, but their sum (one year of age and experience together) hardly changes. Ridge shares the effect and keeps both stable. The lasso keeps one feature, which is stable here but can flip when the features are even closer (section 7.5.3).
For principal components (section 7.4.5), take
stats::prcomp() of the scaled columns and put the
components into a formula like any other column.
2. Modelling in two stages (chapter 8)
2.1 The marketing discount as an offset
Chapter 8 has the only fully specified data set in the monograph: one million simulated auto policies. Age group (A to E) and no-claims bonus (NCB 0 to 4) are strongly related. Table 8.2 gives the policies per cell, Table 8.3 the true relativities, section 8.1 a base frequency of 10% for age A and NCB 0. A Poisson GLM on the 25 cells, with expected claims as response, gives the fit that the monograph’s simulation estimates with noise:
table_8_2 <- list(A = c(132381, 54519, 12194, 1237, 26), B = c(55624, 82213, 49354, 12283, 952),
C = c(11053, 49903, 77029, 50248, 11291), D = c(920, 12187, 49027, 81946, 55690),
E = c(22, 1178, 12396, 54286, 132041))
age_rel <- c(A = 1, B = 0.7, C = 0.6, D = 0.5, E = 0.4)
ncb_rel <- c(1, 0.95, 0.9, 0.85, 0.8)
marketing <- c(1, 0.65, 0.50, 0.40, 0.20)
data_8 <- data.frame(age = rep(names(table_8_2), each = 5), ncb = rep(0:4, 5),
policies = unlist(table_8_2, use.names = FALSE))
data_8$expected_claims <- data_8$policies * 0.10 * age_rel[data_8$age] * ncb_rel[data_8$ncb + 1]
data_8$mkt <- marketing[data_8$ncb + 1]
data_8$ncb <- factor(data_8$ncb)
cat(sprintf("policies %s\n", formatC(sum(data_8$policies), format = "f", digits = 0, big.mark = ",")))## policies 1,000,000
full <- glm_fit(expected_claims ~ age + ncb + offset(log(policies)), data_8)
true_rel <- c(0.10 * age_rel[["A"]] * ncb_rel[1], unname(age_rel[c("B", "C", "D", "E")]), ncb_rel[-1])
gt(data.frame(coefficient = c("intercept", paste("age", c("B", "C", "D", "E")), paste("NCB", 1:4)),
true = true_rel, fitted = unname(exp(coef(full)))), rowname_col = "coefficient") |>
tab_header("Relativities with age and NCB in the model", "Poisson GLM on the 25 cells") |>
fmt_number(decimals = 3)| Relativities with age and NCB in the model | ||
| Poisson GLM on the 25 cells | ||
| true | fitted | |
|---|---|---|
| intercept | 0.100 | 0.100 |
| age B | 0.700 | 0.700 |
| age C | 0.600 | 0.600 |
| age D | 0.500 | 0.500 |
| age E | 0.400 | 0.400 |
| NCB 1 | 0.950 | 0.950 |
| NCB 2 | 0.900 | 0.900 |
| NCB 3 | 0.850 | 0.850 |
| NCB 4 | 0.800 | 0.800 |
The fit gives the truth; the monograph’s own fit on its noisy simulation (Table 8.4) is within about 0.025 of it. Next, the marketing department’s NCB scale goes in as an offset and age is fitted again. Age relativities now increase with age, because age carries part of the NCB effect that the offset removed. The book’s differences come from the noise in its simulation:
offset_fit <- glm_fit(expected_claims ~ age + offset(log(policies * mkt)), data_8)
rel <- unname(exp(coef(offset_fit)))
gt(data.frame(coefficient = c("intercept", paste("age", c("B", "C", "D", "E"))),
book = c(0.112, 0.849, 0.925, 0.980, 1.057), prospicio = rel), rowname_col = "coefficient") |>
tab_header("Table 8.6: age relativities with the NCB scale as offset") |>
fmt_number(columns = book, decimals = 3) |>
fmt_number(columns = prospicio, decimals = 4)| Table 8.6: age relativities with the NCB scale as offset | ||
| book | prospicio | |
|---|---|---|
| intercept | 0.112 | 0.1125 |
| age B | 0.849 | 0.8485 |
| age C | 0.925 | 0.9175 |
| age D | 0.980 | 0.9825 |
| age E | 1.057 | 1.0586 |
Section 8.1 then gives risk premiums at a claim size of 10,000:
premiums <- data.frame(
premium = c("true A/0", "true E/4", "GLM E/4, printed coefficients", "GLM age with marketing NCB",
"offset model E/4, printed coefficients", "offset model E/4, recomputed coefficients"),
book = c(1000, 320, 322, 78, 237, 237),
prospicio = c(0.10 * 1 * 1 * 10000, 0.10 * 0.4 * 0.8 * 10000, 0.10 * 0.39 * 0.826 * 10000,
0.10 * 0.39 * 0.20 * 10000, 0.112 * 1.057 * 0.20 * 10000, rel[1] * rel[5] * 0.20 * 10000)
)
gt(premiums, rowname_col = "premium") |>
tab_header("Section 8.1: risk premiums at a claim size of 10,000") |>
fmt_integer(columns = c(book, prospicio))| Section 8.1: risk premiums at a claim size of 10,000 | ||
| book | prospicio | |
|---|---|---|
| true A/0 | 1,000 | 1,000 |
| true E/4 | 320 | 320 |
| GLM E/4, printed coefficients | 322 | 322 |
| GLM age with marketing NCB | 78 | 78 |
| offset model E/4, printed coefficients | 237 | 237 |
| offset model E/4, recomputed coefficients | 237 | 238 |
2.2 Offsets and residuals give the same second stage
A second stage can continue from a first stage in two ways (sections 8.3 to 8.5): with the log of the first-stage predicted counts as an offset, or with the residual (actual over predicted counts) as the response and the predicted counts as weights. Yan and others, and Shi, show that the two are identical for a Poisson log-link model. The chunk fits a first stage without region, then a second stage with region only:
tr <- pf[train, ]
tr$mu1 <- predict(glm_fit(claims ~ age + veh_age + power + offset(log(exposure)), tr), tr)
by_offset <- glm_fit(claims ~ region + offset(log(mu1)), tr)
by_residual <- glm_fit(I(claims / mu1) ~ region, tr, weights = tr$mu1)
gt(data.frame(coefficient = c("intercept", paste("region", c("B", "C", "D", "E", "F"))),
offset = unname(exp(coef(by_offset))), residual = unname(exp(coef(by_residual)))),
rowname_col = "coefficient") |>
tab_header("Second stage by offset and by residual", "Region relativities") |>
fmt_number(decimals = 4)| Second stage by offset and by residual | ||
| Region relativities | ||
| offset | residual | |
|---|---|---|
| intercept | 0.9301 | 0.9301 |
| region B | 1.2148 | 1.2148 |
| region C | 0.8598 | 0.8598 |
| region D | 1.0619 | 1.0619 |
| region E | 1.0436 | 1.0436 |
| region F | 1.4061 | 1.4061 |
In the zip code summary of section 8.4, the first rows have residuals 0 / 0.014 = 0 and 1 / 0.739 = 1.353.
Section 8.9.1 adds a caution: cross-fit the first-stage predictions,
as part 1 did for expected in section 4.4, so that a model
predicts only records it did not see. An overfitted first stage leaves
nothing for the second stage to find (Table 8.12); cross-fitted
predictions leave residuals such as 3 / 5 = 0.6 and 7 / 5 = 1.4 (Table
8.13).
For a spatial second stage like Figure 8.2, use a
gam_fit() with the tensor product smooth
tensors = list(c("lon", "lat")) and the first stage as
offset.
2.3 Combining tables and area groups
Section 8.7 multiplies the seven aircraft tables into one relativity for the Cessna 172M. Section 8.9.2 replaces 30,000 zip code relativities by 100 area groups, in equal multiplicative steps from the smallest (0.379) to the largest (1.851) relativity:
table_8_11 <- c(1.30, 1.15, 1.00, 1.36, 1.69, 1.00, 0.41, 0.97)
step <- (1.851 / 0.379)^(1 / 99)
checks <- data.frame(
item = c("Cessna 172M relativity", "range, largest over smallest", "step", "range from 99 printed steps"),
book = c(1.37, 4.884, 1.0162, 4.908),
prospicio = c(prod(table_8_11), 1.851 / 0.379, step, 1.0162^99)
)
gt(checks, rowname_col = "item") |>
tab_header("Sections 8.7 and 8.9.2") |>
fmt_number(columns = c(book, prospicio), rows = 1, decimals = 2) |>
fmt_number(columns = c(book, prospicio), rows = c(2, 4), decimals = 3) |>
fmt_number(columns = book, rows = 3, decimals = 4) |>
fmt_number(columns = prospicio, rows = 3, decimals = 5)| Sections 8.7 and 8.9.2 | ||
| book | prospicio | |
|---|---|---|
| Cessna 172M relativity | 1.37 | 1.37 |
| range, largest over smallest | 4.884 | 4.884 |
| step | 1.0162 | 1.01615 |
| range from 99 printed steps | 4.908 | 4.908 |
The printed step 1.0162 is the exact 1.01615 rounded up, so 99 steps of it overshoot the range (4.908 against 4.884). Table 8.15 uses the rounded step:
groups <- c(1, 2, 3, 22, 56)
gt(data.frame(group = as.character(groups), book = c(0.379, 0.385, 0.391, 0.531, 0.917),
prospicio = 0.379 * 1.0162^(groups - 1)), rowname_col = "group") |>
tab_header("Table 8.15: relativities of selected area groups") |>
fmt_number(decimals = 3)| Table 8.15: relativities of selected area groups | ||
| book | prospicio | |
|---|---|---|
| 1 | 0.379 | 0.379 |
| 2 | 0.385 | 0.385 |
| 3 | 0.391 | 0.391 |
| 22 | 0.531 | 0.531 |
| 56 | 0.917 | 0.917 |
3. Learning from black-box models (chapter 9)
3.1 The boosting model’s variance
The monograph calls the gradient boosting benchmark a very complicated GLM. Its training score keeps rising with more trees, but its validation score stops rising (Figure 9.1). The chunk shows this on fold 0 of the portfolio:
fit_d <- pf[train & pf$fold != 0, ]
val_d <- pf[pf$fold == 0, ]
trees <- data.frame()
for (rounds in c(50, 150, 600)) {
b_fit <- gbm_fit(f_tree, fit_d, rounds)
gap_train <- pseudo_r2(fit_d$claims, predict(b_fit, fit_d), fit_d$exposure)
gap_val <- pseudo_r2(val_d$claims, predict(b_fit, val_d), val_d$exposure)
trees <- rbind(trees, data.frame(trees = as.character(rounds), train = gap_train, validation = gap_val))
}
gt(trees, rowname_col = "trees") |>
tab_header("Boosting on fold 0", "Pseudo-R2 by number of trees") |>
fmt_number(decimals = 3)| Boosting on fold 0 | ||
| Pseudo-R2 by number of trees | ||
| train | validation | |
|---|---|---|
| 50 | 0.044 | 0.042 |
| 150 | 0.067 | 0.052 |
| 600 | 0.109 | 0.051 |
3.2 Permutation feature importance
Section 9.2 measures a feature’s importance by how much worse the model predicts held-out data after you shuffle that feature’s column. The shuffle breaks the link to the outcome and needs only predictions, so it works for any model. Tables 9.1 to 9.4 use three insureds, frequency age / 100, a model that has learned exactly that, and the mean absolute error:
toy_age <- c(20, 30, 40)
toy_height <- c(1.4, 1.5, 1.6)
toy_freq <- toy_age / 100
toy_model <- function(a, h) a / 100
base_mae <- mean(abs(toy_model(toy_age, toy_height) - toy_freq))
mae_age <- mean(abs(toy_model(c(40, 20, 30), toy_height) - toy_freq))
mae_height <- mean(abs(toy_model(toy_age, c(1.6, 1.4, 1.5)) - toy_freq))
gains <- c(age = mae_age - base_mae, height = mae_height - base_mae)
for (name in names(gains)) {
cat(sprintf("%-6s increase in MAE %.3f, importance %.0f\n", name, gains[[name]],
100 * gains[[name]] / max(gains)))
}## age increase in MAE 0.133, importance 100
## height increase in MAE 0.000, importance 0
cat("printed: age 0.133 and 100, height 0 and 0\n")## printed: age 0.133 and 100, height 0 and 0
On the portfolio, “our GLM” is the monograph’s end point: the age
steps that the lasso kept, steps for vehicle age, region, power and the
make encoding (at K = 64), without noise or experience
features (part 1, sections 3.2 and 4.4). The boosting model gets the raw
features and the same make encoding, but not exper: this
near-copy of age would blur every comparison (the caveat of section 9.2
about correlated features).
As in section 9.5.1, each importance is the average over the seven
cross-validation models of the loss of pseudo-R2 on the held-out fold
when the feature is shuffled. permutation_importance()
takes a score to minimize, so the pseudo-R2 goes in with a negative
sign.
The make encoding changes with each held-out fold, so the
splits argument cannot fit the models here. The loop fits
both models on each fold, explains them on the held-out rows (the fold
number seeds the shuffle) and combines the seven results. It also runs
partial_dependence() on age and the pairwise
interaction_screen() for the next two sections:
veh_knots <- c(2, 4, 6, 8, 10)
features <- c("age", "veh_age", "region", "power", "log_te", "noise")
ages <- c(18, 21, 25, 40, 60, 75)
# The formula builds the step columns and the interaction from the frame's own columns, so
# predict() rebuilds them on whatever frame the helpers pass (shuffled, or with age set to one value).
glm_formula <- function(interaction = FALSE) {
reformulate(c(sprintf("I(as.numeric(age >= %d))", kept), sprintf("I(as.numeric(veh_age >= %d))", veh_knots),
"region", "power", "log_te", if (interaction) "I(as.numeric(age < 25 & power == 'high'))",
"offset(log(exposure))"), "claims")
}
f_gbm <- claims ~ age + veh_age + region_code + power_code + log_te + noise + offset(log(exposure))
frame <- function(mask, log_te) {
f <- pf[mask, c("age", "veh_age", "region", "power", "region_code", "power_code", "noise", "exposure",
"claims")]
f$log_te <- log_te[mask]
f
}
# Region and power are shuffled together with the trees' codes for them.
groups <- list(age = "age", veh_age = "veh_age", region = c("region", "region_code"),
power = c("power", "power_code"), log_te = "log_te", noise = "noise")
neg_r2 <- function(model, f) -pseudo_r2(f$claims, predict(model, f), f$exposure)
fit_model <- list(GLM = function(f) glm_fit(glm_formula(), f), GBM = function(f) gbm_fit(f_gbm, f))
imp_by <- list(GLM = list(), GBM = list())
pd_by <- list(GLM = list(), GBM = list())
screen_by <- list()
glm_with_interaction <- numeric()
for (k in 0:6) {
log_te_k <- make_feature(64, held_out = k)
fit_f <- frame(train & pf$fold != k, log_te_k)
val_f <- frame(pf$fold == k, log_te_k)
for (m in c("GLM", "GBM")) {
model <- fit_model[[m]](fit_f)
imp_by[[m]][[k + 1]] <- permutation_importance(model, val_f, neg_r2, groups, seed = k)
pd_by[[m]][[k + 1]] <- partial_dependence(model, val_f, "age", ages)$mean
if (m == "GBM") screen_by[[k + 1]] <- interaction_screen(model, val_f, neg_r2, groups, seed = k)
}
with_i <- glm_fit(glm_formula(TRUE), fit_f)
glm_with_interaction <- c(glm_with_interaction,
pseudo_r2(val_f$claims, predict(with_i, val_f), val_f$exposure))
}
score_full <- lapply(imp_by, function(v) -mean(vapply(v, attr, double(1), "base")))
mean_loss <- lapply(imp_by, function(v) {
setNames(rowMeans(sapply(v, function(imp) imp$importance)), v[[1]]$feature)
})
cat(sprintf("cv pseudo-R2: GLM %.3f, GBM %.3f\n", score_full$GLM, score_full$GBM))## cv pseudo-R2: GLM 0.055, GBM 0.048
ord <- features[order(-mean_loss$GLM[features])]
gt(data.frame(feature = ord, GLM = unname(unlist(mean_loss$GLM[ord])), GBM = unname(unlist(mean_loss$GBM[ord]))),
rowname_col = "feature") |>
tab_header("Permutation importance", "Loss of pseudo-R2 when the feature is shuffled") |>
fmt_number(decimals = 3)| Permutation importance | ||
| Loss of pseudo-R2 when the feature is shuffled | ||
| GLM | GBM | |
|---|---|---|
| log_te | 0.039 | 0.033 |
| age | 0.037 | 0.034 |
| power | 0.019 | 0.019 |
| veh_age | 0.011 | 0.009 |
| region | 0.008 | 0.003 |
| noise | 0.000 | 0.000 |
library(ggplot2, exclude = "layer")
imp_df <- data.frame(
feature = factor(rep(features, 2), levels = features[order(mean_loss$GLM[features])]),
model = rep(c("GLM", "GBM"), each = length(features)),
loss = c(unlist(mean_loss$GLM[features]), unlist(mean_loss$GBM[features]))
)
ggplot(imp_df, aes(loss, feature, fill = model)) +
geom_col(position = position_dodge(width = 0.8), width = 0.7) +
labs(x = "loss of pseudo-R2 when the feature is shuffled", y = NULL, fill = NULL,
title = "Permutation importance, mean over the seven held-out folds") +
theme(legend.position = "top")The two models agree on which features matter and roughly on their order. The GBM gives the noise feature almost no importance, although it can use it. With the monograph’s treatment of nonlinear effects and of make, our GLM now scores above this untuned boosting model (in section 1.3 of part 1 the raw-feature baseline GLM was far below it). The GLM loss for noise is exactly zero because the GLM does not use noise; the monograph’s GLM importances are never zero, because its lasso kept each feature in at least one fold.
3.3 Partial dependence
Section 9.3 isolates the effect of a feature in a black box: set the
feature to one value for every record, average the predictions, and
repeat for another value. For a GLM without interactions, the ratio of
the two averages is exactly the ratio of the feature’s relativities. The
printed nu_registered steps give 1.107 between 1 and 10;
Tables 9.7 to 9.9 give the same ratio from predictions, and the boosting
model of Table 9.10 gives 1.104:
nu <- function(v) -0.0001407 * v + 0.02936 * (v >= 2) + 0.07342 * (v >= 7) - 0.15822 * (v >= 16) -
0.17117 * (v >= 35)
gt(data.frame(ratio = c("GLM steps, 10 vs 1", "Table 9.9, ratio of totals", "Table 9.10, GBM"),
book = c(1.107, 1.107, 1.104),
prospicio = c(exp(nu(10) - nu(1)), 0.01225 / 0.01107, 0.005892 / 0.005336)),
rowname_col = "ratio") |>
tab_header("Partial dependence ratios of nu_registered") |>
fmt_number(decimals = 3)| Partial dependence ratios of nu_registered | ||
| book | prospicio | |
|---|---|---|
| GLM steps, 10 vs 1 | 1.107 | 1.107 |
| Table 9.9, ratio of totals | 1.107 | 1.107 |
| Table 9.10, GBM | 1.104 | 1.104 |
On the portfolio, the table gives each model’s partial dependence on driver age, relative to age 40 and averaged over the seven held-out folds, beside the truth for a low-power car. The true young-driver effect is larger for high power, which is the interaction:
true_age <- exp(0.9 * exp(-(ages - 18) / 6) + 0.0015 * pmax(ages - 60, 0)^1.5)
pd_mean <- lapply(pd_by, function(v) colMeans(do.call(rbind, v)))
gt(data.frame(age = as.character(ages), GLM = pd_mean$GLM / pd_mean$GLM[4], GBM = pd_mean$GBM / pd_mean$GBM[4],
`truth, low power` = true_age / true_age[4], check.names = FALSE), rowname_col = "age") |>
tab_header("Young-driver effect", "Partial dependence relative to age 40") |>
fmt_number(decimals = 2)| Young-driver effect | |||
| Partial dependence relative to age 40 | |||
| GLM | GBM | truth, low power | |
|---|---|---|---|
| 18 | 2.81 | 2.39 | 2.40 |
| 21 | 2.06 | 1.85 | 1.69 |
| 25 | 1.54 | 1.18 | 1.29 |
| 40 | 1.00 | 1.00 | 1.00 |
| 60 | 1.00 | 1.02 | 0.98 |
| 75 | 1.18 | 1.09 | 1.07 |
pd_df <- rbind(
data.frame(age = ages, rel = true_age / true_age[4], series = "truth, low power"),
data.frame(age = ages, rel = pd_mean$GLM / pd_mean$GLM[4], series = "GLM"),
data.frame(age = ages, rel = pd_mean$GBM / pd_mean$GBM[4], series = "GBM")
)
is_truth <- pd_df$series == "truth, low power"
ggplot(pd_df, aes(age, rel, colour = series)) +
geom_line(data = pd_df[is_truth, ], colour = "grey75", linewidth = 1.5) +
geom_line(data = pd_df[!is_truth, ]) +
geom_point(data = pd_df[!is_truth, ]) +
labs(x = "driver age (years)", y = "partial dependence relative to age 40", colour = NULL,
title = "Young-driver effect: the GLM overstates it without the interaction") +
theme(legend.position = "top")A partial dependence is an average over the portfolio (section 9.3), so both models’ young-driver figures mix high-power cars with the other cars. The GLM figure is higher: without an interaction term it charges every young driver part of the extra load of high-power cars. The next section finds that interaction.
3.4 Interactions from permutations
The interaction screen of section 9.4 shuffles two features
separately and together. With losses L_A, L_B
and L_AB, the sum L_A + L_B - L_AB is zero if
neither feature interacts with anything, and positive if the two
interact with each other or with a common third feature. Table 9.11
prints the three losses for three pairs with aircraft age (from the
values, its columns are L_AB, L_A and
L_B):
table_9_11 <- data.frame(name = c("region", "nu_registered", "faa_eng_hp_char"),
l_ab = c(0.291, 0.115, 0.123), l_a = c(0.253, 0.016, 0.002),
l_b = c(0.135, 0.135, 0.135), printed = c("0.096", "0.037", "0.014"))
gt(data.frame(pair = paste(table_9_11$name, "x aircraft age"), L_AB = table_9_11$l_ab, L_A = table_9_11$l_a,
L_B = table_9_11$l_b, prospicio = table_9_11$l_a + table_9_11$l_b - table_9_11$l_ab,
book = as.numeric(table_9_11$printed)), rowname_col = "pair") |>
tab_header("Table 9.11: interaction with aircraft age") |>
fmt_number(decimals = 3)| Table 9.11: interaction with aircraft age | |||||
| L_AB | L_A | L_B | prospicio | book | |
|---|---|---|---|---|---|
| region x aircraft age | 0.291 | 0.253 | 0.135 | 0.097 | 0.096 |
| nu_registered x aircraft age | 0.115 | 0.016 | 0.135 | 0.036 | 0.037 |
| faa_eng_hp_char x aircraft age | 0.123 | 0.002 | 0.135 | 0.014 | 0.014 |
Our sums differ from the printed values by 0.001, because the three inputs are rounded. The same screen on the boosting model, over each pair of portfolio features and averaged over the seven folds:
screen <- screen_by[[1]][c("a", "b")]
screen$strength <- rowMeans(sapply(screen_by, function(s) s$strength))
screen <- screen[order(-screen$strength), ]
top <- data.frame(pair = paste(screen$a, "x", screen$b), strength = screen$strength)[1:6, ]
gt(top, rowname_col = "pair") |>
tab_header("Interaction screen of the boosting model",
"Strength of each pair of features, mean over seven folds (pseudo-R2 units)") |>
fmt_number(columns = strength, decimals = 4)| Interaction screen of the boosting model | |
| Strength of each pair of features, mean over seven folds (pseudo-R2 units) | |
| strength | |
|---|---|
| age x power | 0.0051 |
| age x log_te | 0.0012 |
| veh_age x noise | 0.0006 |
| veh_age x region | 0.0005 |
| region x power | 0.0003 |
| region x noise | 0.0000 |
Age and power come first, which is the planted interaction. The next pairs have a quarter of its strength or less, and their order changes with the shuffle (the third pair includes the noise feature, which interacts with nothing). One more column for the first pair raises the cross-validated GLM score:
cat(sprintf("GLM cv pseudo-R2 %.3f, with a young-driver high-power term %.3f\n",
score_full$GLM, mean(glm_with_interaction)))## GLM cv pseudo-R2 0.055, with a young-driver high-power term 0.058
In the monograph, the leaves of a decision tree fitted to the ratio
of boosting to GLM predictions did this work (cross-validated pseudo-R2
from 0.151 to 0.156). A booster_fit() with one tree and a
few leaves is a decision tree, and the hand-made column above uses the
same idea.
3.5 The test data, once
All decisions above used only the training folds. By the rule of section 3.2, the test data is looked at once, at the end. The chunk fits each model again on all seven training folds, with the make encoding from all of them, and scores each on folds 7 to 9:
log_te_all <- make_feature(64)
fit_all <- frame(train, log_te_all)
test_all <- frame(!train, log_te_all)
final <- list(
"baseline GLM" = predict(glm_fit(f_base, pf[train, ]), pf[!train, ]),
"our GLM" = predict(glm_fit(glm_formula(), fit_all), test_all),
"our GLM + interaction" = predict(glm_fit(glm_formula(TRUE), fit_all), test_all),
"GBM" = predict(gbm_fit(f_gbm, fit_all), test_all),
"truth" = truth[!train]
)
for (name in names(final)) {
cat(sprintf("%-22s %.3f\n", name, pseudo_r2(test_all$claims, final[[name]], test_all$exposure)))
}## baseline GLM 0.025
## our GLM 0.068
## our GLM + interaction 0.071
## GBM 0.064
## truth 0.089
Cross-validation predicted this ranking. The last digit of the boosting model can change with the LightGBM version and platform; the last digits of the GLMs cannot.
4. Challenges in ratemaking models (chapter 10)
The last chapter lists ways that a good cross-validation score can still mislead:
- data with a misunderstood meaning (the monograph’s aircraft age was the years since the registration certificate, not since manufacture),
- technical errors, such as factor levels coded differently in
training and production (a fitted model keeps its factor levels, and
predict()builds the design with them), - data that breaks the assumptions of the model,
- coefficients and business mix that drift over time,
- regulation,
- outliers and data quality.
Cross-validation fails when the future differs from the folds, so
monitor the model in production. actual_vs_expected()
compares actual and expected claims by period, with a z-score for each
period and a test for a trend in the ratio (section 10.4).