Interactions#

Tuple interactions are dispatched from their parent feature specs. They add an interaction alongside the configured main effects; for two spline parents, the result is a functional-ANOVA ti()-style interaction rather than a full te() or thin-plate tp() surface.

from superglm import Categorical, Spline, SuperGLM

model = SuperGLM(
    features={"age": Spline(k=14), "region": Categorical()},
    interactions=[("age", "region")],
    selection_penalty=0.01,
)
model.fit(df, y, sample_weight=exposure)

The same model as one list of terms names the interaction class itself: ti joins two smooths, and interaction(spec) takes any class in the table below. See Declaring terms.

from superglm import SplineCategorical, SuperGLM, cat, interaction, s

model = SuperGLM(
    terms=[s("age", k=14), cat("region"), interaction(SplineCategorical("age", "region"))],
    selection_penalty=0.01,
)
model.fit(df, y, sample_weight=exposure)

Auto-detected interaction types#

Parent types

Interaction class

Geometry

Spline + Spline

TensorInteraction

ti()-style interaction, excluding parent main effects

Spline + Categorical

SplineCategorical

Reference-coded, unpooled spline deviations

Polynomial + Categorical

PolynomialCategorical

Reference-coded polynomial deviations

Numeric + Categorical

NumericCategorical

Per-level slopes

Categorical + Categorical

CategoricalInteraction

Cross-level indicators

Numeric + Numeric

NumericInteraction

Product term

Polynomial + Polynomial

PolynomialInteraction

Tensor-product polynomial term

The dispatcher is intentionally type-based. With one spline it selects the appropriate spline interaction; with no spline it selects the matching numeric, polynomial, or categorical geometry. Full tensor-product te() and thin-plate tp() APIs are not currently exposed.

An OrderedCategorical parent participates as a spline on its mapped level scores — the same axis its own main effect uses — so OrderedCategorical + Categorical builds a SplineCategorical and OrderedCategorical + Spline builds a TensorInteraction. OC-parented tensors always use the exact prediction path: fit-time discretization is skipped for them, because the margin already lives on at most one score point per level and there is nothing for binning to compress. Such pairs also screen — as ti and spline_cat rows on the mapped scores; see Interaction Screening.

Choosing a factor-varying curve#

SplineCategorical and FactorSmooth answer related but different questions:

Need

API

Main spline

Sparse-level behavior

Reference-coded fixed interaction

SplineCategorical

Model-dependent

No pooling

Fully penalized random curves

FactorSmooth(..., basis="fs")

Optional

Wiggle and null-space directions shrink

Centered deviation curves

FactorSmooth(..., basis="sz")

Required

Wiggle shrinks; polynomial null space remains (shrinks with select=True)

Here basis= chooses the factor-smooth construction. kind= chooses the continuous marginal spline family; this release supports kind="ps" for both factor bases. SZ means “sum to zero”: it is a continuous rating curve for each level, not a finite two-way rating table.

Fully penalized FS curves#

from superglm import FactorSmooth, SuperGLM, interaction, s

model = SuperGLM(
    family="poisson",
    terms=[
        s("DrivAge", kind="ps", k=8),
        interaction(FactorSmooth("DrivAge", group="Region", basis="fs", kind="ps", k=6)),
    ],
    selection_penalty=0.0,
)
model.fit_reml(df, y, offset=log_exposure)

The same model as a features dict:

from superglm import FactorSmooth, Spline, SuperGLM

model = SuperGLM(
    family="poisson",
    features={"DrivAge": Spline(kind="ps", k=8)},
    interactions=[FactorSmooth("DrivAge", group="Region", basis="fs", kind="ps", k=6)],
    selection_penalty=0.0,
)

FS is analogous to mgcv’s bs="fs": every level has a complete curve and shared wiggle/null-space smoothing components. It can be fitted without the global Spline; when both are present, identifiability is supplied by the full FS penalty, but the construction does not force the global curve to do as much work as possible.

Sum-to-zero SZ deviations#

from superglm import FactorSmooth, SuperGLM, interaction, s

model = SuperGLM(
    family="poisson",
    terms=[
        s("age", kind="ps", k=7, m=2),
        interaction(FactorSmooth("age", group="region", basis="sz", kind="ps", k=6, m=2)),
    ],
    selection_penalty=0.0,
).fit_reml(X, y)

SZ is analogous to mgcv’s bs="sz" with one shared smoothing parameter (two, wiggle and null, with select=True). At every value of age, the fitted regional deviations sum exactly to zero, so the required global Spline is the portfolio curve and the SZ term describes departures from it. Adding the global spline is therefore intended, not a source of duplicate main-effect geometry.

group= names the factor whose levels receive curves. It corresponds to the factor argument in mgcv’s s(x, factor, bs=...); it is not a generic by= multiplier. The group needs no term of its own: the factor smooth reads the column itself. A term on the group is redundant: both bases give every level its own intercept (FS in its penalized null space, SZ in its uncentered level curves), so a term that depends on the level alone repeats columns the factor smooth already has. mgcv’s documentation says the same of bs="sz": adding the factor’s main effect gives a rank-deficient model. SuperGLM rejects a Categorical or RandomEffect on the group, cat(...) or re(...) in terms=; any other term there, and any term in SuperLSS, still fits, with a warning that names the term to drop. A random effect for a different column is supported.

Beside an sz term, predict prices a held level (one with no claims, no weight, or whose line separates) at the group term’s mean over the levels the data identify, whatever value the fit left it. The group term’s relativities(), term_inference(), reconstruct_feature() and term_importance() read a held level there too, and factor_smooth() lists held levels in its diagnostics as held_levels. The term’s coefficients for a held level are not an estimate; drop the redundant term to avoid reading them.

Level universes are inherited, never redeclared#

A Categorical-parented interaction — SplineCategorical, CategoricalInteraction, NumericCategorical, PolynomialCategorical — takes its level universe from the parent term at build time. Whatever bound the parent (a levels= list, the column dtype, a cross_validate full-frame bind, or plain inference) binds the interaction too, along with the parent’s pinned levels and its unseen= policy. There is no levels= on the interaction itself: one declaration on the main effect is the whole story, and a second one would be a second thing to keep in step.

A level pinned on the parent gets no block in the interaction either — no all-zero columns for a level with no data — and predicts through the parent’s base, so the interaction contributes nothing for those rows. See Feature types for the sources and the pin semantics.

FactorSmooth is the one exception to “every source works everywhere”: it is not Categorical-parented, and in this release only the explicit FactorSmooth(levels=...) channel reaches it — the column-dtype and cross_validate/bind_levels full-frame channels bind main-loop features only. Declare its universe explicitly when folds may drop a level. With basis="fs" an empty declared level is absorbed by the penalty (its curve shrinks to the population); basis="sz" rejects empty declared levels unless the term has select=True, because a level with no rows makes the centered system numerically singular (measured: minimum penalized eigenvalue collapses from ~0.6 to ~4e-10). With select=True every level’s line is penalized, so an empty declared level is allowed and predicted at the population curve.

Prediction behavior#

Known levels receive their fitted FS curve or SZ deviation. With the default unseen="population", an unseen level receives zero deviation; set unseen="error" to reject it with its label. Missing values always fail. FactorSmooth(levels=...) binds the grouping factor’s universe the same way Categorical does, so folds and refreshes share one set of curves; an empty declared level shrinks to the population smooth under basis="fs". Under basis="sz" it is refused, because the sum-to-zero contrast needs every level to carry rows, unless the term has select=True; then it is predicted at the population curve.

conditional = model.predict(test)
population = model.predict(test, random_effects="population")

random_effects="population" removes RandomEffect and FactorSmooth contributions while retaining fixed effects and the global spline. For SZ, that is the global curve, adjusted as described next when the training data cannot identify some levels.

Rows the training data do not determine#

When neither the training data nor a penalty separate two terms, as with a level whose rows all sit at one value of its own slope, predict still prices every row, and gives one NonEstimablePredictionWarning naming the rows that tell those terms apart (its rows attribute). Their price rests on how the fit split the terms rather than on the data. The test is R’s predict.lm check (rankdeficient = "warnif", tolerance 1e-6 of the row’s size). A direction a penalty fixes, such as a random effect’s level sum under its zero-mean prior, is determined and never warns. As in predict.lm, a row the fit’s rank decision treats as determined only up to its cut, a near alias it truncated, can warn too, a training row included.

Only a dense, unbinned fit is tested. These fits are silent, as they were before the test existed:

  • a binned fit (discrete=True, or a Spline(discrete=True));

  • a fit with a FactorSmooth term, basis="sz" or "fs", whose held and population levels have their own rules (described below);

  • a structured fit, and any model that does not carry the fit’s two rank records (one saved by an older superglm, say);

  • a fit whose columns sit so far from zero, against their spread, that float64 cannot resolve the test (a column near 2**40 that varies by a few units).

The rating tables carry no mark.

SZ levels the data cannot identify#

Some SZ levels do not carry enough information for their whole curve:

  • a level whose training rows all have zero weight;

  • a level with fewer distinct values of the smooth’s variable than the penalty leaves unpenalized (with the default m=2, a single distinct value).

With select=True, only a level without weight is in this position. It is predicted at the population curve, and the report’s thin_levels and predict name it; the solver does not name it at fit. The population curve is the main effect, unless a plain sz term on the same group has a thin or separated level, or does not know a declared level: the two terms then share the levels they leave out and hold, and the selected term’s population is the mean of the levels both identify. The rest of this section describes terms without select=True.

For such a level, part of its curve can trade places with the global curve without changing any fitted value, so the data do not decide that part. A fit_reml fit on the structured solver names these levels when it fits; every fit records them, and predict names them when it meets them. At prediction:

  • a level with data keeps the value its rows identify, so predictions on its training rows reproduce the fit;

  • where its rows say nothing (with m=2, its slope), the level follows the shape of the population curve;

  • a level without weight is predicted at the population value;

  • each call to predict that meets such a level warns once and names it;

  • every other level predicts exactly as fitted.

The population curve is the one around which the identified levels’ unpenalized parts (straight lines, with m=2) average to zero, as if the other levels were not in the model. factor_smooth(), reconstruct_feature() and relativities() report on the same footing: each level’s curve is its deviation from the population curve, and the global curve is the population curve.

If every level is in this position, or has a line that separates the response (next section), no level identifies the population curve. Its unpenalized part is then set by a convention: each level’s unidentified part is zero. Away from the levels’ own values, the curves still depend on where the fit landed along the global smooth’s unpenalized curve, wherever that curve is not a polynomial. The fit warns, and the warning names the remedy: select=True on the term, described below.

To give a level its own curve, give it weighted rows at enough distinct values.

SZ levels whose line separates the response#

Under a log link with zero responses (Poisson, Tweedie, negative binomial), or under a binomial link, an SZ level’s unpenalized straight line can separate the response. Two examples are a level with no claims, and a level whose claims all sit at one value of the variable with its other rows to one side. The likelihood then keeps increasing along that line, so the level’s fitted values move toward zero (or one) for as long as the fit runs.

  • The fit warns with a SeparationWarning that names these levels and the remedy, select=True on the term.

  • separation="ignore" silences the warning; separation="error" does not refuse the fit for this case.

  • The population curve leaves these levels out of its average, so it does not follow their lines.

  • predict does not follow those lines either: where the fit stopped along a line says nothing about the data, and away from the level’s own rows the line can rise as steeply as it falls there.

  • Along that line the level follows the shape of the population curve, and it keeps what its other rows identify. A level whose claims all sit at one value keeps its fitted value there.

  • A level whose every row is on the boundary, such as a level with no claims, is predicted at the population curve.

  • Each call to predict that meets such a level warns once and names it.

To give such levels finite estimates, pass select=True to the term, or use basis="fs".

Penalizing SZ levels’ lines: select=True#

FactorSmooth("age", group="region", basis="sz", select=True)

select=True adds a second penalty to an SZ term. It penalizes every level’s straight line (with m=2; its polynomial part in general), with a smoothing parameter of its own named null (for example age:region:sz:null), and REML estimates it as it estimates the others. This is the null-space penalty of mgcv’s select=TRUE (Marra and Wood, 2011), and it treats the levels’ lines as random effects, as basis="fs" does.

The option belongs to the term, not to the data: a term with select=True always carries the penalty, and a term without it never does. Two fits of the same term on slightly different data, such as cross-validation folds, are therefore the same model.

  • Every level’s curve is finite, including a level whose line separates the response: a level with no claims sits below the population curve by as much as its rows and the other levels support.

  • When every level is thin, the global curve is fitted through the trend across the levels, and the fit is the same on every solver.

  • The population curve is the global curve, unless a plain sz term on the same group has a thin or separated level, or does not know a declared level. The terms then share the levels they leave out and hold, and the population is the mean of the levels both identify. Every level with data predicts its own fitted curve. A level whose rows all have zero weight, or a level declared through levels= with no rows, is predicted at the population curve, and predict names it.

  • No level’s line is unpenalized, so the fit gives no SeparationWarning that names this term’s levels, and no warning for thin levels.

  • The solver’s separation warning describes the fitted model only, so a trial of the smoothing-parameter search that lets a line run off before its smoothing parameter grows does not report one. The final curves are bounded.

  • The penalty shrinks every level’s line, not just the separated ones, so it changes the other levels’ curves and the term’s effective degrees of freedom.

  • The smoothing parameter needs enough levels to estimate. With very few levels and one of them separated, REML can drive it to its lower bound and report that it did not converge. The lines are still finite there.

  • A lambda policy given as one LambdaPolicy for the whole term applies to both wiggle and null. A dict of policies can name either; a component it leaves out is estimated.

  • FactorSmooth raises a ValueError for a policy that fixes wiggle or null at zero, which would leave part of every level unpenalized. Use select=False for unpenalized lines.

  • basis="fs" already penalizes every level’s polynomial part, so select=True applies to basis="sz" only.

Groups with sparse levels#

A level with few rows, or few claims, gives an unpenalized part of its curve little or nothing to estimate it from. On the first 3,000 training policies of the French motor book, with a vehicle-age curve by region, 12 of the 22 regions had no claim or had all their claims at a single vehicle age. These are the held-out results on the remaining policies (Poisson, claim frequency):

How the region enters

Held-out deviance

Gini

FactorSmooth(basis="sz"), lines unpenalized

40,604

0.076

FactorSmooth(basis="sz", select=True)

34,201

0.163

FactorSmooth(basis="fs")

34,332

0.182

re("Region"), no factor smooth

34,201

0.163

cat("Region"), no factor smooth

79,099

0.075

cat("Region") with a vehicle-age curve by region (SplineCategorical)

80,724

0.084

The select=True and re("Region") rows are different models that nearly coincide: select=True shrinks each region’s vehicle-age curve to about an intercept, which is what re() fits, and their deviances are 34,200.7 and 34,200.8.

  • For a curve by level, pass select=True to an SZ term or use basis="fs". Both penalize every level’s line, so a sparse level stays close to the population curve.

  • For a level effect alone, use re(). It shrinks a sparse level toward the average.

  • A plain categorical level with exposure and no claim has no finite effect. The fit warns, the level is predicted close to zero, and predict names it. The same holds for a spline-by-category interaction, whose levels take their constant from the categorical main effect.

  • A numeric or polynomial curve by category gives each level its own slope or curve. When a level’s claims cannot fix it, the fit warns, and predict and the reported curves hold that level’s curve flat beyond the values its rows covered.

  • To keep a categorical term, merge sparse levels into similar ones with Categorical(grouping=...).

  • When no level of a group is identified, every level being thin or separated, the population curve is a convention, not an estimate. With several sz terms on that group it is not unique, because the fit splits each level’s constant between the terms. Use select=True or basis="fs" there.

Separated cells: exposure without response#

A crossed categorical cell that carries exposure but whose responses all sit on the response boundary — no positive claim under a log-link Tweedie or Poisson fit — has no finite maximum-likelihood effect. The likelihood keeps improving as the cell’s coefficient walks toward −∞, so IRLS drifts until the objective stagnates and the cell’s fitted values collapse to zero. The same applies to a main-effect level with exposure and no positive response; interactions just make such cells far more common. This is the classical nonexistence problem for log-linear MLEs (Haberman 1974; Fienberg & Rinaldo 2012), the binomial version of which is complete/quasi-complete separation (Albert & Anderson 1984).

The fit is checked for this at build time, before any IRLS iteration, controlled by the separation constructor parameter:

model = SuperGLM(
    features={"make": Categorical(), "region": Categorical()},
    interactions=[("make", "region")],
    separation="error",  # "warn" (default) | "error" | "ignore"
)
  • "warn" (default) fits anyway and, before the fit is installed on the model, emits one SeparationWarning. For each separated level or cell it gives its rows, their weight total when the weights are not all one, its exposure (the sum of exp(offset) over its rows, each row once, under a log link with an offset), the response total its rows would expect at the base level’s rate, and the response total the fit gives them, which is where the fit stopped, not an estimate. The base-rate figure is what predict gives those rows with the level set to the base (both parents to their base for a cell); it is left out when the base is itself separated, or when the move takes a row into a crossed cell no training row occupies, whose rate the data do not set. Both totals weight each row by its sample_weight, whatever weight_semantics says, and the line says so when the weights are not all one. On a log link, a level no crossed term involves also states its fitted factor against the base. A total past float64’s range reads “beyond float64”. It says what to do, with a grouping call for the first separated level. Raised as an error, the warning leaves the model’s previous fit in place.

  • "error" refuses the design with a SeparationError, before any fit.

  • "ignore" disables the check and every notice of it.

The fit keeps the level: its coefficient, its price in predict and its factor in the rating tables are what the fit reached. summary() flags its row SEP (the workbook’s Warning cell reads Separated, the editor’s summary SEP) and leaves its standard error, z, p-value and interval blank, as do term_inference() and relativities(with_se=True), for main effects and crossed cells: a Wald statistic has no finite reference there (Hauck and Donner 1977). Any other reported contrast that the rows outside separated levels and cells leave undetermined moves with it, and is flagged and blanked the same way: every relativity against a separated base, the intercept then, a parent’s main effect beside a separated cell in its base row or column. The test is Lenth’s estimability test (as predict reads its rows) on the term, its categorical parents and the intercept. Every other number is unchanged. centering="mean" centres on the levels whose contrast against the base is determined. With a separated base, every centred level stays blank: their covariance is the difference of entries the walk has grown to about 1e14. The default base, the most exposed level, avoids this. A rating-table block notes the factors summary() flags (a factor fixed at 1 is never one) and the separated levels or cells they move with, and predict warns once per call that reaches one, a row an unseen="base" label or a declared level with no rows prices there included.

Limits. A level separated only jointly with another term (two factors that coincide on the claim-free rows, or a slope by a claim-free category) is not flagged: the test covers a term, its categorical parents and the crossed terms beside it, and such cases keep the figures an unflagged fit shows. A model saved before these flags existed keeps its crossed-cell figures and its REML weak-identification labels until it is refitted. A binned (discrete=True) fit’s totals score the level’s rows exactly, as predict does, not through the fitted bins.

Remedies: collapse the affected levels into neighbours (Categorical(grouping=collapse_levels(X["make"], groups={"B+C": ["B", "C"]}))), model the crossed factor with a RandomEffect (its ridge bounds every cell), or bound a main effect with a fit-time cap (Constraint.fit.cap) or the term with a selection penalty. Penalised terms, and capped levels in fit and fit_reml, are exempt from the check because their optima are finite; fit_path fits without its caps, so it reports a capped level as separated. A crossed cell bounded only through a capped parent is still reported. That exemption covers these categorical cells only: the spline-by-factor hold described below applies to a term whatever penalty bounds it. A cell with few rows but at least one positive response is not separated and is never flagged — thin is not separated.

Rank and aggregate metrics cannot detect this failure

On a measured 5-fold comparison, a separated crossed interaction moved out-of-sample deviance by a factor of ~27,000 while normalised gini moved by 0.004 and balance actually improved. The collapse concentrates in a handful of rows, which rank metrics shrug off and aggregate balance averages away — only the likelihood notices, because only the likelihood is unbounded. A model-selection procedure scoring on gini and balance alone will ship a separated model without a single number looking wrong. Always include out-of-sample deviance (or another proper scoring rule) when interactions are on the table.

Separation the design scan cannot see — for example a numeric 0/1 indicator column whose active rows have no positive response — is caught on the fitted model instead: a fit whose returned linear predictor is pinned at the link’s overflow guard with an extreme working-weight range reports the same SeparationWarning once (or SeparationError under separation="error"). The trial solves of a smoothing-parameter, θ or power search are not reported; only the fit you get back is. The backstop reads the guard, offset included, so a row that its offset alone holds there (an exposure far below the rest, say) is reported too, although no coefficient runs off. This backstop fires only when the walk reaches the guard or exhausts a real iteration budget: a deviance-converged stop at moderate drift, and binomial-logit numeric indicators generally (the logit eta clip keeps the working-weight range below the trigger), still return quietly.

A level’s curve over a range where every response is 0#

A spline-by-factor term fits one curve per level. When every response of a level is 0 over part of the covariate’s range, for example a brand with no claims past vehicle age 22, the data there say the level’s mean is low but not how low. Only the curve’s smoothing parameter holds the curve back, and that parameter is chosen for the whole curve: a sharp feature elsewhere can make it small, and the curve then falls toward a zero mean on those rows.

The build finds such ranges, with or without discrete=True and at any n_bins, and holds the curve there. Below, a response “off the boundary” is a nonzero one; for a binomial response it is one strictly between 0 and 1, since a range where every response is 1 is held the same way.

  • Before the first and past the last covariate value where the level has a response off the boundary, the curve keeps its value at that point, in the fit and in predict(). A spline does the same past its training range (extrapolation="clip").

  • Between two values with responses off the boundary, the curve takes the smoothest path that joins its two sides.

  • The factor’s base level has no curve of its own: its curve is the main effect’s, which every level shares. Its ranges are found on the main effect alone and named as approximate, “left to the smoothing penalty”, but not held, and separation="error" does not refuse on them. To have them held, choose a base that does not separate.

A SeparationWarning names the term, the level and the range, for example 'VehAge:VehBrand', level 'B12': VehAge 23 to 48 (21 rows, total weight 15.04, every response 0): held at its value at VehAge 22. A range the fit cannot hold is named too, as “left to the smoothing penalty”. The hold applies whatever else bounds the term, a selection penalty included. separation="ignore" leaves these curves free, as earlier versions did, and separation="error" refuses the design. To let the data shape these ranges, merge the level into a similar one or drop the interaction.

Hierarchical make/model/trim data#

Sparse nested vehicle levels can be represented with explicit composite IDs, for example make_model and make_model_trim, and separate FS terms. Their penalties are estimated independently: this is partial pooling of each curve, not a correlated nested random-effect covariance.

Use one SZ term at a chosen hierarchy level when centered deviations are the scientific target. Stacking make/model/trim SZ terms is not advertised as a hierarchical decomposition in this release, because each constraint is global rather than sum-to-zero within its parent. FS is usually the clearer first choice for sparse nested levels.

See Credibility terms for reporting, prediction intervals, and structured-solver behavior.