superglm.SuperGLM#
- class superglm.SuperGLM(
- family: str | Distribution = 'poisson',
- link: str | Link | None = None,
- penalty: Penalty | str | None = None,
- selection_penalty: float | Literal['auto'] | None = None,
- spline_penalty: float | dict[str, float] | None = None,
- penalty_features: str | list[str] | None = None,
- features: Mapping[Hashable, FeatureSpec] | None = None,
- splines: list[str] | None = None,
- n_knots: int | list[int] = 10,
- degree: int = 3,
- categorical_base: str = 'most_exposed',
- interactions: list[tuple[str, str] | object] | None = None,
- active_set: bool = False,
- direct_solve: str = 'auto',
- discrete: bool = False,
- n_bins: int | dict[str, int] = 256,
- tol: float = 1e-06,
- max_iter: int = 100,
- convergence: str = 'deviance',
- retain_fit_state: bool = True,
- separation: str = 'warn',
- group_pricing: Literal['rank', 'spanned'] = 'rank',
- weight_semantics: Literal['prior', 'frequency'] = 'prior',
- n_jobs: int | Literal['auto'] = 'auto',
- max_memory: int | str = 'auto',
- *,
- terms: Sequence[TermInput] | None = None,
Bases:
objectPenalised generalised linear model with splines, group penalties, and REML.
Supports Poisson, Gaussian, Gamma, NB2, Tweedie, and Binomial families with group lasso, sparse group lasso, or ridge penalties. Smoothing parameters can be estimated via REML (
fit_reml) or cross-validation (cross_validate).- Parameters:
- familystr or Distribution
Response distribution. Strings
"poisson","gaussian","gamma","binomial"are accepted for parameter-free families. For parameterized families use Distribution objects:Tweedie(p=1.5),NegativeBinomial(theta=1.0), or thefamiliesmodule (e.g.families.tweedie(p=1.5)). For"binomial", y must be in {0, 1} andpredict()returns probabilities.- linkstr or Link, optional
Link function. Defaults to the family’s configured default link.
- penaltystr or Penalty, optional
Penalty type. One of
"group_lasso","sparse_group_lasso","group_elastic_net","ridge", or a Penalty object. Defaults toGroupLasso.- selection_penaltyfloat, {“auto”}, or None, optional
Regularisation strength for the group penalty (feature selection).
None(default) and0.0disable selection."auto"explicitly requests calibration to 10% of lambda_max at fit time.- spline_penaltyfloat or dict[str, float], optional
How strongly
fitsmooths each spline: the weight on its wiggliness penalty. Defaults to 0.1;fit_remlestimates its own weights. A float sets every term. A dict sets terms by name, and a term it does not name is not smoothed (weight 0.0):"x"sets every penalty of the main effectx, and"x:z"a tensor interaction that is not decomposed."x:<penalty>"sets one penalty of a term that has several:"x:wiggle"and"x:null"underselect=True,"x:d1"and"x:d2"underm=(1, 2), or"x:z:margin_x"for one margin of a tensor ("x:z:wiggly:margin_x"when it is decomposed)."x:c[a]"sets the levelaof a spline by the categoricalc; each level takes its own key.
The more specific key wins: under
select=True,{"x": 5.0, "x:null": 1.0}puts 1.0 on the null-space penalty and 5.0 on the other. A key that names nothing in the model is ignored.- penalty_featuresstr or list[str], optional
Restrict the selection penalty to specific feature or group names.
None(default) applies to all penalizable groups.- featuresmapping[hashable, FeatureSpec], optional
Explicit feature specifications mapping hashable column labels to feature objects (
Spline,Categorical,Numeric,Polynomial). Mutually exclusive with splines and terms. A list of term declarations belongs in terms;features=refuses one with aTypeError.- splineslist[str], optional
Deprecated auto-detection shorthand. Column names in this list are treated as splines and all other columns are inferred as categorical or numeric. Use explicit
features={"age": Spline(...)}for new code. Mutually exclusive with features.- n_knotsint or list[int]
Number of interior knots for auto-detect splines.
- degreeint
B-spline degree for auto-detect splines.
- categorical_basestr
Base level strategy for auto-detected categoricals.
- interactionslist[tuple[str, str] or interaction spec], optional
Pairs of feature names to interact, or explicit interaction specifications such as
FactorSmooth. Tuple interaction types are auto-detected from their parent feature specs. Mutually exclusive with terms.- termslist of str, BoundTerm, BoundInteraction or mapping, optional
Keyword only. The model’s terms as one list, in the form the
SuperLSSfamily helpers such asfamily.locationtake: a column name for a numeric linear term;s,cat,reandtermfor main effects;tiandinteractionfor interactions; and{column: spec}mappings, each standing for oneterm(column, spec)per entry, in the mapping’s order. For example,terms=[s("age", k=10), s("value", k=8), cat("region"), "density", ti("age", "value")]. A list gives the same model as the equivalentfeatures=andinteractions=, bit for bit, with main effects then interactions in declaration order. Cannot be combined with features, splines or interactions. A non-default n_knots, degree or categorical_base raisesValueError; set those options on each term instead, as ins("age", n_knots=8).- active_setbool
Use active-set cycling in the BCD solver.
- direct_solve{“auto”, “gram”, “qr”, “structured”}
Strategy for the direct IRLS solver (lambda1=0).
"auto"(default) uses compact structured elimination for large random-effect and factor-smooth (basis="fs"or"sz") terms and the Gram solver otherwise; the choice reads only the terms, their sizes and the grouping columns’ nesting, andresult.direct_fallback_reasonsays why Gram was chosen. A fit never switches solver: when the structured solver cannot proceed the fit stops with an error naming the cause, and"gram"fits the model with the dense solver instead."qr"uses QR on the materialised weighted design, backward-stable but O(n·p²) per iteration, for smaller datasets."structured"forces structured elimination for an eligible random-effect, FS or SZ block, and raises for any other model.- discretebool
Use discretized basis matrices for large-n REML (fREML-style).
- n_binsint or dict[str, int]
Number of discretization bins per feature when
discrete=True.- tolfloat
Convergence tolerance for IRLS / PIRLS. Default
1e-6. Can also be set per-call viafit(tol=...)orfit_reml(pirls_tol=...). Fit-time values take precedence. Larger values converge faster but may stop before near-separated coefficients have stabilised.- max_iterint
Maximum IRLS / PIRLS outer iterations. Default
100.- convergence{“deviance”, “coefficients”}
Convergence criterion.
"deviance"(default) stops when relative deviance change drops below tol — fast, since well-identified coefficients lock in early."coefficients"(experimental) stops when the maximum relative coefficient change drops below tol. May not converge for near-separated levels where the MLE is at −∞.- retain_fit_statebool
If True (default), keep training-scale fit state such as the fitted design matrix for later diagnostics. If False, eagerly computes compact inference state after fitting, then releases row-scale training caches while preserving prediction, summaries, and term confidence intervals.
- separation{“warn”, “error”, “ignore”}
Check for separated cells: categorical levels or crossed cells with exposure whose responses all sit on the response boundary (no positive response under a log-link Poisson fit, say), so they have no finite maximum-likelihood effect.
"warn"(default) fits them and, once the fit is solved, emits oneSeparationWarningnaming each with its rows, exposure, the response its rows would expect at the base level’s rate and the response the fit gives them, and the remedies;summary()flags them and leaves their standard errors and p-values blank."error"raisesSeparationErrorbefore fitting;"ignore"disables the check and its notices. Terms under an active selection penalty, and aCategoricalunder aConstraint.fit.capinfitandfit_reml(which enforce it, unlikefit_path), are exempt. The same mode governs the solver’s backstop for separation the build scan cannot see (read on the fit returned, or each pointfit_pathreturns, not on a search’s trial solves), the hold on a spline-by-factor level’s curve over a boundary-only range, and the warning for aFactorSmooth(basis="sz")level whose line separates (warned, never refused;select=Trueis the remedy). See the how-to Interactions, section Separated cells.- group_pricing{“rank”, “spanned”}
Dimension
p_gat which the selection penalty and the fallback df ledger price a group whose spec emits fewer columns than the term spans (a categorical interaction with empty or nested cells)."rank"(default) prices the emitted, identifiable width, following the group-lasso literature’s derivation ofsqrt(p_g)from the df of the group’s score statistic."spanned"prices the width the term spans, so cell pruning is a pure reparametrisation of the fit. The choice moves fitted results only for models that combine such an interaction with an active group penalty, and moves the reportedeffective_df/phi/AIC/BIC of any fit whose df falls back to the Breheny-Huang allocation.- weight_semantics{“prior”, “frequency”}
What
sample_weightsays about a row."prior"(default) reads it as an EDM prior weight – a statement of precision,Var(Y_i) = phi V(mu_i) / w_i– which is what you have when the response is an average:incurred / exposureweighted by exposure, or an average severity weighted by claim count. This is the reading R’sglmand glum give their single weight argument, and the one statsmodels callsvar_weights."frequency"reads it as a replication count, so an integer weight is exactly equivalent to repeating the row; that is statsmodels’freq_weightsand Stata’sfweight.The two agree only at
w == 1, and only the prior reading is a likelihood at fractional weights. At fixed smoothing they sharebeta;phi, Wald standard errors, residual degrees of freedom, AIC/BIC, and through REML the smoothing parameters and fitted surface all differ, as does learned knot placement. See the explanation Families and Dispersion Estimation.- n_jobsint or “auto”
The most threads a fit uses for its heaviest steps: forming the weighted Gram block by block and checking the rank of the design. Refits and inference on the fitted model (
summary,metrics,drop1,estimate_pand the like) keep it."auto"(default) uses theSUPERGLM_N_JOBSenvironment variable when it is set and the number of physical cores otherwise;1runs those steps on the calling thread. The fitted model does not depend on it: every thread count gives the same coefficients, bit for bit.- max_memoryint, str or “auto”
The working memory those threads may hold at once, in bytes or as a size such as
"4G". A fit starts fewer threads when each needs more than this budget allows, so it is the limit to set on a shared machine."auto"(default) usesSUPERGLM_MAX_MEMORYwhen it is set and otherwise a quarter of the machine’s memory, or of the container’s memory limit where that is lower.
See also
The methods and attributes of this class are grouped by task on the SuperGLM reference pages; each has its own page.