GLMs for insurance rating, part 2: refinement and validation (Goldburd, Khare, Tevet and Guller)
glm-ratemaking-goldburd-validation.RmdRendered from docs/guides/glm-ratemaking-goldburd-validation.qmd.
The code runs each time the site is built, so the output below is
current.
This is part 2 of a guide to Generalized Linear Models for Insurance Rating (CAS Monograph 5, second edition, 2025 revision; Goldburd, Khare, Tevet and Guller), with the prospicio R package. Part 1 covers the multiplicative rating plan, offsets, weights, the choice of distribution and the F-test, and maps the monograph’s workflow to prospicio.
Section numbers are the monograph’s. The PDF does not hold its data,
so the guide recomputes the printed arithmetic where it can and runs the
workflow on the synthetic portfolio
validation/data/glm_policies.csv.
The setup is that of part 1: 600 policies, with the log of exposure
as the claim count offset. claims is Poisson with a
log-linear age effect and region factors 1.0, 1.2, 0.8 and 1.5 for A to
D. wavy_claims is Poisson with the non-linear age effect
0.8 sin(age / 8):
library(prospicio)
# The data file, found from the repository root (CI) or from docs/guides (Quarto).
find_data <- function(name, dir = getwd()) {
repeat {
path <- file.path(dir, "validation", "data", name)
if (file.exists(path)) return(path)
parent <- dirname(dir)
if (identical(parent, dir)) stop("validation/data/", name, " not found", call. = FALSE)
dir <- parent
}
}
d <- read.csv(find_data("glm_policies.csv"))
n <- nrow(d)
big <- glm_fit(claims ~ age + region + offset(log(exposure)), d, family = "poisson", dispersion = "pearson")
cat(n, "policies,", sum(d$claims), "claims,", sum(d$wavy_claims), "wavy_claims\n")## 600 policies, 155 claims, 693 wavy_claims
This is the R twin of the Python guide glm-ratemaking-goldburd-validation.md,
with the same sections, examples and numbers.
1. Continuous variables: partial residuals, bins, polynomials, hinges and splines (section 5.4)
A continuous predictor enters linearly on the link scale. Section
5.4.1 tests this with partial residuals against x: the
working residual (y - mu) / mu (log link) plus the
predictor’s own term b x. Each bin is averaged with the
working weights (mu times the prior weight for a Poisson on
the log link, section 6.3.2). glm_diagnostics() returns
both. The fit is a straight line in age on wavy_claims:
ages <- d$age
y <- d$wavy_claims
linear <- glm_fit(wavy_claims ~ age + offset(log(exposure)), d, family = "poisson")
b_age <- linear@coefficients[["age"]]
diag <- glm_diagnostics(linear)
partial <- diag$working + b_age * ages
cat(sprintf("linear age slope %+.4f\n", b_age))## linear age slope +0.0121
library(gt)
true_c <- mean(0.8 * sin(ages / 8))
ord <- order(ages)
bands <- do.call(rbind, lapply(0:7, function(k) {
idx <- ord[(k * n %/% 8 + 1):((k + 1) * n %/% 8)]
ww <- diag$working_weights[idx]
age <- sum(ages[idx] * ww) / sum(ww)
data.frame(band = sprintf("%.1f-%.1f", ages[idx[1]], ages[idx[length(idx)]]), mean_age = age,
partial = sum(partial[idx] * ww) / sum(ww), fitted = b_age * age,
true = 0.8 * sin(age / 8) - true_c)
}))
gt(bands, rowname_col = "band") |>
tab_header("Partial residuals of wavy_claims against age",
"Eight bands of equal count, averaged with the working weights") |>
cols_label(mean_age = "mean age", partial = "binned partial residual", fitted = "fitted b x age",
true = "true 0.8 sin(age/8), centred") |>
fmt_number(columns = mean_age, decimals = 1) |>
fmt_number(columns = c(partial, fitted), decimals = 3) |>
fmt_number(columns = true, decimals = 3, force_sign = TRUE)| Partial residuals of wavy_claims against age | ||||
| Eight bands of equal count, averaged with the working weights | ||||
| mean age | binned partial residual | fitted b x age | true 0.8 sin(age/8), centred | |
|---|---|---|---|---|
| 18.1-24.7 | 21.6 | 0.840 | 0.263 | +0.315 |
| 24.8-30.6 | 28.2 | 0.307 | 0.341 | −0.318 |
| 30.7-38.3 | 34.3 | −0.106 | 0.416 | −0.750 |
| 38.5-46.8 | 42.9 | 0.005 | 0.520 | −0.660 |
| 47.0-56.7 | 52.0 | 0.747 | 0.631 | +0.152 |
| 56.8-62.9 | 59.7 | 1.216 | 0.724 | +0.716 |
| 63.0-71.4 | 67.6 | 1.117 | 0.820 | +0.640 |
| 71.5-79.9 | 76.1 | 0.603 | 0.922 | −0.088 |
library(ggplot2, exclude = "layer") # keeps prospicio's layer()
bins <- lapply(0:7, function(k) ord[(k * n %/% 8 + 1):((k + 1) * n %/% 8)])
binned <- data.frame(
age = sapply(bins, function(i) sum(ages[i] * diag$working_weights[i]) / sum(diag$working_weights[i])),
pr = sapply(bins, function(i) sum(partial[i] * diag$working_weights[i]) / sum(diag$working_weights[i])),
series = "binned partial residual")
grid <- seq(18, 80, by = 0.5)
curves <- rbind(
data.frame(age = grid, pr = b_age * grid, series = "fitted straight line, b x age"),
data.frame(age = grid, pr = 0.8 * sin(grid / 8) - true_c, series = "true effect, 0.8 sin(age / 8), centred"))
ggplot(curves, aes(age, pr)) +
geom_line(aes(colour = series), linewidth = 0.8) +
geom_point(data = binned, colour = "grey40", size = 2) +
labs(x = "age (years)", y = "partial residual (log scale)", colour = NULL,
title = "Partial residuals of wavy_claims against age: a line misses the wave
(dots: binned partial residual)") +
theme(legend.position = "top")The binned residuals follow the true sine, shifted by about 0.6 (the
intercept’s share), with a trough near 40 and a peak near 60. The
monograph offers four fixes, and prospicio fits all of them. In R the
first three are formula terms (factor(),
I(z^2), pmax(0, age - k)):
- bins (5.4.2): a factor of age bands of about equal counts. Each band floats freely, at the cost of many parameters and possible reversals.
- polynomials (5.4.3): powers of a centred and scaled age. They bend, but misbehave at the edges.
-
hinge functions (5.4.4):
max(0, age - knot)terms. The slope changes at chosen knots, here 38 and 62, read off the trough near 40 and the peak near 60. -
splines (5.4.5 and 10.3):
gam_fit()fits a penalized P-spline with the smoothness chosen by UBRE (the GAM of section 10.3). A natural cubic spline also works (splines::ns(age, df)in the formula,Terms.natural_splinein Python), but the guide uses the GAM in both languages.
Each fit gets its training deviance, its AIC (with the GAM’s
effective degrees of freedom) and its mean Poisson deviance on five
held-out folds from cross_validate(). k_fold()
gives the same folds in Python and R (the R indices are the Python
indices plus one):
cuts <- sort(ages)[(1:7) * n %/% 8 + 1]
d$band <- factor(vapply(ages, function(a) sum(a >= cuts), 0))
d$z <- (ages - 50) / 20
forms <- list(
"linear" = wavy_claims ~ age + offset(log(exposure)),
"8 bins" = wavy_claims ~ band + offset(log(exposure)),
"cubic" = wavy_claims ~ z + I(z^2) + I(z^3) + offset(log(exposure)),
"hinges 38, 62" = wavy_claims ~ age + pmax(0, age - 38) + pmax(0, age - 62) + offset(log(exposure))
)
folds <- k_fold(n, 5, 2025)
cv_deviance <- function(fit_fn) {
mean(cross_validate(d, folds, fit_fn, function(m, test) {
family_deviance("poisson", test$wavy_claims, predict(m, test)) / nrow(test)
}))
}
scores <- do.call(rbind, lapply(names(forms), function(name) {
fit <- glm_fit(forms[[name]], d, family = "poisson")
cv <- cv_deviance(function(train) glm_fit(forms[[name]], train, family = "poisson"))
data.frame(model = name, parameters = as.character(length(fit@coefficients)),
deviance = fit@deviance, aic = fit@aic, cv = cv)
}))
gam_form <- wavy_claims ~ age + offset(log(exposure))
gfit <- gam_fit(gam_form, d, smooths = "age", n_basis = 10, family = "poisson")
ll <- sum(y * log(gfit@fitted) - gfit@fitted - lgamma(y + 1))
cv <- cv_deviance(function(train) gam_fit(gam_form, train, smooths = "age", n_basis = 10, family = "poisson"))
scores <- rbind(scores, data.frame(model = "P-spline GAM", parameters = sprintf("%.1f", gfit@edf),
deviance = gfit@deviance, aic = -2 * ll + 2 * gfit@edf, cv = cv))
gt(scores, rowname_col = "model") |>
tab_header("Five age effects on wavy_claims", "Training deviance and AIC; mean deviance on five held-out folds") |>
cols_label(aic = "AIC", cv = "CV deviance") |>
fmt_number(columns = c(deviance, aic), decimals = 1, use_seps = FALSE) |>
fmt_number(columns = cv, decimals = 4)| Five age effects on wavy_claims | ||||
| Training deviance and AIC; mean deviance on five held-out folds | ||||
| parameters | deviance | AIC | CV deviance | |
|---|---|---|---|---|
| linear | 2 | 769.9 | 1673.9 | 1.2923 |
| 8 bins | 8 | 658.6 | 1574.6 | 1.1338 |
| cubic | 4 | 635.5 | 1543.5 | 1.0730 |
| hinges 38, 62 | 4 | 624.0 | 1532.0 | 1.0534 |
| P-spline GAM | 5.8 | 621.0 | 1532.7 | 1.0612 |
All four non-linear forms beat the straight line. The hinges, with knots read off the partial residuals, do best out of sample, just ahead of the GAM, which found its shape unaided.
The monograph’s building-age example, from its printed coefficients:
Table 6 has a slope of 1.225 below the knot at log age 2.75 and 1.225 -
2.269 above it, and Table 7 adds a knot at 3.6 with coefficient 1.170.
The quadratic of Figure 10 (4.749 x - 0.866 x^2) peaks at
x = 4.749 / (2 x 0.866), near the authors’ knot and the
GAM’s peak at about e^2.8 (section 10.3):
## Table 6 slopes: 1.225 then -1.044 (monograph 1.225 and -1.044)
## Table 7 slopes: 1.289, -1.183, -0.013
peak <- 4.749 / (2 * 0.866)
cat(sprintf("quadratic peak at log age %.2f, about %.0f years; GAM peak e^2.8 = %.0f years\n", peak, exp(peak), exp(2.8)))## quadratic peak at log age 2.74, about 16 years; GAM peak e^2.8 = 16 years
Past the second knot at log age 3.6 the slope is almost flat, the “leveling off” of the monograph.
2. Interactions (section 5.6)
An interaction makes one variable’s relativity depend on the level of another. In a multiplicative plan it is one more factor, applied only to the combination. Figure 13 has main factors 2.0 and 1.5 and an interaction factor of 1.1 on the BY cell. Table 9 gives occupancy class 2 a sprinkler factor from the sum of the main and interaction coefficients:
base <- 10.0; f_b <- 2.0; f_y <- 1.5; f_by <- 1.1
checks <- data.frame(
quantity = c("cell X/A", "cell X/B", "cell Y/A", "cell Y/B", "sprinkler discount, main effects only",
"sprinkler discount, class 1 with the interaction", "sprinkler factor, class 2 (a 43.7% discount)"),
prospicio = c(base, base * f_b, base * f_y, round(base * f_b * f_y * f_by, 1), exp(-0.3046) - 1,
exp(-0.2895) - 1, exp(-0.2895 - 0.2847)),
book = c(10, 20, 15, 33, -0.263, -0.251, 0.563))
gt(checks, rowname_col = "quantity") |>
tab_header("Interaction arithmetic against the monograph", "Figure 13 and Table 9") |>
fmt_number(columns = c(prospicio, book), rows = 1:4, decimals = 0) |>
fmt_percent(columns = c(prospicio, book), rows = 5:6, decimals = 1) |>
fmt_number(columns = c(prospicio, book), rows = 7, decimals = 3)| Interaction arithmetic against the monograph | ||
| Figure 13 and Table 9 | ||
| prospicio | book | |
|---|---|---|
| cell X/A | 10 | 10 |
| cell X/B | 20 | 20 |
| cell Y/A | 15 | 15 |
| cell Y/B | 33 | 33 |
| sprinkler discount, main effects only | −26.3% | −26.3% |
| sprinkler discount, class 1 with the interaction | −25.1% | −25.1% |
| sprinkler factor, class 2 (a 43.7% discount) | 0.563 | 0.563 |
A factor-by-continuous interaction shifts the slope, and the main
effect then refers to the point where the continuous variable is zero.
In Table 11 that is log AOI = 0, an amount of $1, which is why the
sprinkler main effect turns positive. Table 12 uses
log(AOI / 200,000), so the main effect is the relativity at
the base amount. The tables are the same model: each intercept-like term
of Table 12 picks up its slope times ln 200,000:
shift <- log(200000)
cat(sprintf("intercept: %.4f (monograph Table 12: -3.7710)\n", -8.9456 + 0.4239 * shift))## intercept: -3.7714 (monograph Table 12: -3.7710)
## sprinklered: -0.5150 (monograph Table 12: -0.5153)
The gaps of 0.0004 and 0.0003 are rounding: a slope rounded by
0.00005 moves its product with ln 200,000 = 12.2 by
0.0006.
In R, the interaction is a formula term, region:ac, with
ac the centred age (Python:
Terms.interaction). f_test() compares the
models with and without it. The true model has no interaction, and the
F-test agrees. Centring age at 40 also makes the region main effects the
relativities of a 40-year-old, as in Table 12:
d$ac <- d$age - 40
mains <- glm_fit(claims ~ ac + region + offset(log(exposure)), d, family = "poisson", dispersion = "pearson")
inter <- glm_fit(claims ~ ac + region + region:ac + offset(log(exposure)), d, family = "poisson", dispersion = "pearson")
test <- f_test(mains, inter)
cat(sprintf("region x age: F = %.3f, percentile %.1f%%\n", test$statistic, 100 * (1 - test$p_value)))## region x age: F = 1.024, percentile 61.8%
cat("same fit as uncentred age:", abs(mains@deviance - big@deviance) < 1e-8,
sprintf("; base rate at age 40 %.4f (true %.4f)\n", exp(mains@coefficients[[1]]), exp(-1)))## same fit as uncentred age: TRUE ; base rate at age 40 0.4574 (true 0.3679)
3. Deviance and residuals (sections 6.1 and 6.3)
The scaled deviance is twice the gap in log-likelihood between the
saturated model (one parameter per row) and the fitted model. Multiplied
by phi, it is the unscaled deviance, which
@deviance and family_deviance() report. For
the Poisson, each row contributes
2 [y ln(y / mu) - (y - mu)]. For the gamma, each row
contributes 2 [-ln(y / mu) + (y - mu) / mu]. On a tiny
example:
y3 <- c(0, 1, 3); mu3 <- c(0.5, 1.2, 2.0)
pois <- sum(2 * (ifelse(y3 > 0, y3 * log(y3 / mu3), 0) - (y3 - mu3)))
cat(sprintf("Poisson deviance by hand %.6f, prospicio %.6f\n", pois, family_deviance("poisson", y3, mu3)))## Poisson deviance by hand 1.468148, prospicio 1.468148
y3 <- c(100, 250, 900); mu3 <- c(150, 200, 600)
gam_d <- sum(2 * (-log(y3 / mu3) + (y3 - mu3) / mu3))
cat(sprintf("gamma deviance by hand %.6f, prospicio %.6f\n", gam_d, family_deviance("gamma", y3, mu3)))## gamma deviance by hand 0.387046, prospicio 0.387046
Section 6.3.2 defines the working residuals
(y - mu) g'(mu) and bins them with equal sums of working
weights w / (V(mu) g'(mu)^2) (mu for the
Poisson on the log link). For a well-specified model, each of
m binned residuals has mean 0 and variance
phi m / SWW, for total working weight SWW; the
appendix suggests an m that makes this about 0.01 or less.
Binned over a predictor (Figure 19), the residuals show a missed
non-linear effect. Here the wavy_claims residuals are
binned over age for the straight line and the GAM. If the model is
right, the sum of the squared bin residuals over their variance is about
chi-square with 10 degrees of freedom (mean 10, 95th percentile
18.3):
binned_working_residuals <- function(key, y, mu, m) {
idx <- order(key)
total <- sum(mu); out <- numeric(); cum <- 0; cur <- integer()
for (i in idx) {
cur <- c(cur, i)
cum <- cum + mu[i]
if (cum >= total * (length(out) + 1) / m - 1e-9 || i == idx[length(idx)]) {
out <- c(out, sum(y[cur] - mu[cur]) / sum(mu[cur]))
cur <- integer()
}
}
out
}
m <- 10
sdev <- sqrt(m / sum(linear@fitted))
cat(sprintf("%d bins by age, total working weight %.0f, sd of a bin under the model %.3f\n", m, sum(linear@fitted), sdev))## 10 bins by age, total working weight 693, sd of a bin under the model 0.120
resid <- do.call(rbind, lapply(c("straight line", "GAM"), function(name) {
bins <- binned_working_residuals(ages, y, if (name == "GAM") gfit@fitted else linear@fitted, m)
out <- data.frame(model = name, t(setNames(bins, as.character(1:m))), check.names = FALSE)
out$ss <- sum(bins^2) / sdev^2
out
}))
gt(resid, rowname_col = "model") |>
tab_header("Binned working residuals over age", "Ten bins of equal working weight") |>
tab_spanner("bin", columns = as.character(1:m)) |>
cols_label(ss = "sum of squares / sd^2") |>
fmt_number(columns = as.character(1:m), decimals = 2, force_sign = TRUE) |>
fmt_number(columns = ss, decimals = 1)| Binned working residuals over age | |||||||||||
| Ten bins of equal working weight | |||||||||||
|
bin
|
sum of squares / sd^2 | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ||
| straight line | +0.55 | −0.21 | −0.53 | −0.52 | −0.06 | +0.41 | +0.76 | +0.10 | −0.04 | −0.48 | 130.8 |
| GAM | −0.01 | +0.05 | −0.09 | +0.03 | +0.05 | −0.09 | +0.08 | +0.02 | −0.01 | −0.04 | 2.1 |
The straight line’s residuals follow the sine, far beyond their standard deviation of 0.12. The GAM’s show no pattern; their sum of squares is below chance, as expected for a model fitted to the same data.
Section 6.3.1 notes that deviance residuals of counts cluster and
look non-normal, and suggests randomized quantile residuals (Dunn and
Smyth): each count’s residual is drawn at random within the normal
scores of its probability step, so under the right model it is exactly
standard normal. prospicio has them as
residuals(type = "quantile") on a glm_fit()
model, and as quantile_residuals() for any family (the
randomized probability integral transform of pit_values()).
The claim count model has the true form:
moments <- function(r) {
m <- mean(r)
skew <- mean((r - m)^3) / mean((r - m)^2)^1.5
sprintf("mean %+.2f, sd %.2f, skewness %+.2f, beyond 1.96: %.1f%%", m, sd(r), skew, 100 * mean(abs(r) > 1.96))
}
claims_fit <- glm_fit(claims ~ age + region + offset(log(exposure)), d, family = "poisson")
claims_diag <- glm_diagnostics(claims_fit)
cat("deviance residuals:", moments(claims_diag$deviance), "\n")## deviance residuals: mean -0.26, sd 0.82, skewness +1.45, beyond 1.96: 1.3%
## quantile residuals: mean -0.05, sd 1.03, skewness +0.05, beyond 1.96: 4.5%
With about a quarter of a claim expected per policy, the deviance residuals form two clusters (no claim, one claim), skewed and too narrow. The quantile residuals match a standard normal in mean, spread, symmetry and tails; a departure would point at the model.
4. Validation on held-out data (sections 4.3 and 7)
The monograph requires a test on data the fit did not use: build on a
training set and touch the test set once at the end. Here one fold of
five from k_fold() is held out, and a “current plan” (the
straight line in age) is compared with a “proposed model” (the GAM) on
wavy_claims. lift_table() sorts the test rows
by predicted claims per year and cuts them into bands of equal exposure
(the quantile plot of section 7.2.1). A good model’s actuals track its
predictions and spread widely from the first band to the last. Values
are relative to the test set’s average frequency:
train <- folds[[1]]$train
test <- folds[[1]]$test
yt <- y[test]
et <- d$exposure[test]
current <- predict(glm_fit(forms[["linear"]], d[train, ], family = "poisson"), d[test, ])
proposed <- predict(gam_fit(gam_form, d[train, ], smooths = "age", n_basis = 10, family = "poisson"), d[test, ])
avg <- sum(yt) / sum(et)
by_band <- data.frame(band = 1:5)
for (name in c("current", "proposed")) {
b <- lift_table(yt, if (name == "current") current else proposed, et, bands = 5)
by_band[[paste(name, "pred")]] <- b$expected / b$exposure / avg
by_band[[paste(name, "act")]] <- b$actual / b$exposure / avg
}
gt(by_band, rowname_col = "band") |>
tab_header("Lift on the test set", "Claim frequency relative to the test average, 5 bands of equal exposure") |>
cols_label(`current pred` = "current predicted", `current act` = "current actual",
`proposed pred` = "proposed predicted", `proposed act` = "proposed actual") |>
fmt_number(columns = -band, decimals = 2)| Lift on the test set | ||||
| Claim frequency relative to the test average, 5 bands of equal exposure | ||||
| current predicted | current actual | proposed predicted | proposed actual | |
|---|---|---|---|---|
| 1 | 0.85 | 0.91 | 0.49 | 0.46 |
| 2 | 0.97 | 0.39 | 0.77 | 0.50 |
| 3 | 1.16 | 1.13 | 1.16 | 1.03 |
| 4 | 1.35 | 1.43 | 1.70 | 1.46 |
| 5 | 1.56 | 1.12 | 2.15 | 1.55 |
The current plan’s actuals do not rise with its predictions (band 2 is the lowest). The proposed model’s actuals rise in every band.
The double lift chart (section 7.2.2) sorts by the ratio of the
predictions of the two models. The end bands hold the risks on which the
models disagree most. The loss ratio chart (section 7.2.3) sorts by the
proposed model over the current premium. If the proposed model improves
on the plan, the loss ratios rise across the bands.
double_lift_table() and loss_ratio_table()
draw both, in bands of about equal exposure.
The Gini index (section 7.2.4) sorts by predicted rate and plots the
cumulative share of exposure against the cumulative share of losses (the
Lorenz curve); it is twice the area between the curve and the diagonal.
gini_index() computes it with exposure and takes ties
together. Here the rate depends only on age, so policies of the same age
tie, but only up to floating-point bits that differ between platforms
and between the Python and R fits. Rounding the rates to 10 decimals
makes the ties exact:
dl <- double_lift_table(yt, proposed, current, et, bands = 5)
lr <- loss_ratio_table(yt, proposed, current, et, bands = 5)
rate <- function(pred) round(pred / et, 10) # equal ages tie exactly
cat(sprintf("Gini on the test set: current %.3f, proposed %.3f\n",
gini_index(yt, rate(current), et), gini_index(yt, rate(proposed), et)))## Gini on the test set: current 0.121, proposed 0.256
lift_bands <- data.frame(band = 1:5, current = dl$b_relativity, proposed = dl$a_relativity,
actual = dl$actual_relativity, loss_ratio = lr$loss_ratio)
gt(lift_bands, rowname_col = "band") |>
tab_header("Double lift and loss ratio, 120 test policies in 5 bands",
"Relativities to the overall average; loss ratio = actual / current premium") |>
tab_spanner("relativity", columns = c(current, proposed, actual)) |>
cols_label(loss_ratio = "loss ratio") |>
fmt_number(columns = -band, decimals = 2)| Double lift and loss ratio, 120 test policies in 5 bands | ||||
| Relativities to the overall average; loss ratio = actual / current premium | ||||
|
relativity
|
loss ratio | |||
|---|---|---|---|---|
| current | proposed | actual | ||
| 1 | 0.96 | 0.42 | 0.48 | 0.42 |
| 2 | 1.03 | 0.66 | 0.65 | 0.54 |
| 3 | 1.01 | 0.97 | 1.32 | 1.10 |
| 4 | 1.01 | 1.36 | 0.75 | 0.62 |
| 5 | 0.98 | 1.59 | 1.82 | 1.57 |
long <- data.frame(band = rep(1:5, 3),
relativity = c(lift_bands$actual, lift_bands$current, lift_bands$proposed),
series = rep(c("actual", "current plan", "proposed model"), each = 5))
ggplot(long, aes(band, relativity)) +
geom_hline(yintercept = 1, colour = "grey75", linetype = "dotted") +
geom_line(aes(colour = series), linewidth = 0.8) +
geom_point(aes(colour = series), size = 2) +
labs(x = "band (sorted by proposed / current prediction)",
y = "relative claim frequency (overall = 1)", colour = NULL,
title = "Double lift chart: the actuals follow the proposed model") +
theme(legend.position = "top")In both end bands of the double lift chart the actuals run with the proposed model, and the current plan predicts about 1 in every band: where the two models disagree, the proposed model was right. The loss ratio chart says the same, with one reversal in the 120 test policies.
For a yes or no outcome, section 7.3 adds the ROC curve. Table 13’s confusion matrices give the rates the monograph quotes:
roc_rates <- data.frame(
rate = c("sensitivity at 50%", "specificity at 50%", "false positive rate at 50%",
"sensitivity at 25%", "false positive rate at 25%"),
prospicio = c(39 / 109, 673 / 704, 1 - 673 / 704, 75 / 109, 103 / 704),
book = c(0.358, 0.956, 0.044, 0.688, 0.146))
gt(roc_rates, rowname_col = "rate") |>
tab_header("Rates from the confusion matrices of Table 13", "Threshold on the predicted claim probability") |>
fmt_number(columns = c(prospicio, book), rows = 1:3, decimals = 3) |>
fmt_percent(columns = c(prospicio, book), rows = 4:5, decimals = 1)| Rates from the confusion matrices of Table 13 | ||
| Threshold on the predicted claim probability | ||
| prospicio | book | |
|---|---|---|
| sensitivity at 50% | 0.358 | 0.358 |
| specificity at 50% | 0.956 | 0.956 |
| false positive rate at 50% | 0.044 | 0.044 |
| sensitivity at 25% | 68.8% | 68.8% |
| false positive rate at 25% | 14.6% | 14.6% |
Footnote 17 states that the area under the ROC curve is
0.5 x normalized Gini + 0.5, where the normalized Gini is
the model’s Gini over that of a perfect model (each row predicted by its
own outcome). A logistic model of whether a policy had a claim checks
the identity: the area comes from roc_curve() (ties count
as half, as in the Mann-Whitney statistic) and the normalized Gini from
normalized_gini():
d$had_claim <- as.numeric(d$wavy_claims > 0)
prob <- glm_fit(had_claim ~ age + pmax(0, age - 38) + pmax(0, age - 62) + log(exposure), d,
family = "binomial", link = "logit")@fitted
auc <- roc_curve(d$had_claim, prob)$auc
cat(sprintf("AUROC %.6f; 0.5 x normalized Gini + 0.5 = %.6f\n", auc, 0.5 * normalized_gini(d$had_claim, prob) + 0.5))## AUROC 0.743339; 0.5 x normalized Gini + 0.5 = 0.743339
For a binary outcome, the Lorenz curve and the ROC curve carry the same information, so the monograph warns against reporting both as separate evidence.
5. Stability and regularization (sections 6.4 and 10.5)
Section 6.4 checks stability by refitting on the cross-validation training sets (or bootstrap samples) and watching the coefficients:
c_full <- claims ~ age + region + offset(log(exposure))
stab <- do.call(rbind, lapply(seq_along(folds), function(k) {
b <- glm_fit(c_full, d[folds[[k]]$train, ], family = "poisson")@coefficients[-1]
data.frame(fold = k - 1, age = b[[1]], B = b[[2]], C = b[[3]], D = b[[4]])
}))
gt(stab, rowname_col = "fold") |>
tab_header("Coefficients refitted without one fold", "Claim count model, log scale") |>
fmt_number(columns = age, decimals = 4, force_sign = TRUE) |>
fmt_number(columns = c(B, C, D), decimals = 3, force_sign = TRUE)| Coefficients refitted without one fold | ||||
| Claim count model, log scale | ||||
| age | B | C | D | |
|---|---|---|---|---|
| 0 | −0.0091 | +0.166 | −0.314 | +0.274 |
| 1 | −0.0097 | −0.099 | −0.284 | +0.122 |
| 2 | −0.0112 | +0.207 | −0.318 | +0.061 |
| 3 | −0.0093 | +0.052 | −0.122 | +0.345 |
| 4 | −0.0132 | +0.051 | −0.270 | +0.187 |
The age slope stays between -0.009 and -0.013. The region coefficients move by up to 0.3, about their standard errors. The 155 claims leave them unsettled.
Section 6.4 also looks for single records with an outsized pull.
Cook’s distance is how far all the coefficients move, scaled by their
covariance, when the fit leaves out one row; it is large when a row has
both a large residual and high leverage (hat value).
cooks.distance() and hatvalues() return both
for the claim count model of section 3:
cook <- cooks.distance(claims_fit)
top <- order(-cook)[1:3]
influential <- data.frame(rank = 1:3, claims = d$claims[top], expected = claims_fit@fitted[top],
region = d$region[top], age = d$age[top], leverage = hatvalues(claims_fit)[top],
cook = cook[top])
gt(influential, rowname_col = "rank") |>
tab_header("The three most influential policies", "Claim count model") |>
cols_label(cook = "Cook's D") |>
fmt_integer(columns = claims) |>
fmt_number(columns = expected, decimals = 2) |>
fmt_number(columns = age, decimals = 1) |>
fmt_number(columns = c(leverage, cook), decimals = 4)| The three most influential policies | ||||||
| Claim count model | ||||||
| claims | expected | region | age | leverage | Cook's D | |
|---|---|---|---|---|---|---|
| 1 | 3 | 0.32 | B | 69.9 | 0.0116 | 0.0522 |
| 2 | 2 | 0.34 | C | 22.2 | 0.0201 | 0.0334 |
| 3 | 2 | 0.31 | C | 33.7 | 0.0151 | 0.0292 |
refit <- glm_fit(claims ~ age + region + offset(log(exposure)), d[-top[1], ], family = "poisson")
cat(sprintf("region B coefficient %+.3f, without that policy %+.3f\n", claims_fit@coefficients[[3]], refit@coefficients[[3]]))## region B coefficient +0.078, without that policy +0.018
The most influential policy had three claims in 0.9 years where 0.32 were expected. No leverage is high (the average is 5/600, 0.008), so the pull comes from the residual. With 155 claims in all, one policy can shift a thin level’s relativity by several points, which is why the monograph says to look.
The elastic net (section 10.5) minimizes the deviance plus
lambda times a mix of the coefficients’ absolute values
(lasso) and squares (ridge), on standardized columns with the intercept
unpenalized. As lambda falls from the value that zeroes
every coefficient, variables enter one by one, and cross-validation
picks lambda. elastic_net_fit() and
elastic_net_cv() minimize glmnet’s objective, for every
family including the gamma and the Tweedie. The claim count model gets
age, region and two columns unrelated to claims (trials and
n_sev, drawn independently), and the lasso sorts them:
foldid <- integer(n)
for (k in seq_along(folds)) foldid[folds[[k]]$test] <- k
form <- claims ~ age + trials + n_sev + region + offset(log(exposure))
cv <- elastic_net_cv(form, d, family = "poisson", link = "log", alpha = 1, nlambda = 40,
lambda_min_ratio = 1e-3, foldid = foldid)
lams <- cv$lambda
cat(sprintf("lambda_max %.5f, CV minimum at %.5f, one-SE choice %.5f\n", lams[1], cv$lambda_min, cv$lambda_1se))## lambda_max 0.05114, CV minimum at 0.02518, one-SE choice 0.05114
path <- function(label, b) {
names(b) <- sub("^region", "", names(b))
data.frame(fit = label, t(b), check.names = FALSE)
}
paths <- rbind(path("lambda_min", coef(cv$fit, lambda = cv$lambda_min)[-1]),
path("smaller", coef(cv$fit, lambda = lams[length(lams)])[-1]),
path("GLM", glm_fit(form, d, family = "poisson")@coefficients[-1]))
gt(paths, rowname_col = "fit") |>
tab_header("Lasso coefficients at two penalties, and the plain GLM", "Claim count model, log scale") |>
fmt_number(columns = -fit, decimals = 4, force_sign = TRUE)| Lasso coefficients at two penalties, and the plain GLM | ||||||
| Claim count model, log scale | ||||||
| age | trials | n_sev | B | C | D | |
|---|---|---|---|---|---|---|
| lambda_min | −0.0055 | 0.0000 | 0.0000 | 0.0000 | −0.0486 | 0.0000 |
| smaller | −0.0106 | −0.0254 | +0.0629 | +0.0696 | −0.2758 | +0.1984 |
| GLM | −0.0106 | −0.0255 | +0.0631 | +0.0700 | −0.2762 | +0.1990 |
At the cross-validated lambda the lasso keeps age
(shrunk by half) and a small region C discount, and drops the rest, both
noise columns included. With a cross-validation curve this flat, the
one-standard-error rule drops everything. At a small lambda
it is close to the unpenalized GLM, which gives the noise columns small
non-zero coefficients. Shrinking thin levels towards zero is the
credibility-like behaviour the monograph points to.