Skip to contents

Rendered from docs/guides/glm-to-comprehensive-pricing-chalk.qmd. The code runs each time the site is built, so the output below is current.

CAS Monograph 16 is From GLMs to Comprehensive Insurance Pricing: Techniques and Challenges (Alan Chalk, David Deacon, Montserrat Guillen and Max Martinelli, 2025). It starts where the GLM monograph of Goldburd and others stops and asks what a pricing team does next. This guide covers chapters 3 to 6: measuring a model on unseen data, penalized regression, step and hinge functions, and factors with thousands of levels. The second part, glm-to-comprehensive-pricing-chalk-2.qmd, covers chapters 7 to 10. Table and section numbers are the monograph’s.

This is the R twin of the Python guide glm-to-comprehensive-pricing-chalk.md: the same sections, data and numbers, with the R package (glm_fit(), elastic_net_fit(), elastic_net_cv(), gam_fit(), booster_fit(), family_deviance()). Its boosting adapter calls the same LightGBM (4.7.0, through the lightgbm package) with the same parameters.

What this guide reproduces. The monograph’s case studies use data that is not available offline (the FAA aircraft registry joined to NTSB accident records, UK road accident counts, and a simulated auto portfolio whose rows are not published), so this guide does not recompute their coefficients or plots. It reproduces every worked example whose inputs the monograph prints, each with the monograph’s value beside prospicio’s. To show the methods on data, it simulates a motor portfolio with a known ground truth, as section 2.3 of the monograph does. Models are compared by ranking and by pseudo-R2 rounded to three decimals, because gradient boosting libraries change the later digits between versions and platforms.

The data. The Python guide draws the portfolio with the numpy generator (seed 2025), which R cannot replay. This guide reads the same draws from examples/data/chalk_portfolio.csv and examples/data/chalk_toys.csv, which examples/data/make_chalk_portfolio.py writes with the Python guide’s code, so every number below equals the Python guide’s.

CI runs every R chunk that has a text block after it (R/prospicio/tests/test-guides.R) and requires the chunk to print exactly that text, which is also the Python guide’s. To render the page, install the R package and lightgbm, then run quarto render docs/guides/glm-to-comprehensive-pricing-chalk.qmd.

1. Measuring performance (chapter 3)

1.1 Pseudo-R2

The monograph scores every model by the share of the possible improvement in log-likelihood that it achieves, from the null model (the mean for everyone) to the saturated model (each record at its own outcome). Deviance is twice the gap to the saturated model, so this share is 1 - D_model / D_null, the deviance explained. Table 3.1 has four records, two claims and predictions 0.2 to 0.8:

library(prospicio)
library(gt)

y <- c(0, 0, 1, 1)
mu <- c(0.2, 0.4, 0.6, 0.8)
null <- rep(mean(y), length(y))

# Poisson log-likelihood without the log(y!) constant, as in section 3.1.
loglik <- function(y, mu) sum(y * log(mu) - mu)

ll_model <- loglik(y, mu)
ll_null <- loglik(y, null)
ll_sat <- sum((y * log(y) - y)[y > 0])
d_model <- family_deviance("poisson", y, mu)
d_null <- family_deviance("poisson", y, null)
check <- data.frame(
  measure = c("log-likelihood, model", "log-likelihood, null", "log-likelihood, saturated",
              "pseudo-R2 from log-likelihoods", "pseudo-R2 from deviances"),
  prospicio = c(ll_model, ll_null, ll_sat, (ll_model - ll_null) / (ll_sat - ll_null),
                1 - d_model / d_null),
  book = c("-2.734", "-3.386", "-2", "47%", "47%"))
gt(check, rowname_col = "measure") |>
  tab_header("Table 3.1: pseudo-R2 of four records", "Poisson log-likelihood without the log(y!) constant") |>
  fmt_number(columns = prospicio, decimals = 3)
Table 3.1: pseudo-R2 of four records
Poisson log-likelihood without the log(y!) constant
prospicio book
log-likelihood, model −2.734 -2.734
log-likelihood, null −3.386 -3.386
log-likelihood, saturated −2.000 -2
pseudo-R2 from log-likelihoods 0.471 47%
pseudo-R2 from deviances 0.471 47%

family_deviance() also takes prior weights, for the exposure-weighted version of section 3.7.2. It multiplies each record’s deviance by its exposure, in the model and null deviance.

Two more checks are arithmetic on printed values (Table 3.6 and the rebasing factor of section 3.7.4):

data.frame(
  quantity = c("Table 3.6, linear predictor", "Table 3.6, frequency", "Section 3.7.4, rebasing factor"),
  prospicio = c(-2.447 + 0.410 + 5 * -0.086, exp(-2.467), 0.004593 / 0.004579),
  book = c("-2.467", "0.085", "1.0031")) |>
  gt(rowname_col = "quantity") |>
  tab_header("Arithmetic on printed values") |>
  fmt_number(columns = prospicio, rows = 1:2, decimals = 3) |>
  fmt_number(columns = prospicio, rows = 3, decimals = 4)
Arithmetic on printed values
prospicio book
Table 3.6, linear predictor −2.467 -2.467
Table 3.6, frequency 0.085 0.085
Section 3.7.4, rebasing factor 1.0031 1.0031

1.2 A portfolio with a known truth, and folds from the policy number

The simulated portfolio takes the place of the monograph’s case studies: 20,000 policies with driver age, vehicle age, region, power, a 300-level make, a noise feature and a young-driver, high-power interaction. The true log frequency has a steep young-driver effect and a rise after age 60, a vehicle-age effect that falls until age 6 and is flat after, region and power effects, a make effect for each of 300 makes (make sizes fall like a Zipf law) and an extra load for young drivers of high-power cars.

noise has no effect. exper (years since the driving test) is highly correlated with age and has no effect of its own. The chunk below rebuilds the true log frequency from the data files with the Python guide’s formula.

Section 3.7.3 recommends folds from the policy number, so that anyone can rebuild them and all records of one policy fall in one fold. Here the fold is the last digit of the row number counted from 0. Folds 7 to 9 (30%) are the test data; folds 0 to 6 are the seven cross-validation folds.

# 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
cat(sprintf("%d policies, %.0f car-years, %.0f claims\n", n, sum(pf$exposure), sum(pf$claims)))
## 20000 policies, 15000 car-years, 3659 claims
cat(sprintf("frequency %.4f; makes with under 20 policies: %d\n", sum(pf$claims) / sum(pf$exposure),
            sum(tabulate(pf$make + 1, 300) < 20)))
## frequency 0.2439; makes with under 20 policies: 166
cat(sprintf("correlation of age and exper %.3f\n", cor(pf$age, pf$exper)))
## correlation of age and exper 0.997

The null model is the mean frequency times each record’s exposure. cv_score() trains on six of the seven folds, scores the seventh and averages, for any function that fits and predicts (a GLM, a GAM or a boosting model).

pseudo_r2 <- function(y, mu, expo) {
  null <- expo * sum(y) / sum(expo)
  1 - family_deviance("poisson", y, mu) / family_deviance("poisson", y, null)
}

cv_score <- function(fit_predict, formula, folds = 0:6) {
  scores <- vapply(folds, function(k) {
    val <- pf[pf$fold == k, ]
    pseudo_r2(val$claims, fit_predict(formula, pf[train & pf$fold != k, ], val), val$exposure)
  }, double(1))
  list(mean = mean(scores), folds = scores)
}

# Python's list of formatted numbers: ['0.100', '0.200'].
py_list <- function(x, digits) {
  paste0("[", paste0("'", sprintf(paste0("%.", digits, "f"), x), "'", collapse = ", "), "]")
}

truth <- exp(true_lp) * pf$exposure
cat(sprintf("pseudo-R2 of the true frequencies on the test data %.3f\n",
            pseudo_r2(pf$claims[!train], truth[!train], pf$exposure[!train])))
## pseudo-R2 of the true frequencies on the test data 0.089

A perfect model explains only a few percent of the deviance of individual claim counts, because most of each count is chance (section 3.7.1; the monograph’s perfect model scored 0.051), so compare models on the same data.

1.3 Null, baseline and benchmark models

The null model predicts the training mean. Its validation pseudo-R2 is slightly negative, not zero, because the training mean is not the validation fold’s mean (Table 3.3). Rebasing to the fold’s mean (section 3.7.4) makes it exactly zero.

The baseline is a Poisson GLM with age and vehicle age as straight lines and region and power as factors (section 3.5). The benchmark is LightGBM through booster_fit() (section 3.6), with the make as a plain number so the trees can split on it. The trees see region and power as the codes 0, 1, 2, … of their levels in alphabetical order, in the Python guide’s column order, so LightGBM gets the same matrix.

pf$region_code <- as.integer(pf$region) - 1
pf$power_code <- match(as.character(pf$power), c("high", "low", "mid")) - 1
f_null <- claims ~ 1 + offset(log(exposure))
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)

glm_fp <- function(formula, d, new) predict(glm_fit(formula, d), new)

gbm_fp <- function(formula, d, new, rounds = 150) {
  predict(booster_fit(formula, d, n_rounds = rounds, learning_rate = 0.05, params = gbm_params,
                      seed = 1), new)
}

null_cv <- cv_score(glm_fp, f_null)
cat("null model by fold     ", py_list(null_cv$folds, 4), "\n")
## null model by fold      ['-0.0000', '-0.0000', '-0.0031', '-0.0000', '-0.0009', '-0.0012', '-0.0028']
val <- pf[pf$fold == 0, ]
mu0 <- glm_fp(f_null, pf[train & pf$fold != 0, ], val)
rebased <- mu0 * sum(val$claims) / sum(mu0)
cat(sprintf("fold 0 rebased          %.4f\n", abs(pseudo_r2(val$claims, rebased, val$exposure))))
## fold 0 rebased          0.0000
cat(sprintf("baseline GLM  cv        %.3f\n", cv_score(glm_fp, f_base)$mean))
## baseline GLM  cv        0.021
cat(sprintf("benchmark GBM cv        %.3f\n", cv_score(gbm_fp, f_tree)$mean))
## benchmark GBM cv        0.045

The order is the monograph’s: null, GLM, boosting model well above the GLM. The rest of the monograph closes that gap with models that a pricing team can explain.

2. Penalized regression (chapter 4)

2.1 Why fewer parameters can predict better

In the rare-car example of section 4.1, ten insurers each see one of ten cars for a year, and one car has a claim. An unpenalized GLM at each insurer predicts 100% or 0%: right on average (10%), far off each time. The spread of the ten predictions is the variance of the model. This is the population variance (divide by 10), as in the monograph.

preds <- c(1, rep(0, 9))
pop_var <- mean((preds - mean(preds))^2)
cat(sprintf("mean %.2f, variance %.2f, sd %.2f (printed 0.09, 0.30)\n",
            mean(preds), pop_var, sqrt(pop_var)))
## mean 0.10, variance 0.09, sd 0.30 (printed 0.09, 0.30)

A model that ignores this car and predicts the 5% average for every make has bias but no variance, and every insurer is closer to the truth with it. Penalized regression trades bias for variance continuously, by maximizing the log-likelihood less a penalty on the coefficients:

  • ridge: the sum of their squares,
  • lasso: the sum of their absolute values,
  • elastic net: a mix of the two, with weight alpha on the lasso part.

elastic_net_fit() minimizes the glmnet objective: half the mean deviance plus lambda times the penalty. The intercept is not penalized and the columns are standardized first. Its lambda and alpha are the monograph’s lambda and alpha (section 4.6.3).

2.2 Ridge in closed form, and why features are standardized

For one feature, a normal response and no intercept, ridge divides the mean of x * y by the mean of x^2 plus lambda (section 4.7.1), which pulls the least squares estimate towards zero. In section 4.7.2 the means are 10 and 5 with length in metres, and lambda = 5. In centimetres they are 100 and 10,000 times larger, so the same lambda shrinks almost nothing:

units <- data.frame(unit = c("metres", "centimetres"), xy = c(10, 1000), xx = c(5, 50000),
                    scale = c(1, 100))
ridge_b <- units$xy / (units$xx + 5)
data.frame(unit = units$unit, `least squares` = units$xy / units$xx, ridge = ridge_b,
           `frequency at 1 m` = ridge_b * units$scale, check.names = FALSE) |>
  gt(rowname_col = "unit") |>
  tab_header("Section 4.7.2: ridge on one length in two units", "lambda = 5") |>
  fmt_number(columns = `least squares`, decimals = 4) |>
  fmt_number(columns = ridge, decimals = 6) |>
  fmt_number(columns = `frequency at 1 m`, decimals = 4)
Section 4.7.2: ridge on one length in two units
lambda = 5
least squares ridge frequency at 1 m
metres 2.0000 1.000000 1.0000
centimetres 0.0200 0.019998 1.9998

The monograph prints 0.019 and 1.9 for centimetres: it truncated the exact values. The units, not the data, set the effect of the penalty.

Standardizing each feature to unit standard deviation before the penalty removes this. elastic_net_fit() does it by default and returns coefficients on the original scale, so ridge on metres and on centimetres differ by exactly the factor of 100. The 200 lengths are the Python guide’s draws, from chalk_toys.csv:

len <- toys[toys$example == "metres", ]
b_m <- coef(elastic_net_fit(y ~ x, len, family = "gaussian", alpha = 0, lambda = 0.5))[[2]]
b_cm <- coef(elastic_net_fit(y ~ I(100 * x), len, family = "gaussian", alpha = 0, lambda = 0.5))[[2]]
cat(sprintf("metres %.6f, centimetres x 100 %.6f\n", b_m, 100 * b_cm))
## metres 1.343762, centimetres x 100 1.343762

2.3 The lasso sets coefficients to exactly zero

Section 4.7.3: for one standardized feature, the lasso estimate is the least squares estimate moved towards zero by lambda, and exactly zero beyond it (soft-thresholding). With this objective the least squares estimate is the mean of x * y:

soft <- toys[toys$example == "soft", ]
ols <- mean(soft$x * soft$y)
soft_rows <- do.call(rbind, lapply(c(0, 0.1, 0.2, 0.4), function(lam) {
  b <- coef(elastic_net_fit(y ~ x, soft, family = "gaussian", alpha = 1, lambda = lam))[[2]]
  data.frame(lam = sprintf("%.1f", lam), lasso = b,
             `soft threshold` = sign(ols) * max(abs(ols) - lam, 0), check.names = FALSE)
}))
gt(soft_rows, rowname_col = "lam") |>
  tab_header("Section 4.7.3: the lasso is the soft threshold", "One standardized feature") |>
  fmt_number(columns = c(lasso, `soft threshold`), decimals = 4)
Section 4.7.3: the lasso is the soft threshold
One standardized feature
lasso soft threshold
0.0 0.3382 0.3382
0.1 0.2382 0.2382
0.2 0.1382 0.1382
0.4 0.0000 0.0000

2.4 Paths and choosing the penalty by cross-validation

Tables 4.1 and 4.2 show the coefficient of log aircraft age shrinking as the penalty grows: smoothly for ridge, to zero for the lasso. The chunk repeats this with log driver age. For a Poisson model, records with equal features can be summed (section 8.3), so the age-only models use 63 ages times 10 folds.

elastic_net_fit() with lambda = NULL gives the default glmnet path. The first lambda of this path is the smallest that sets every coefficient to zero:

cells <- aggregate(cbind(claims, exposure) ~ age + fold, pf, sum)
cells <- cells[order(cells$age * 10 + cells$fold), ]
cells$log_age <- log(cells$age)
cells_tr <- cells[cells$fold < 7, ]
f_logage <- claims ~ log_age + offset(log(exposure))
top <- elastic_net_fit(f_logage, cells_tr, alpha = 1)@lambda[1]
paths <- sapply(c(ridge = 0, lasso = 1), function(a) {
  scale <- if (a == 0) 100 else 1
  lams <- scale * top * c(1, 0.3, 0.1, 0.03, 0.01, 0)
  as.numeric(elastic_net_fit(f_logage, cells_tr, alpha = a, lambda = lams)@coefficients["log_age", ])
})
data.frame(penalty = c("1", "0.3", "0.1", "0.03", "0.01", "0 (GLM)"),
           ridge = paths[, "ridge"], lasso = paths[, "lasso"]) |>
  gt(rowname_col = "penalty") |>
  tab_header("Tables 4.1 and 4.2: the log-age coefficient along the path",
             "Penalty as a share of the largest one; ridge starts at 100 times the lasso's") |>
  fmt_number(columns = c(ridge, lasso), decimals = 3)
Tables 4.1 and 4.2: the log-age coefficient along the path
Penalty as a share of the largest one; ridge starts at 100 times the lasso's
ridge lasso
1 −0.023 0.000
0.3 −0.067 −0.292
0.1 −0.153 −0.373
0.03 −0.275 −0.401
0.01 −0.354 −0.409
0 (GLM) −0.413 −0.413

Section 4.3 chooses lambda by fitting the path on six folds and scoring the seventh. elastic_net_cv() (as cv.glmnet() in glmnet) with foldid the policy-number folds does this. It returns the lambda with the best mean validation deviance and, for the one-standard-error rule of section 4.6.5, the largest lambda within one standard error of it (positions on the path start at 0, as in the Python guide):

lams <- elastic_net_fit(f_logage, cells_tr, alpha = 0.99, nlambda = 30, lambda_min_ratio = 1e-3)@lambda
path_cv <- elastic_net_cv(f_logage, cells_tr, alpha = 0.99, lambda = lams, foldid = cells_tr$fold + 1)
cat(sprintf("lam_min at position %d of 30, lam_1se at position %d\n",
            which(lams == path_cv$lambda_min) - 1, which(lams == path_cv$lambda_1se) - 1))
## lam_min at position 29 of 30, lam_1se at position 3

2.5 The relaxed lasso

The relaxed lasso (section 4.5) separates selection from shrinkage: it refits the features that the lasso selected with less penalty or none. In prospicio that is a glm_fit() on the selected columns (section 3.2).

3. Nonlinear effects (chapter 5)

3.1 Step and hinge functions, from the printed coefficients

A step function is 1 at or above a threshold and 0 below it. A hinge is max(0, x - knot). A single step at age 30 gives log frequency = -5.2815 - 1.4689 x step_30 (section 5.2). With steps at 5, 15 and 30 the monograph prints four frequencies:

steps <- data.frame(
  quantity = c("one step, frequency", "one step, relativity", paste0("three steps, band ", 1:4)),
  prospicio = c(exp(-5.2815), exp(-1.4689), exp(cumsum(c(-4.8292, -0.6881, -0.5711, -0.6237)))),
  book = c(0.00509, 0.2302, 0.00783, 0.00394, 0.00222, 0.00119))
steps[["book / prospicio"]] <- steps$book / steps$prospicio
gt(steps, rowname_col = "quantity") |>
  tab_header("Section 5.2: frequencies from the printed coefficients", "Bands are cut at ages 5, 15 and 30") |>
  fmt_number(columns = c(prospicio, book), rows = c(1, 3:6), decimals = 5) |>
  fmt_number(columns = c(prospicio, book), rows = 2, decimals = 4) |>
  fmt_number(columns = `book / prospicio`, decimals = 3)
Section 5.2: frequencies from the printed coefficients
Bands are cut at ages 5, 15 and 30
prospicio book book / prospicio
one step, frequency 0.00508 0.00509 1.001
one step, relativity 0.2302 0.2302 1.000
three steps, band 1 0.00799 0.00783 0.980
three steps, band 2 0.00402 0.00394 0.981
three steps, band 3 0.00227 0.00222 0.978
three steps, band 4 0.00122 0.00119 0.979

The single step’s base frequency differs in the last digit: exp(-5.2815) is 0.005082 (an intercept of -5.2809 or more gives the printed 0.00509).

The three-step frequencies are all about 2% below the printed ones, by almost the same factor in every band, which points at the intercept: -4.85, not -4.8292, gives the printed values and keeps the ratios between bands. Without the data we cannot say which printed number is wrong.

Table 5.7 codes an ordinal feature (pilot quality, five levels) as five cumulative steps. A level’s relativity is the exponential of the running sum of the coefficients:

coef_57 <- c(0, 0.515, 0, 0.211, 0.206)
data.frame(level = as.character(1:5), coefficient = coef_57, prospicio = exp(cumsum(coef_57)),
           book = c("1", "1.673", "1.673", "2.06", "2.539")) |>
  gt(rowname_col = "level") |>
  tab_header("Table 5.7: cumulative relativities of pilot quality") |>
  fmt_number(columns = c(coefficient, prospicio), decimals = 3)
Table 5.7: cumulative relativities of pilot quality
coefficient prospicio book
1 0.000 1.000 1
2 0.515 1.674 1.673
3 0.000 1.674 1.673
4 0.211 2.067 2.06
5 0.206 2.540 2.539

The exact fourth value is 2.067: Table 5.7 truncates it and Table 5.8 rounds it to 2.07.

3.2 Many steps or hinges, and the lasso picks

Section 5.2 gives the lasso one step at each age and lets cross-validation decide how many stay (section 5.6 uses 25 equally spaced steps). Here the steps are every three years from 20 to 77, on the aggregated ages:

knots <- seq(20, 77, by = 3)
step_names <- paste0("age_stp_", knots)
add_steps <- function(d, at) {
  for (a in at) d[[paste0("age_stp_", a)]] <- as.numeric(d$age >= a)
  d
}
cells <- add_steps(cells, knots)
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)
i_min <- which(lams == cvp$lambda_min)
i_1se <- which(lams == cvp$lambda_1se)
kept <- knots[cvp$fit@coefficients[step_names, i_min] != 0]
cat(sprintf("%d steps offered, %d kept at lam_min, %d at lam_1se\n",
            length(knots), cvp$fit@df[i_min], cvp$fit@df[i_1se]))
## 20 steps offered, 8 kept at lam_min, 5 at lam_1se
cat("kept:", paste0("[", paste(kept, collapse = ", "), "]"), "\n")
## kept: [20, 23, 26, 29, 32, 62, 65, 77]

The cross-validation curve, with the two chosen penalties marked:

library(ggplot2, exclude = "layer")   # keeps prospicio's layer()
cv_curve <- data.frame(loglam = log10(lams), mean = cvp$mean, se = cvp$se)
marks <- data.frame(
  loglam = log10(c(cvp$lambda_min, cvp$lambda_1se)),
  choice = c(sprintf("lam_min (%d steps)", cvp$fit@df[i_min]),
             sprintf("lam_1se (%d steps)", cvp$fit@df[i_1se])))
marks$choice <- factor(marks$choice, levels = marks$choice)
ggplot(cv_curve, aes(loglam, mean)) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), colour = "grey75", width = 0.04) +
  geom_line(colour = "grey75") +
  geom_vline(aes(xintercept = loglam, colour = choice, linetype = choice), data = marks) +
  labs(x = "log10 of the penalty lambda", y = "deviance on the validation fold",
       colour = NULL, linetype = NULL,
       title = "Cross-validation of the lasso on 20 age steps") +
  theme(legend.position = "top")
1.11.21.31.41.51.6-2-10log10 of the penalty lambdadeviance on the validation foldlam_min (8 steps)lam_1se (5 steps)Cross-validation of the lasso on 20 age steps

The next chunk compares three fits with the truth by age (the exposure-weighted average of the policies’ true frequencies): the lasso at lambda_min, the relaxed lasso (the kept steps refitted by an unpenalized glm_fit(), section 4.5) and a P-spline GAM (gam_fit(), which the monograph uses for its spatial second stage in chapter 8):

grid <- add_steps(data.frame(age = 18:80, exposure = 1), knots)
true_by_age <- tapply(truth, pf$age, sum) / tapply(pf$exposure, pf$age, sum)
lasso_curve <- predict(cvp$fit, grid, lambda = cvp$lambda_min)
f_kept <- reformulate(c(paste0("age_stp_", kept), "offset(log(exposure))"), "claims")
relaxed_curve <- predict(glm_fit(f_kept, cells_tr), grid)
gam_age <- gam_fit(claims ~ age + offset(log(exposure)), cells_tr, smooths = "age", n_basis = 12)
gam_curve <- predict(gam_age, grid)
show_ages <- c(18, 20, 23, 26, 35, 50, 65, 80)
data.frame(age = as.character(show_ages), truth = as.numeric(true_by_age)[show_ages - 17],
           lasso = as.numeric(lasso_curve)[show_ages - 17], relaxed = as.numeric(relaxed_curve)[show_ages - 17],
           GAM = as.numeric(gam_curve)[show_ages - 17]) |>
  gt(rowname_col = "age") |>
  tab_header("Claim frequency by age: truth and three fits", "Claims per policy year") |>
  fmt_number(columns = c(truth, lasso, relaxed, GAM), decimals = 3)
Claim frequency by age: truth and three fits
Claims per policy year
truth lasso relaxed GAM
18 0.565 0.531 0.553 0.530
20 0.481 0.408 0.415 0.449
23 0.363 0.304 0.310 0.355
26 0.264 0.256 0.260 0.290
35 0.216 0.207 0.200 0.206
50 0.207 0.207 0.200 0.195
65 0.215 0.236 0.239 0.228
80 0.256 0.239 0.253 0.249
cat(sprintf("GAM effective degrees of freedom %.1f\n", gam_age@edf))
## GAM effective degrees of freedom 5.7
curves <- rbind(
  data.frame(age = grid$age, frequency = as.numeric(true_by_age), fit = "truth"),
  data.frame(age = grid$age, frequency = as.numeric(lasso_curve), fit = "lasso at lam_min"),
  data.frame(age = grid$age, frequency = as.numeric(relaxed_curve), fit = "relaxed lasso"),
  data.frame(age = grid$age, frequency = as.numeric(gam_curve), fit = "GAM"))
curves$fit <- factor(curves$fit, levels = c("truth", "lasso at lam_min", "relaxed lasso", "GAM"))
ggplot(curves, aes(age, frequency)) +
  geom_line(aes(colour = fit, linewidth = fit == "truth")) +
  scale_colour_manual(values = c("truth" = "grey75", "lasso at lam_min" = "#F8766D",
                                 "relaxed lasso" = "#00BA38", "GAM" = "#619CFF")) +
  scale_linewidth_manual(values = c("TRUE" = 1.6, "FALSE" = 0.6), guide = "none") +
  labs(x = "driver age (years)", y = "claims per policy year", colour = NULL,
       title = "Claim frequency by age: truth and three fits") +
  theme(legend.position = "top")
0.20.30.40.520406080driver age (years)claims per policy yeartruthlasso at lam_minrelaxed lassoGAMClaim frequency by age: truth and three fits

All three fits find the young-driver slope and the rise after 60 without being told where they are. Lasso shrinkage pulls the extremes towards the middle (as section 5.2 sees above aircraft age 20), and the relaxed fit removes part of that. The monograph prefers steps and hinges because the result is a short rating table. A GAM gives a smooth curve, which you tabulate afterwards.

Section 5.8.1 links steps to the fused lasso. A step at each level is the same model as a dummy at each level, and each step coefficient is the difference between neighbouring dummies. So a lasso penalty on steps penalizes the jumps between neighbours.

3.3 Monotone effects

Section 5.7.2 makes an ordinal effect monotone with non-negative step coefficients. A GAM can set the shape directly: bs = "mpd" is a monotone decreasing P-spline (from scam). The chunk fits it to vehicle age, whose true effect falls until age 6 and is flat after:

veh <- aggregate(cbind(claims, exposure) ~ veh_age + fold, pf, sum)
mono <- gam_fit(claims ~ veh_age + offset(log(exposure)), veh[veh$fold < 7, ], smooths = "veh_age",
                n_basis = 8, bs = "mpd")
curve <- predict(mono, data.frame(veh_age = 0:20, exposure = 1))
show <- c(0, 2, 4, 6, 10, 15, 20)
data.frame(`vehicle age` = as.character(show), fitted = (curve / curve[1])[show + 1],
           true = exp(-0.08 * pmin(show, 6)), check.names = FALSE) |>
  gt(rowname_col = "vehicle age") |>
  tab_header("Relativity of claim frequency to vehicle age 0", "Monotone P-spline against the true effect") |>
  fmt_number(columns = c(fitted, true), decimals = 2)
Relativity of claim frequency to vehicle age 0
Monotone P-spline against the true effect
fitted true
0 1.00 1.00
2 0.89 0.85
4 0.80 0.73
6 0.75 0.62
10 0.70 0.62
15 0.64 0.62
20 0.61 0.62

The monotone fit bends more gradually than the true hinge and keeps falling a little after age 6, but it cannot turn back up. A constraint hides a reversal if the data has one, so use it where the shape is known (claim history, deductibles), not to make a factor look tidy.

4. High cardinality categorical variables (chapter 6)

4.1 Target encoding, and keeping it out of its own fold

A factor with thousands of levels (aircraft make, city, zip code) is a problem as dummies in a GLM: it uses much memory and gives unstable estimates for thin levels. Target encoding, the main tool of chapter 6, replaces each level by one number, its actual-to-expected ratio shrunk towards 1 by the credibility factor z = n / (n + K), where n is the level’s exposure. The log of that number is the feature.

Encoding a level from its own records leaks the target into the feature (section 6.3), so a record in fold k is encoded only from the other folds. Table 6.1 has one make with six aircraft in three folds:

te_fold <- c(1, 1, 2, 2, 3, 3)
te_acc <- c(0, 0, 0, 1, 1, 1)
data.frame(fold = as.character(1:3),
           `accidents elsewhere` = sapply(1:3, function(k) sum(te_acc[te_fold != k])),
           `aircraft elsewhere` = sapply(1:3, function(k) sum(te_fold != k)),
           encoding = sapply(1:3, function(k) mean(te_acc[te_fold != k])),
           book = c(0.75, 0.50, 0.25), check.names = FALSE) |>
  gt(rowname_col = "fold") |>
  tab_header("Table 6.1: each fold encoded from the other folds") |>
  fmt_integer(columns = c(`accidents elsewhere`, `aircraft elsewhere`)) |>
  fmt_number(columns = c(encoding, book), decimals = 2)
Table 6.1: each fold encoded from the other folds
accidents elsewhere aircraft elsewhere encoding book
1 3 4 0.75 0.75
2 2 4 0.50 0.50
3 1 4 0.25 0.25

4.2 The credibility constant, and the printed encodings

Section 6.6 estimates K as the ratio of the within-make variance (an aircraft-year’s accident count, Bernoulli at the mean rate 0.004584) to the between-make variance, which the monograph estimates from the mean residuals of large makes as 7.038492e-6:

p <- 0.004584
within <- p * (1 - p)
K_est <- within / 7.038492e-6
data.frame(
  quantity = c("within variance", "K", "credibility at 1,000 aircraft-years"),
  prospicio = c(within, K_est, 1000 / (1000 + 648)),
  book = c("0.004562987", "648", "0.61")) |>
  gt(rowname_col = "quantity") |>
  tab_header("Section 6.6: the credibility constant") |>
  fmt_number(columns = prospicio, rows = 1, decimals = 9) |>
  fmt_number(columns = prospicio, rows = 2, decimals = 0) |>
  fmt_number(columns = prospicio, rows = 3, decimals = 2)
Section 6.6: the credibility constant
prospicio book
within variance 0.004562987 0.004562987
K 648 648
credibility at 1,000 aircraft-years 0.61 0.61

Table 6.5 lists encoded makes at K = 1,024, the monograph’s final value. The next chunk recomputes them from the printed inputs:

table_6_5 <- data.frame(
  make = c("DJI", "TEXTRON AVIATION INC", "MARLIN JOHN E", "STUMP GREAT LAKES"),
  expo = c(11900, 5483, 13, 12), ave = c(0, 0.24356, 186.59373, 223.74936),
  z_printed = c(0.9208, 0.8426, 0.0122, 0.0116), te_printed = c(0.079, 0.363, 3.266, 3.579)
)
z <- table_6_5$expo / (table_6_5$expo + 1024)
data.frame(make = table_6_5$make, z = z, `book z` = table_6_5$z_printed,
           encoding = 1 - z + z * table_6_5$ave,
           `from book z` = 1 - table_6_5$z_printed + table_6_5$z_printed * table_6_5$ave,
           `book encoding` = table_6_5$te_printed, check.names = FALSE) |>
  gt(rowname_col = "make") |>
  tab_header("Table 6.5: encoded makes at K = 1,024") |>
  fmt_number(columns = c(z, `book z`), decimals = 4) |>
  fmt_number(columns = c(encoding, `from book z`, `book encoding`), decimals = 3)
Table 6.5: encoded makes at K = 1,024
z book z encoding from book z book encoding
DJI 0.9208 0.9208 0.079 0.079 0.079
TEXTRON AVIATION INC 0.8426 0.8426 0.363 0.363 0.363
MARLIN JOHN E 0.0125 0.0122 3.327 3.264 3.266
STUMP GREAT LAKES 0.0116 0.0116 3.580 3.584 3.579

DJI and Textron match. Marlin’s printed credibility (0.0122) implies about 12.65 aircraft-years, not 13, so the exposure column is rounded (the encoding from the printed z is 3.264). Stump Great Lakes differs for the same reason.

Section 6.7.1’s worked sentence multiplies Stump’s z by 222.22, but Table 6.5 has 223.75, which gives the printed 3.58: the text is wrong. The table’s caption also describes AvE as predicted over actual, but its values are actual over expected.

Two smaller checks come from the same chapter: the Bell helicopter example of section 6.7.2 (16 per thousand against 4 for the overall mean, against 20 for the GLM prediction for helicopters), and the logistic blending of section 6.7.6 at a level with no data, which should get no credibility but gets some:

cat(sprintf("Bell: %.2f against the mean, %.2f against the GLM (printed 4 and 0.80)\n", 16 / 4, 16 / 20))
## Bell: 4.00 against the mean, 0.80 against the GLM (printed 4 and 0.80)
for (smoothing in c(100, 500)) {
  cat(sprintf("logistic credibility at n = 0, inflection 500, smoothing %d: %.3f\n",
              smoothing, 1 / (1 + exp((500 - 0) / smoothing))))
}
## logistic credibility at n = 0, inflection 500, smoothing 100: 0.007
## logistic credibility at n = 0, inflection 500, smoothing 500: 0.269

The second value is section 6.7.6’s “about 25%” for a level with no data.

4.3 Ridge regression on dummies is credibility

Section 6.8.1: ridge on the dummies of one factor, with a centred normal response and no intercept, gives each level the coefficient n_k (mean_k - mean) / (n_k + lambda), a credibility-weighted deviation from the overall mean. prospicio minimizes the mean squared error over two plus lambda over two times the sum of squares, so the monograph’s lambda is lambda times the number of records. A formula with 0 + has no intercept, so elastic_net_fit() fits exactly that model. The 456 responses are the Python guide’s draws.

lvl <- toys[toys$example == "dummies", ]
sizes <- c(1, 5, 50, 400)
lvl$yc <- lvl$y - mean(lvl$y)
lvl$level <- factor(lvl$x, levels = 0:3, labels = paste0("level", 0:3))
lam <- 0.1
fit <- elastic_net_fit(yc ~ 0 + level, lvl, family = "gaussian", alpha = 0, lambda = lam,
                       standardize = FALSE)
K <- lam * nrow(lvl)
data.frame(level = paste("level", 0:3), records = sizes, ridge = as.numeric(coef(fit)),
           `z x deviation` = sizes / (sizes + K) * sapply(0:3, function(j) mean(lvl$yc[lvl$x == j])),
           z = sizes / (sizes + K), check.names = FALSE) |>
  gt(rowname_col = "level") |>
  tab_header("Section 6.8.1: ridge on dummies is credibility",
             sprintf("lambda = %s, so the monograph's lambda is %.1f", lam, K)) |>
  fmt_integer(columns = records) |>
  fmt_number(columns = c(ridge, `z x deviation`), decimals = 4, force_sign = TRUE) |>
  fmt_number(columns = z, decimals = 3)
Section 6.8.1: ridge on dummies is credibility
lambda = 0.1, so the monograph's lambda is 45.6
records ridge z x deviation z
level 0 1 +0.0456 +0.0456 0.021
level 1 5 −0.0470 −0.0470 0.099
level 2 50 +0.2407 +0.2407 0.523
level 3 400 −0.0511 −0.0511 0.898

The penalty does the work of the Buhlmann K. Credibility theory estimates K from variance components; penalized regression chooses it by cross-validation.

4.4 Target encoding the portfolio’s 300 makes

On the portfolio, the encoding follows section 6.7.2. A cross-fitted first GLM without make gives each policy’s expected count, so no model predicts a record that it saw in training. A make’s encoding is its shrunk actual-to-expected ratio, and its log goes into a second-stage GLM with the first-GLM prediction as offset (section 6.9). For each K, seven-fold cross-validation repeats the whole procedure inside each fold:

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, ])

# Sums by make, one per make 0 to 299.
by_make <- function(rows, v) {
  out <- numeric(300)
  s <- rowsum(v[rows], pf$make[rows])
  out[as.integer(rownames(s)) + 1] <- s
  out
}

# Each make's shrunk actual-to-expected ratio from the rows in `source`.
encode <- function(source, K) {
  actual <- by_make(source, pf$claims)
  exp_ <- by_make(source, expected)
  z <- by_make(source, pf$exposure) / (by_make(source, pf$exposure) + K)
  1 - z + z * ifelse(exp_ > 0, actual / exp_, 1)
}

# Per policy: 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) {
  te <- encode(train & pf$fold != held_out, K)[pf$make + 1]
  for (j in setdiff(0:6, held_out)) {
    in_j <- pf$fold == j
    te[in_j] <- encode(train & pf$fold != j & pf$fold != held_out, K)[pf$make[in_j] + 1]
  }
  log(te)
}

stage1 <- lapply(0:6, function(k) predict(glm_fit(f_base, pf[train & pf$fold != k, ]), pf))
results <- do.call(rbind, lapply(c(16, 64, 256, 1024, 4096), function(K) {
  res <- vapply(0:6, function(k) {
    d2 <- data.frame(claims = pf$claims, log_te = make_feature(K, k), s1 = stage1[[k + 1]])
    fit2 <- glm_fit(claims ~ log_te + offset(log(s1)), d2[train & pf$fold != k, ])
    val <- pf$fold == k
    c(pseudo_r2(pf$claims[val], predict(fit2, d2[val, ]), pf$exposure[val]), coef(fit2)[["log_te"]])
  }, double(2))
  data.frame(K = as.character(K), `cv pseudo-R2` = mean(res[1, ]), coefficient = mean(res[2, ]),
             check.names = FALSE)
}))
gt(results, rowname_col = "K") |>
  tab_header("Target encoding of the 300 makes", "Second-stage GLM by credibility constant K") |>
  fmt_number(columns = `cv pseudo-R2`, decimals = 3) |>
  fmt_number(columns = coefficient, decimals = 2)
Target encoding of the 300 makes
Second-stage GLM by credibility constant K
cv pseudo-R2 coefficient
16 0.040 0.82
64 0.041 1.08
256 0.039 1.41
1024 0.037 2.24
4096 0.035 4.98

The baseline GLM scored 0.021 without make; the encoded make roughly doubles that. As in Figure 6.1, the score is flat over a wide range of K, best near 64. As in Figure 6.2, the coefficient rises with K: a heavily shrunk encoding needs a coefficient above 1 to restore the spread. The best score and a coefficient near 1 occur at the same K, as section 6.6 expects when the encoding is correct. The rest of the guide uses K = 64.

A generalized linear mixed model (section 6.5) treats make as a random effect and shrinks it the same way. Section 6.8.2 gives the Bayesian view of ridge, which is bayes_glm_fit() with normal priors.

5. The printed numbers of chapters 3 to 6 and prospicio’s

Where Printed Recomputed Note
Table 3.1 pseudo-R2 47% 0.471 matches
Section 3.5 linear predictor -2.467, 0.085 -2.467, 0.085 matches
Section 3.7.4 rebasing 1.0031 1.0031 matches
Section 4.1 variance 0.09, 0.30 0.09, 0.30 matches
Section 4.7.2 ridge in cm 0.019, 1.9 0.019998, 1.9998 printed digits truncated
Section 5.2 one step 0.00509, 0.2302 0.00508, 0.2302 relativity matches, the frequency is 0.005082
Section 5.2 three steps 0.00783 to 0.00119 0.00799 to 0.00122 all about 2% higher, which points at the printed intercept
Table 5.7 cumulative 2.06 2.067 Table 5.8 prints 2.07
Section 6.6 K 648, 0.61 648, 0.61 matches
Table 6.5 encodings 0.079, 0.363, 3.266, 3.579 0.079, 0.363, 3.264, 3.580 Marlin from its printed z, exposures printed rounded, 222.22 in the text is 223.75

Next: part 2, chapters 7 to 10.