OrderedCategorical#

class superglm.OrderedCategorical(
values: dict[str, float] | None = None,
order: list[str] | None = None,
basis: _SplineBase | None = None,
base: Literal['most_exposed', 'first'] | str = 'most_exposed',
grouping: Any = None,
specials: list[str] | None = None,
)#

Bases: object

Ordered categorical feature smoothed by a spline over its level values.

Designed for continuous variables that arrive pre-binned into ordered categories (e.g. age bands, mileage bands). Maps category labels to numeric values and fits a smooth function through them, borrowing strength between adjacent levels. With fit_reml(), REML selects the smoothing parameter automatically — the effective degrees of freedom will typically be much less than the number of levels.

The smooth is configured by passing a Spline() specification as basis:

OrderedCategorical(
    order=["low", "medium", "high"],
    basis=Spline(kind="ps", k=6),
)
Parameters:
valuesdict[str, float] or None

Explicit mapping from category labels to numeric values (e.g. midpoints: {"18-25": 21.5, "26-35": 30.5, ...}). Mutually exclusive with order.

orderlist[str] or None

Ordered list of category labels. Numeric values are generated as linspace(0, 1, len(order)). Mutually exclusive with values.

basisSpline, Piecewise, Polynomial object, or None

The shape fitted over the ordered levels. Deep-copied at construction, so mutating the passed object afterwards changes nothing here.

Spline(...) gives the penalized smooth:

OrderedCategorical(order=[...], basis=Spline(kind="cr", k=6))

Omitting basis gives the default cubic regression spline, Spline(kind="cr", n_knots=5, penalty="ssp", select=False). In either form n_knots is clamped to n_levels - 1 with a warning. Spline(knots=[...]) may state knots as band names (knots=["Mi060", "Mi066"]), each resolving to that level’s value on the smooth’s axis; numeric entries stay axis values.

Piecewise(breaks=[...]) gives stated kinks with no smoothing penalty, an unpenalized main block like the specials= block. It evaluates on level positions 0..L-1 (values= sets the order but not the spacing). Breaks are band names, with integer positions as the escape hatch; degrees=[...] states one polynomial degree per segment (0 = flat tail), value-continuous at every seam. Rating tables stay one row per band at any degree. extrapolation is inert here, since every level lies inside [0, L-1].

Polynomial(powers=[...]) gives orthogonal ordinal contrasts (the contr.poly device) on the level positions, orthonormalized against the training exposure (SAS ORPOL’s weighted construction). powers= may be a non-contiguous subset, and each stated power reports its own z row in the summary.

basestr

Reporting reference level. "most_exposed" (default), "first", or a specific level name. This changes only the reported relativities and reference-adjusted intercept, not the fitted smooth.

specialslist[str] or None

Level labels held out of the smooth and fitted as free, unpenalized level effects — one indicator column and one coefficient each. Use for levels that are structurally different rather than merely sparse (a MISSING band, a structural zero); the penalty already handles sparse bands better than free levels do. A label listed here is removed from order/values if also present there, and never receives a numeric position on the smooth’s axis.

Examples

Using ordered level names (auto-spaced 0 to 1) with an explicit smooth:

OrderedCategorical(
    order=["18-25", "26-35", "36-45", "46-55", "56+"],
    basis=Spline(kind="ps", k=6),
)

Using explicit midpoints:

OrderedCategorical(
    values={"18-25": 21.5, "26-35": 30.5, "36-45": 40.5},
    basis=Spline(kind="cr", k=4),
)

Independent, unsmoothed level effects should use Categorical:

Categorical(base="most_exposed")
property kind: str#

Public factory kind of the inner spline ("ps", "cr", …).

property n_knots: int#

Knot count of the inner spline, after the n_levels - 1 clamp.

property degree: int#

B-spline degree of the inner spline.

property select: bool#

Whether the inner spline carries double-penalty selection.

property penalty: str | None#

Penalty type of the inner spline.

property constraint_kind: str | None#

Shape token declared on the inner basis ("increasing", …).

The constraint binds on the whole level axis, not only at the L level values: conservative, since published monotone-ordinal methods constrain the level effects (Rufibach, CSDA 54(6), 2010, Sec. 5) and sign conditions are sufficient but not necessary (Hofner, Kneib & Hothorn, Stat. Comput. 26, 2016, Sec. 3.3). A cap and a step limit bind at the levels, which are what gets priced (_level_rows). See docs/how-to/constrain-a-smooth.md.

property constraint_mode: str#

Whether the declared constraint binds at fit time or post-fit.

property constraint_rules: ConstraintRules#

The rule objects declared on the basis; empty for a basis that takes none.

rules_of reads these, so an ordered term answers with real rule kinds rather than the describe-string constraint_kind forwards.

shape_axis(
x: NDArray,
) → tuple[NDArray, NDArray[bool]]#

The inner basis’ numeric axis, and the rows that sit on it.

A shape constraint is stated over the inner spline’s level-score axis, so engines must resolve it through the wrapper as transform does. specials= rows have no coordinate and are absent from the first return value; the mask lets a caller drop the same rows from per-row weights.

property has_specials: bool#

True when one or more levels are fitted as free effects.

property basis_kind: str#

Kind of the inner basis: "spline", "piecewise" or "polynomial".

build(
x: NDArray,
sample_weight: NDArray[floating] | None = None,
) → GroupInfo | list[GroupInfo]#

Build design columns from ordered categorical data.

With specials=, returns two GroupInfos: the penalized spline block, then the unpenalized special-indicator block, an order _split_beta and transform rely on. When every special is pinned there is no second block.

transform(
x: NDArray,
) → NDArray#

Build design matrix for new data using learned parameters.

score(
x: NDArray,
beta: NDArray[floating],
) → NDArray[floating]#

Score the fitted ordered-categorical contribution directly on new data.

reconstruct(
beta: NDArray[floating],
) → dict[str, Any]#

Convert fitted coefficients to interpretable output.