Mixture Components

Experimental.

Mixture-of-regimes support for state-space models.

A measure can have one or more MixtureComponent alternatives to its standard measurement model. Each component is an offset from the standard regime: in the component’s regime, an observation is the usual (state-dependent) measured-mean plus the component’s learned offset, with its learned variance added to the measurement-noise. This is particularly useful for rare outliers with a clear data-generating process (e.g. forecasting the activity of customers who usually have long visits but occasionally have very short ones), especially when forecasting with data-transformations that make these outliers problematic in the back-transform (e.g. if the customer duration data was log1p transformed, an outlier will increase the variance and so lead to implausibly large back-transformed forecasts).

The MixtureModel owns the components. Multivariate support is accomplished by enumerating the possible “combos” of regimes (e.g. [(measure1=standard, measure2=standard), (measure1=weird, measure2=standard), …] and so on). Regime probabilities are tracked jointly over this table, allowing p(measure_x=weird) to vary over time and across groups.

Optionally, groups can belong to latent classes (MixtureModel(..., classes=[LatentClass(...), ...])) with their own base-rates for each component – a discrete random effect on the base-rates, e.g. some customers have outliers much more often than others. The table of combos is then repeated once per class. Classes share the transition (it applies within each class), and a group never changes class, so its posterior over classes accumulates evidence over all of its timesteps, and carries over into forecasts.

class torchcast.mixture.RegimeTransition(num_combos: int)

Bases:

Base-class for how combo-probabilities evolve over time. Subclasses implement initial() (the combo-prior at the first timestep) and forward() (the combo-prior at the next timestep, given the combo-posterior at the current timestep).

Both receive base_probs, the long-run probability of each combo implied by the MixtureComponent base-rates: a (num_combos,) tensor (or, if any components have predictors, a (num_groups, num_combos) tensor, for the timestep that the combo-prior is for).

With latent classes (MixtureModel(classes=...)), the transition only sees the combos within a class (so num_combos is the number per class): the MixtureModel applies it to each class separately – to the combo-probabilities given the class, with that class’s base-rates (normalized within the class), as if each class of each group were a separate group ((num_groups * num_classes, num_combos) tensors) – and scales the result by the probability of the class. So groups never change class, and the classes share the transition’s parameters, differing only in their base-rates.

initial(base_probs: Tensor, num_groups: int) → Tensor
Parameters:
  • base_probs – A (num_combos,) or (num_groups, num_combos) tensor.

  • num_groups – The number of groups.

Returns:

A (num_groups, num_combos) tensor of combo-probabilities.

forward(posterior: Tensor, base_probs: Tensor) → Tensor
Parameters:
  • posterior – A (num_groups, num_combos) tensor of combo-probabilities at the current timestep.

  • base_probs – A (num_combos,) or (num_groups, num_combos) tensor, for the next timestep.

Returns:

A (num_groups, num_combos) tensor of combo-probabilities at the next timestep.

class torchcast.mixture.StaticTransition(num_combos: int)

Bases: RegimeTransition

A static mixture: the regimes are independent across timesteps, so the regime-prior at every timestep is base_probs (whatever the previous posterior). It has no parameters. With latent classes (MixtureModel(classes=...)), the regimes are independent across timesteps given the class, which stays fixed: each group’s base-rates are a mixture over the classes, learned from all of its timesteps.

Parameters:

num_combos – The number of regime-combos.

class torchcast.mixture.StickyTransition(num_combos: int, stay_init: float = 0.1)

Bases: RegimeTransition

Each regime-combo i persists with probability stay_i; otherwise the next combo is drawn from a shared distribution b.

Rather than learning b directly, it’s derived so that the stationary distribution of the transition matrix T is base_probs (b ∝ base_probs * (1 - stay)). So base_probs keeps its interpretation as the long-run probability of each combo, and is also the initial distribution. With stay = 0 this reduces to a static mixture where the combo-prior is always base_probs (as in StaticTransition). (If the base-rates vary over time – components with predictors – then base_probs is the stationary distribution for the current predictors.)

Parameters:
  • num_combos – The number of regime-combos.

  • stay_init – Initial value for the probability of persisting in the current combo.

get_stay_prob() → Tensor
Returns:

A (num_combos,) tensor: the probability of persisting in each combo, stay.

get_matrix(base_probs: Tensor) → Tensor

The transition-matrix, for inspection and testing (forward() applies it without building it).

Parameters:

base_probs – A (num_combos,) tensor (so not for components with predictors, whose base-rates vary by group).

Returns:

The (num_combos, num_combos) transition-matrix.

class torchcast.mixture.MixtureComponent(measure: str, offset_init: float, prob_init: float, id: str, predictors: Sequence[str] | None = None, model_mat_kwarg_name: str = 'X')

Bases:

An alternative (‘weird’) regime for a single measure: a learned offset from the usual state-mean, and a learned increase in measurement noise.

Parameters:
  • measure – The measure this component applies to.

  • offset_init – Initial value for the component’s offset, relative to the standard regime’s measured-mean. For example, if you know you’re tracking anomalously low values, you can pick a value several standard-deviations below the global average).

  • prob_init – Initial value for the component’s base-rate, i.e. the long-run probability that an observation for measure comes from this component (exact when it’s the only component for this measure). With predictors, this is the base-rate when the predictors are zero.

  • id – A unique identifier (within the measure). '__standard__' is reserved for the standard regime.

  • predictors – Optional names of predictors of the component’s base-rate: each has a learned coefficient, added to the component’s logit (vs. the standard regime). E.g. a treatment that makes this regime more common. The predictors are passed to the model’s forward() as a (num_groups, num_timesteps, len(predictors)) tensor X (see model_mat_kwarg_name) – or, to use a different tensor than other consumers of X (e.g. a LinearModel), as {id}__X. Like the predictors of a LinearModel, they need to cover the forecast horizon too: the combo-prior for each timestep uses that timestep’s predictors.

  • model_mat_kwarg_name – The name of the forward() keyword-argument with the predictors (as for LinearModel). Default ‘X’.

property qualified_id: str

'{measure}.{id}': unique across all of a model’s components (id is unique within a measure).

get_logit(X: Tensor | None = None) → Tensor
Parameters:

X – If the component has predictors, a (..., len(predictors)) tensor.

Returns:

The logit vs. the standard regime: a scalar, or X.shape[:-1] with predictors.

property extra_var: Tensor

The variance this regime adds to the measurement-noise variance.

class torchcast.mixture.StandardRegime(measure: str)

Bases:

A measure’s standard regime – the usual measurement model, from which a MixtureComponent is an offset. Has the same interface as a component, so the regimes of a measure (e.g. in MixtureModel.core_combos) can be handled alike: zero offset, zero extra variance, and the fixed logit (0) that the components’ logits are relative to. (Created by the MixtureModel. Has no parameters: its values are buffers, so they follow .to().)

property qualified_id: str

'{measure}.__standard__'.

get_logit(X: Tensor | None = None) → Tensor
Parameters:

X – Ignored (the standard regime has no predictors).

Returns:

The fixed logit, 0, that the components’ logits are relative to.

class torchcast.mixture.LatentClass(id: str, membership_prob_init: float | None = None, relative_rate_init: Mapping[str, float] | None = None)

Bases:

A latent class of groups, for MixtureModel’s classes: groups in this class have their own base-rate for each component. Which class a group is in isn’t known; the model learns each class’s base-rates, and its posterior over each group’s class accumulates evidence over all of the group’s timesteps.

The first of a model’s classes is the reference: its base-rates are the components’ own (see MixtureComponent’s prob_init). Each other class’s base-rates are relative to the reference’s, via relative_rate_init.

Parameters:
  • id – A unique identifier (among the model’s classes).

  • membership_prob_init – Initial value for the prior probability that a group is in this class. Either given for all of the model’s classes (normalized to sum to 1), or for none (equal probabilities).

  • relative_rate_init – For classes after the first (required, with at least one ratio other than 1): a dictionary mapping a component’s qualified_id ('{measure}.{id}') to the initial value of its rate in this class, relative to the reference class – e.g. {'log_spend.high': .1} for a ‘high’ regime ~10x less common. Exactly, it multiplies the component’s odds vs. its measure’s standard regime (for a rare component, that’s about the same as multiplying its rate). Components not listed are initialized as in the reference class.

class torchcast.mixture.MixtureModel(components: Sequence[MixtureComponent], transition: RegimeTransition | None = None, joseph_form: bool = True, classes: Sequence[LatentClass] | None = None)

Bases:

Experimental. Mixture components for a state-space model: pass as the mixture argument of KalmanFilter (or BinomialFilter). Owns the MixtureComponent objects, the RegimeTransition, and the fixed table of regime-combos.

A combo is a tuple with one entry per mixture measure (in the order of self.mixture_measures): one of that measure’s regimes (see get_regimes()) – its StandardRegime, or one of its components. Measures without components are always in the standard regime, and do not appear in the table. The first combo is always all-standard.

Parameters:
  • components – The mixture components. Mixture measures are ordered by their first appearance here.

  • transition – A RegimeTransition, controlling how combo-probabilities evolve over time. Defaults to StickyTransition.

  • joseph_form – Whether the update-step for the non-standard regime-combos (those with any measure in a component’s regime) uses the Joseph form of the covariance update. (The standard regime’s update follows the model’s joseph_form.) With mixtures, the update runs once for each regime-combo, and the Joseph form’s intermediate results (kept for the backward pass) can dominate memory-use during training; False uses the simpler P - K @ H @ P instead – less memory (and compute), but less numerically robust. The non-standard combos are the safer place for this: a component’s extra variance makes their update better-conditioned, and their covariances only matter in proportion to their posterior probability. Default True.

  • classes – Optional LatentClass objects (at least two): latent classes of groups, each with its own base-rate for each component (a discrete random effect on the base-rates). Default None (no classes; i.e. one). With K classes, the table of combos is the core_combos repeated once per class (class-major: the first len(core_combos) combos are in the first class, and so on; the class id is the last part of each of self.labels), and the base-rates are learned per class: each component’s logit gets a per-class offset, and the classes have prior logits (both fixed at 0 for the first class, for identifiability). Otherwise the classes are the same: the transition is shared, applied within each class with that class’s base-rates (see RegimeTransition), so its num_combos is the number of combos per class (len(self.core_combos)); and groups never change class. The initial values come from each class’s membership_prob_init and relative_rate_init; the latter is required for all but the first class, since otherwise the classes would be symmetric. Only the bookkeeping of combo-probabilities grows with K: combos with the same observable regimes share a state-update and likelihood (see get_effective_combos()). Use Predictions.latent_class_probs for the posterior probability of each class.

get_next_prior(posterior: Tensor, base_probs: Tensor) → Tensor

The combo-prior at the next timestep: self.transition applied to the combo-posterior. With latent classes, it’s applied within each class (see RegimeTransition), so the probability of each class is unchanged.

Parameters:
  • posterior – A (num_groups, num_combos) tensor of combo-probabilities at the current timestep.

  • base_probs – A (num_combos,) or (num_groups, num_combos) tensor, for the next timestep.

Returns:

A (num_groups, num_combos) tensor of combo-probabilities at the next timestep.

validate(measures: Sequence[str], non_gaussian_measures: Sequence[str] = ()) → None

Called by the StateSpaceModel. Mixture measures must be measures of the model, with a gaussian likelihood.

Parameters:
  • measures – The model’s measures.

  • non_gaussian_measures – Measures whose likelihood isn’t gaussian (e.g. the binary measures of a BinomialFilter).

property num_combos: int

The number of regime-combos: len(core_combos), times the number of latent classes.

get_regimes(measure: str) → list[StandardRegime | MixtureComponent]
Parameters:

measure – A mixture measure.

Returns:

The measure’s regimes: its StandardRegime, then its components.

get_base_probs(component_X: Mapping[str, Tensor] | None = None) → Tensor

See _get_log_base_probs().

get_effective_combos(measures: Sequence[str]) → tuple[list[tuple[str, ...]], Tensor]

When only a subset of measures is observed, combos that differ only in unobserved measures are indistinguishable (they imply the same likelihood and the same state-update). So each ‘effective’ combo (aka a hypothesis) stands for one or more combos: those that are indistinguishable given measures.

Parameters:

measures – The measures observed.

Returns:

A tuple of two items. The first is a list of the unique ‘effective’ combos – each a tuple of the qualified_id of each component that’s in effect, i.e. for the observed measures that are in a non-standard regime; the first is always the empty tuple (all-standard). The second is a (num_combos,) long tensor mapping each combo to its effective combo (an index into the first item). The class doesn’t affect the likelihood or state-update, so each class’s combos map to the same effective combos.

get_combo_offsets(components: tuple[str, ...], measures: Sequence[str], like: Tensor) → tuple[Tensor, Tensor]
Parameters:
  • components – The qualified_id of each component that’s in effect.

  • measures – The (observed) measures.

  • like – A tensor whose dtype/device to use.

Returns:

Two (num_measures,) tensors: the offset to the measured-mean, and the variance to add to the measurement-noise, for each measure.

get_standard_probs(combo_probs: Tensor, measures: Sequence[str]) → Tensor

The probability that each measure is in its standard regime.

Parameters:
  • combo_probs – A (num_groups, num_combos) tensor of combo-probabilities.

  • measures – The measures to return probabilities for.

Returns:

A (num_groups, len(measures)) tensor with the probability that each measure is in its standard regime (always 1 for measures without mixture components).

prepare(kwargs: Mapping, init_combo_probs: Tensor | None, num_groups: int, num_timesteps: int) → tuple[Tensor, Sequence[Tensor], set[str]]

For a model’s forward(): the combo-prior for the first timestep, and the base-rates for the combo-prior at each timestep (base_probs[t]; time-varying if any components have predictors).

Parameters:
  • kwargs – The forward() kwargs, which may include the components’ predictors.

  • init_combo_probs – The combo_probs of forward()’s initial_state, if any (evolved one step by the transition, like the mean/cov of initial_state).

Returns:

(combo_prior, base_probs, used_keys), where used_keys are the kwargs used.

repeat_per_class(x: Tensor) → Tensor

For things computed per core-combo that don’t depend on the class (e.g. a combo’s offsets): repeat them for each class, class-major.

Parameters:

x – A (num_core_combos, ...) tensor.

Returns:

A (num_combos, ...) tensor.

class torchcast.state_space.MixtureOfNormals(labels: list, probs: Tensor, means: Tensor, vars: Tensor)

A batch of univariate mixtures of normals: the predictive distribution of a single measure with mixture components. The last dimension of each tensor indexes the mixture’s components; the first is the standard regime. (Each component’s mean and variance are the standard regime’s plus that component’s offset and extra variance.)

For example, to get the mean on the original scale of a log-transformed measure, back-transform each component and then mix: (mix.probs * torch.exp(mix.means + mix.vars / 2)).sum(-1).

Parameters:
  • labels – A name for each component ('__standard__', then the MixtureComponent ids).

  • probs – The probability of each component.

  • means – The mean of each component.

  • vars – The variance of each component.

cdf(value: Tensor) → Tensor

The cumulative distribution function at value, which broadcasts against the mixture’s batch-shape.

mean() → Tensor

The mean of the mixture.

quantile(q: float, num_iter: int = 60) → Tensor

The q-th quantile, found by bisection on the cdf.

var() → Tensor

The variance of the mixture (which includes the spread between the components’ means).