Credibility And Factor-Varying Smooths#
RandomEffect and FactorSmooth(..., basis="fs") are REML-selected
credibility terms. They are useful when a categorical level has its own
experience, but thinner levels should borrow strength from the portfolio
instead of receiving unrestricted fixed effects.
FactorSmooth(..., basis="sz") is related but has a different interpretation:
it estimates centered level deviations around a required global curve. Its
wiggle is smoothed, but its polynomial null space is not fully shrunk unless
the term has select=True, and its level table is not labelled as
credibility or collapse.
SuperGLM |
mgcv analogue |
What varies by level |
|---|---|---|
|
|
one intercept |
|
|
a fully penalized smooth curve |
|
|
a centered deviation curve |
All three use every fitted level rather than dropping a reference level. REML
estimates their penalty strengths. For RE and FS this controls full shrinkage
toward the population prediction; for SZ it controls wiggle around a
sum-to-zero deviation surface, and with select=True every level’s line as
well, so the deviations can shrink fully.
Random intercept credibility#
Use a random effect when each level needs one relativity.
import numpy as np
from superglm import Numeric, RandomEffect, SuperGLM
model = SuperGLM(
family="poisson",
features={
"LogDensity": Numeric(),
"VehBrand": RandomEffect(),
},
selection_penalty=0.0,
)
model.fit_reml(
train,
train["ClaimNb"],
offset=np.log(train["Exposure"]),
)
The explicit selection_penalty=0.0 documents the fitting contract; it is not
an additional tuning parameter. fit_reml() owns the smoothing and
variance-component lambdas and therefore accepts only None or 0.0 for
selection. Omitted, None, and zero are equivalent here. Sparse term
selection belongs to fit() or fit_path(), not the REML fit.
The estimated variance component is \(\tau^2 = \phi / \lambda\). At level \(j\), SuperGLM reports scalar credibility
where \(I_j\) is the fitted working information. Thick levels have \(Z_j\) near one and retain more of their own estimate; thin levels have \(Z_j\) near zero and are pulled more strongly toward the population.
brand = model.random_effects(
"VehBrand",
exposure=train["Exposure"].to_numpy(),
)
brand.lambda_value
brand.tau_squared
brand.effective_df
brand.table[
[
"level",
"exposure",
"unpooled_effect",
"effect",
"posterior_se",
"credibility",
]
]
Fully penalized FS credibility#
Use a factor smooth when the deviation itself changes over a continuous variable. For example, the driver-age curve can differ by region:
import numpy as np
from superglm import FactorSmooth, Spline, SuperGLM
model = SuperGLM(
family="poisson",
features={
# The population curve
"DrivAge": Spline(kind="ps", k=8),
},
interactions=[
# Fully penalized regional deviations from that curve
FactorSmooth("DrivAge", group="Region", basis="fs", k=6),
],
selection_penalty=0.0,
)
model.fit_reml(
train,
train["ClaimNb"],
offset=np.log(train["Exposure"]),
)
One shared P-spline basis is repeated implicitly for every factor level. The
term has shared wiggle and null-space smoothing parameters, but each level
gets its own coefficient block. The null-space penalties make the deviations
fully penalized, matching the role of mgcv’s bs="fs" basis. Each null_j
shrinks one degree of every level’s polynomial part: null_0 its constant,
null_1 its straight line, null_2 (with m=3) its quadratic, each
orthogonal over the training rows to the lower degrees. A null_j smoothing
parameter therefore means the same curve whatever the row order or platform.
The degree is that of the B-spline coefficients as a polynomial in their
index: through null_3 it is the curve’s degree in x, and from null_4
(m >= 5) the curve stays piecewise cubic. An fs model saved before 0.44.0
keeps the null axes it was fitted on and predicts as before, but its
null_j smoothing parameters belong to those axes, not to the degrees, and do
not compare with a fresh fit’s.
For level \(j\), the scalar summary generalizes ordinary credibility to the whole coefficient block:
It is the mean fraction of the level’s \(k\) coefficient directions retained after shrinkage. It is a useful compact ranking, not a claim that all parts of the curve receive identical shrinkage.
regional_age = model.factor_smooth(
"DrivAge:Region:fs",
grid=80,
levels=["R11", "R24"],
)
regional_age.lambdas
regional_age.variance_components
regional_age.table[
["level", "fit_weight", "effective_df", "credibility", "sufficient_support"]
]
regional_age.curves[
["level", "DrivAge", "effect", "posterior_se", "lower", "upper"]
]
Add a global Spline("DrivAge") when the scientific question is “what is the
portfolio age curve, and how does each region deviate from it?” A factor
smooth can also be fitted without a global smooth when complete level-specific
curves are the intended model.
The FS null-space smoothing components are REML smoothing/variance
components. They are not sparse selection penalties, and they work with
fit_reml() while selection_penalty remains zero.
Centered SZ deviations#
Use SZ when the global curve should carry the portfolio-wide shape and the level curves should be identifiable deviations from it:
import numpy as np
from superglm import FactorSmooth, Spline, SuperGLM
model = SuperGLM(
family="poisson",
features={"DrivAge": Spline(kind="ps", k=7, m=2)},
interactions=[
FactorSmooth(
"DrivAge",
group="Region",
basis="sz",
kind="ps",
k=6,
m=2,
)
],
selection_penalty=0.0,
).fit_reml(train, train["ClaimNb"], offset=np.log(train["Exposure"]))
regional_deviation = model.factor_smooth("DrivAge:Region:sz", grid=80)
Equivalent marginal coefficients across levels sum to zero, so the deviation
curves also sum to zero pointwise. There is one shared wiggle lambda. The
polynomial null space remains unpenalized: even an extremely large wiggle
lambda can leave finite linear or low-order polynomial deviations. With
select=True (see “Penalizing SZ levels’ lines: select=True” in the
interactions guide), a second null
lambda penalizes every level’s line, and both lambdas at their upper bound
shrink every deviation to zero. For every sz term, with or without
select, regional_deviation.collapsed is None, and its table reports
support, information, EDF, and coefficient norms without credibility or
shrinkage columns.
The sz coefficients use the same coordinates as fs: for each level, the
coordinates in which the wiggle penalty is diagonal, then the unpenalized
polynomial coordinates. They are not the B-spline coefficients of the curve,
so compare levels through model.factor_smooth(...) rather than through raw
coefficients.
SZ requires the matching global Spline. It is not a generic
SplineCategorical interaction: SplineCategorical is reference-coded and
unpooled, while SZ uses all levels symmetrically with an exact sum-to-zero
constraint.
Do not add Categorical() or RandomEffect() for the same grouping column as
a FactorSmooth. The factor smooth already contains the lower-order group
geometry, so those terms would duplicate it. SuperGLM rejects that
configuration. Random effects for a different grouping column are supported.
Conditional and population prediction#
Prediction is conditional by default and includes fitted random effects and factor-smooth deviations:
conditional = model.predict(test)
population = model.predict(test, random_effects="population")
random_effects="population" zeros all RandomEffect and FactorSmooth
contributions while retaining fixed effects and global smooths. By default, an
unseen factor level also receives this zero-deviation population prediction.
Use unseen="error" on either term when an unknown level must fail instead.
Missing group values always fail.
Exact, discrete, and structured fitting#
These terms use compact group matrices beside the model’s other columns. The structured solver never forms the full matrix for the large term. It eliminates the term’s levels first and then solves the small dense part that remains:
Random effects form a tree. A lone random effect is a tree of one level. Nested random effects, such as vehicle models within makes, form a tree of several levels.
basis="fs"factor smooths give each level its own small block.basis="sz"factor smooths combine their levels through a balanced binary tree, which keeps the level curves summing to zero.
model = SuperGLM(
family="poisson",
features=features,
interactions=[
FactorSmooth("DrivAge", group="Region", basis="fs", k=6)
],
discrete=True,
n_bins=256,
direct_solve="auto",
selection_penalty=0.0,
)
model.fit_reml(train, y, offset=offset)
direct_solve="auto" keeps the Gram solver for small terms and uses the
structured solver above a size crossover. The crossover is reached only when
the structured term spans most of the coefficient columns: a wide random
effect beside an equally wide dense border fits faster on Gram. The choice
reads only the model’s terms, their sizes, and which grouping levels sit inside
which others.
A fit never switches solver. If the structured solver cannot finish a fit, the fit stops with an error that names the cause.
direct_solve="gram"fits the same model with the dense solver.direct_solve="structured"forces the structured solver. It is useful for reproducible benchmarking.A thinly observed
szlevel is kept. A level with fewer distinct values than its smooth’s unpenalized part stays in the model.Its standard errors can be missing. Such a level can leave every standard error of the term and of its main effect missing (NaN).
The structured solver names the level. It names such a level in a warning. The Gram solver fits the same model without that warning.
With
select=Truethe term penalizes every level’s line. No level keeps an unpenalized direction, and neither solver names a thin level at fit. Every coefficient has a standard error when the penalised fit has full rank, as a random effect’s levels do: the penalty then determines the directions the data leave open, such as a thin level’s line or the block of a level without weight. A level without weight is still predicted at the population curve, and the report’sthin_levelsandpredictname it.
discrete=True bins the continuous spline support and reuses cached
sufficient statistics across REML iterations; factor identities and the SZ
constraint remain exact. The large term keeps its compact form, the level
codes and one shared basis, so no matrix with a column per level and basis
function is built.
Real French motor example#
examples/fremtpl2_credibility.py
uses the real
freMTPL2freq OpenML data set
and follows the caps used by
scikit-learn’s insurance-pricing example.
Each row is a French motor third-party-liability policy with claim count,
exposure, driver, vehicle, and geographic attributes.
The claim counts come from the companion severity file,
freMTPL2sev, one record per claim, rather
than from the frequency file’s ClaimNb column. That column is wrong for the
policies numbered up to 24,500: almost none of their claims appear in the
severity file. Recounting every policy from the severity file and dropping the
six policies with more than five claims follows Wüthrich and Merz,
Statistical Foundations of Actuarial Learning and its Applications
(Springer, 2023), Section 13.1. It leaves 678,007 policies and 26,383 claims.
Run the deterministic 30,000-policy comparison:
uv run python examples/fremtpl2_credibility.py \
--max-rows 30000 \
--output-dir fremtpl2_credibility_results
The common baseline uses smooth driver age, vehicle age, and Bonus-Malus plus
the remaining tariff controls. All challengers use Poisson claim counts with
log(Exposure) as an offset. The test split contains 7,500 policies and 289
observed claims.
The table below is a 14 October 2026 snapshot generated with seed 20260724
against the OpenML and preprocessing versions available on that date. It is
not a CI-pinned data or performance contract. Regenerate it when the upstream
data set, preprocessing, solver, or material dependencies change. Every fit
reached a REML optimum within the script’s default limit of 50 iterations.
Challenger |
Credibility addition |
Held-out deviance |
Change vs baseline |
REML iterations |
|---|---|---|---|---|
baseline |
none |
0.444025 |
— |
12 |
brand fixed |
unrestricted vehicle-brand factor |
0.443880 |
+0.032% |
12 |
|
vehicle-brand random effect |
0.443369 |
+0.148% |
16 |
|
driver-age deviations by region |
0.445542 |
-0.342% |
13 |
|
both terms |
0.444744 |
-0.162% |
24 |
These are one seeded demonstration, not a universal ranking. They make the modeling distinction visible:
unrestricted brand coefficients gain little on this split;
brand credibility pools those estimates and gives the best holdout score, about 4.5 times the gain of the unrestricted factor;
regional driver-age deviations do not carry over to the holdout here: the
fschallenger is the worst of the five;combining plausible terms does not guarantee the best holdout score.
This page ran on the book as published until the correction (its last such
revision is 7d01428c), and the correction changed which term wins. There, the
unrestricted brand factor lost on the holdout (-0.339%), brand credibility lost
less (-0.131%) and the regional factor smooth scored best (+0.279%). On the
corrected counts the brand factor gains a little (+0.032%), brand credibility
is best (+0.148%) and the factor smooth is worst (-0.342%). One finding holds on
both runs: combining terms does not guarantee the best holdout score. That the
thinnest brands are pulled hardest toward zero is a property of the estimator,
Z_j = I_j / (I_j + lambda), not a finding of either run.
Vehicle-brand credibility ranged from 0.110 to 0.850, lowest on the
thinnest brands, as Z_j implies. Regional factor-smooth credibility
ranged from 0.0020 to 0.127, reflecting the greater information required
to estimate a complete curve rather than one intercept.
The script writes held-out metrics, the random-effect table, factor-smooth
credibility and curve tables, and credibility_demo.png.
Current scope#
FactorSmoothsupportsbasis="fs"andbasis="sz", currently withkind="ps", and requiresfit_reml().FS/SZ construct the marginal in bounded QR chunks before evaluating the final support basis, for every
mand null-component policy.fit()andfit_path()reject factor smooths.Factor-smooth
kmust be at least 5.basis="fs"refuses a difference ordermthat float64 does not reliably represent, where a closed-form lower bound on its penalty’s condition number reaches 2^47 (none belowk=73; atk=100,17 <= m <= 75), unless the wiggle’s smoothing parameter is fixed at zero. A fit refusesnull_0fixed at zero beside an intercept, which the levels’ constants would alias, and warns when it is fixed below the REML floor.Missing numeric or grouping values are rejected.
The FS and SZ Gaussian, Poisson, construction, unseen-level, and discrete reference cases are pinned against mgcv in the test suite. The FS cases fit the same penalties in mgcv 1.9-3 through
paraPen(tests/oracles/factor_smooth_mgcv_reference.R), because mgcv’s ownbs="fs"penalizes whichever basis of the null space its eigensolver returns, and a shuffle of the rows can permute, flip or rotate that basis. The SZ cases are pinned against mgcv 1.9-4’s ownbs="sz".