rheon.spec.hmm¶
- rheon.spec.hmm(name: str, *, features: list[str], n_components: int, precision_prior: float, covariance_type: Literal['full', 'tied', 'diag'] = 'full', learn: bool = True, transition_prior: float | None = None, transition: list[float] | None = None, means: list[float] | None = None, covs: list[float] | None = None, warm_rows: int | None = None, init: Literal['first', 'farthest', 'k-means++', 'lloyd'] | None = None, seed: int | None = None, exog_tvtp: str | None = None, tvtp_coef: list[list[float]] | None = None, prior_rows: float | None = None, warm_span: float | timedelta | str | _Expr | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
A Gaussian hidden Markov model of the features, filtered one row at a time.
Use it to ask which regime the stream is in: a transition matrix carries what the rows before have shown into each row’s answer. Use
ew_class()instead to ask which labeled class a row looks like, when a column names each row’s class.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weightandgroup, are inrheon.spec. This model readsfeaturesand takes notargets.fit_intercepthas nothing to act on, as there is no regression, and each switch that reads residuals is refused, as isemit_feature_health.min_weightwithholds what is reported, never what is learned: a row below it moves the filter and shows nulls. This model’s own:n_componentsThe number of hidden states, from 2 to 1,024, and required.
precision_priorA ridge on every state’s covariance, in the features’ squared units, finite and above 0. It is required here as it is for
ew_class(): a state’s centered co-moments start at zero, a zero matrix has no density, and every row is predicted through each state’s inverse. Undercovariance_type"full"or"diag"withlearn = Trueeach state’s covariance forgets toward a prior instead (prior_rows), and this ridge stands in for that prior only where every feature’s pooled variance is 0. Under"tied", and withlearn = False, it is the ridge. Keep it small against the data’s scale: with states given and not learned, a ridge of 1.0 on data whose variance is about 1.0 halves every correlation.covariance_type"full"(the default, the one shape that sees a regime’s correlation between features),"tied"or"diag", as forew_class().learnWhether the states and the transition counts move with the rows. Default
True.Falsewith no states given is refused: there would be nothing to filter with.transition_prior,transitionThe Dirichlet pseudo-count per cell (default 1, finite and at least 0), and an
n_components x n_componentsmatrix whose rows are distributions, to spread that mass over instead of flat, so the given matrix is the prior mean. A row with no counts is that mean, the given matrix or uniform,transition_prior = 0included. The prior pulls harder than its count suggests, and undertransition_prior = 0a state the first rows do not favor can get no count (The transition prior in Notes). Both are refused besidetvtp_coef, which learns no count.means,covsThe states given outright:
meansisn_components x dandcovsisn_componentsmatrices ofd x d(dthe number of features), both flattened row-major, finite, and given together. With them there is no warm-up. Eachcovsblock must be symmetric and positive definite, and the pair enters at one row’s weight. So underlearn = Truethe stream washes the given means out as it would one row, within about one half-life, and underlearn = Falsethe states are held exactly. Under"full"and"diag"withlearn = Truethe given covariances are also each state’s prior, worthprior_rowsrows for as long as the model runs (The update below). Pass them where the regimes differ in their covariance alone (A regime in the covariance alone in Notes).warm_rows,init,seedWithout given states, the first
warm_rowslearned rows (default 1,000, orn_componentswhere that is more, and at leastn_components) are held to seed the states from.kmeans()’init("lloyd"by default, or"first","farthest"or"k-means++") chooses centers among them withseed(default 0, at least 0).Noneis 0, so a run seeds the same states every time. The held rows are then replayed through those centers as hard assignments. A group with fewer rows than that never seeds, and every field butweight_sum,settled_frac,withheld_reasonandcoefstays null. The held rows must hold every regime, several times over (Seeding in Notes). Withmeansandcovsgiven nothing is seeded, and the three are refused.warm_spanThe warm-up over a span of the clock in place of
warm_rows: the learned rows from the first through the first row at leastwarm_spanafter it, once they are at leastn_components. A number of the clock’s units, or of rows where the spec has no clock, or a duration such as"1h"on a temporal clock; finite and above 0. The span is read off the rows’ exact stamps, and a row of weight 0 is no row of it, so on a clock of one unit a row it holdswarm_span + 1rows: the seeding ofwarm_rows = warm_span + 1, to the bit. The data decides how many rows that is, so they are held to 256 MiB as they come: past half of it a warning, once a group, and the row that would pass it stops the run with an error naming the group and the bytes. Refused besidewarm_rowsand beside given states.prior_rowsHow many rows of weight the prior each state’s covariance forgets toward is worth, under
covariance_type"full"or"diag"withlearn = True: finite and above 0, by default the number of features. The prior is the features’ pooled within-state variance on the diagonal, or, withcovsgiven, each state’s given covariance (The update below). A larger value pulls every state’s covariance harder toward it, and a returning state’s first rows read it the more. Refused under"tied"and withlearn = False, which take no prior.exog_tvtp,tvtp_coefA column named by this parameter, as
weightis, which need not be infeatures, whose valuez_tdrives the matrix instead:Pi_kl(t) = softmax_l(A_kl + B_kl z_t)from the fixedtvtp_coef = [A, B], eachn_components x n_componentsflattened row-major. The two are given together. The count-based learning is off under it, andAandBare fitted elsewhere. A row whoseexog_tvtpis null or not finite is filtered withz = 0, the base transition, and is otherwise an ordinary row.rheon.polars.ModelBank.predict()reads the column too.
Output
One output column, named after the spec, whose value in each row is a record of these fields, all but
coefread before the row is learned, so they are safe as features for that same row. docs/OUTPUTS.md#hmm gives each field’s type and when it is null:filtered_state<j>,predicted_state<j>The filtered probability of each state the rows before left (uniform before the first), and the probability predicted for this row from it.
stateThe most likely state under the predicted probabilities.
loglikThe row’s log-likelihood under the predicted mixture: low on a surprising row.
weight_sumThe weight the model has accumulated before the row and before the row’s own decay.
settled_fracHow far the model had come toward its steady state under decay before the row, null where nothing decays.
withheld_reasonWhy the row’s fields were withheld, null where they were not:
below_warm_rowson the rows held to seed the states from, andbelow_min_weighton a row whoseweight_sumis belowmin_weight, which takes precedence where both hold.coefThe state means after the row is learned, one row per state, each one entry per feature (
coef_index()). It reads zeros on the held rows before the last. The last held row reads the seeded means, since the states are seeded when it is learned.
Until the states are seeded, every field but
weight_sum,settled_frac,withheld_reasonandcoefis null. A row whose state densities cannot be evaluated is counted inrheon.polars.ModelBank.solve_failures()and leaves the filter where it stands. Each seeding run that stopped at its iteration cap is counted there too.Raises
As every builder does (
rheon.spec),TypeErrorfortargets, andValueErrornaming the problem for:an
n_componentsoutside 2 to 1,024, aprecision_prioror aprior_rowsnot finite or not above 0, and atransition_priorbelow 0 or not finite;prior_rowsundercovariance_type = "tied"or withlearn = False;a
covariance_typeother than"full","tied"or"diag", and aninitother than its four words;learn = Falsewithout states;meanswithoutcovsor the reverse, either of the wrong shape or not finite, or acovsblock that is not symmetric and positive definite;a
transitionthat is notn_components x n_componentsor has a row that is not a distribution;a
warm_rowsbelown_components, and aseedbelow 0;exog_tvtpwithouttvtp_coefor the reverse, and atvtp_coefwhoseAandBare notn_components x n_components;transitionortransition_priorbesidetvtp_coef, andwarm_rows,initorseedbeside given states;a switch that reads residuals, such as
emit_sigma,emit_metricsorconformal, andemit_feature_health.
The update
Hamilton’s filter, one row at a time. Before the row, from the filtered
pthe previous row left (uniform before the first), withmu_landSigma_lstatel’s mean and the covariance the row reads,Pithe transition matrix andxthe row’s features:p1_l = sum_k p_k * Pi_kl the predicted state f_l = N(x | mu_l, Sigma_l) the state's density loglik = log sum_l p1_l f_l the row's log-likelihood p_l <- p1_l f_l / sum the filtered state
Each state’s running sums then take the row at weight
w * p_l,wthe row’s weight. The responsibilities sum tow, soweight_sumfollows the same recursion as in every model. The transition matrix is learned from the filtered joint of consecutive states.tau_klis cellkl’s Dirichlet pseudo-count:transition_prior, ortransition_prior * n_components * transition_klwithtransitiongiven. So a never-visited row ofPiis still a distribution, and a row with no counts and no pseudo-count (transition_prior = 0) readstransition, or a uniform row without it.λ = 0.5 ** (Δclock / half_life)is the row’s decay (lam ** Δclockunderlam).Δclockis the clock’s step since the last row the model did not skip, capped atgap_cap, orsession_gapat a session change:N_kl <- λ * N_kl the row's decay, before the read Pi_kl = (N_kl + tau_kl) / sum_l (N_kl + tau_kl) the matrix the row reads xi_kl = p_k(t-1) Pi_kl f_l / sum over all pairs N_kl <- N_kl + w * xi_kl
Each state keeps its weight
W_l, its means and its mean-form co-momentsM_l, which take the row asew_cov()’s do, witha = W_l / (W_l + w p_l),b = w p_l / (W_l + w p_l)anddeltathe row’s deviation from the state’s mean before the row:M_l <- a M_l + a b delta delta',W_l <- W_l + w p_l.Under
"tied", and withlearn = False, the states’ weights and co-moments decay with the row before it is learned, andSigma_l = M_l + omega_l I, withomega_ltheprecision_priorridge as it has decayed with the state’s data ("tied"pools the states’M_lby weight).Under
"full"and"diag"withlearn = True, each state’s covariance forgets toward a prior instead: stabilized forgetting (Kulhavý and Zarrop, “On a general concept of forgetting”, 1993), which flattens the posterior toward a prior where exponential forgetting flattens it toward nothing. WithP0 = prior_rowsandpsithe features’ pooled within-state variance:W_l <- λ * W_l the row's decay, before the read Sigma_l = (W_l M_l + P0 diag(psi)) / (W_l + P0) W_l <- W_l + w p_l, M_l <- a M_l + a b delta delta' the row learned
A prior worth
P0rows stays worthP0rows, so a state that has won no rows for a while reads a broad density neardiag(psi), where under the decaying ridge it collapsed onto its first row back. A zero weight row and the gap it sits in read alike. With no decaySigma_lis scikit-learn QDA’sreg_paramshrinkage towarddiag(psi), withreg_param = P0 / (W_l + P0).psifollows the rows’ squared deviations from the states’ means before the row, weighted by the filtered state, at ten times the half-life (sstarts at the seeded states’ variances pooled by weight, andVat their total weight):e_i = sum_l p_l (x_i - mu_li)^2 V <- λ^(1/10) V + w s_i <- s_i + (w / V) (e_i - s_i) psi_i = max(s_i, 2^-100 max_j s_j) precision_prior where every s_i is 0
With
meansandcovsgiven, each state’s prior is the covariance it was given,G_l, every feature rescaled by how far the rows have moved from it:Sigma_l = (W_l M_l + P0 diag(sqrt(psi)) G_l diag(sqrt(psi))) / (W_l + P0) e_i = sum_l p_l (x_i - mu_li)^2 / G_l,ii in units of the given variances
with
sstarted at 1, so a state readsG_lon the first row, and again, at the scale the rows have by then, when it has no data left. Given covariances that are one diagonal matrix for every state are the diagonal prior exactly. What they say about each regime’s shape is trusted atprior_rowsrows for as long as the model runs, so given covariances of the wrong shape cost a returning state its first rows.Under
"full"with 13 features or more, each state keeps the Cholesky factor ofSigma_lin place of its co-moments, ass * L L'with the scalarskept between 1/4 and 1, and the row moves the factor by plane rotations, in timed^2, where the co-moments are factorized afresh, in timed^3. The prior’s share ofSigma_lchanges withW_l, a diagonal no rotation adds, so the factor holds the prior as factored,f, which decays with the data and is moved back, every coordinate at once by one factorization of each state, whenever any coordinate is more than 1/16 from its target. WithW'the weight after the row:Sigma_l = s L L' = (W_l M_l + diag(f)) / (W_l + P0) f_i <- λ f_i every row, with W_l f_i <- (1 + 1/32) P0 psi_i when any f_i leaves [15/16, 17/16] P0 psi_i s' = s (W_l + P0) / (W' + P0) the row learned L' L'' = L L' + (a w p_l) / ((W' + P0) s') delta delta' by plane rotations
So the factor form reads
Sigma_lwithin 1/16 of the prior’s share of it: a quadratic form within a factor16/15of the exact one’s, and the bound is reached only by a state with no data. Measured against the exact recursion carried in 512 bits, at 13 and 20 features and half-lives of 20 and 500 rows over 2,000 rows, a filtered posterior parted from it by at most 0.009. Below 13 features the factorization is the faster, and is kept, and reads the exact recursion.Example
This code plants two regimes, at -2 and +2, between which a chain switches once in 50 rows on average, and prints the share of the rows after the warm-up whose
stateis their true regime:import numpy as np rng = np.random.default_rng(7) regime = np.zeros(5_000, dtype=int) for t in range(1, 5_000): # switches 1 row in 50 regime[t] = regime[t - 1] if rng.random() > 0.02 else 1 - regime[t - 1] x = np.where(regime == 1, 2.0, -2.0) + rng.standard_normal(5_000) pl.DataFrame({"x": x, "regime": regime}).write_parquet("regimes.parquet") h = rp.spec.hmm( "hmm", features=["x"], half_life=float("inf"), n_components=2, precision_prior=1e-2, # required: a state starts with no spread warm_rows=500, # seeds the states from 500 rows ) out = pl.scan_parquet("regimes.parquet").rheon.fit_predict([h]).collect() found = out["hmm"].struct.field("state")[500:].to_numpy() true = out["regime"][500:].to_numpy() share = max(np.mean(found == true), np.mean(found != true)) # the states may be swapped print(f"rows in their true regime: {share:.2f}")
rows in their true regime: 0.97
See also
ew_class(), the same Gaussian densities against labeled classes.kmeans(), whoseinitseeds the states.docs/REGIMES.md, regime models measured on streams whose regimes are known.
Notes
Which regime are we in.
ew_class()classifies a row against labeled Gaussians. This does the same arithmetic with no labels: the state is hidden, and a transition matrix carries information from one row to the next. That is the difference between “which regime does this row look like” and “which regime are we in”, and the second is usually the question. The densities are Gaussian, asew_class()’s are; under"tied"they carry the same decayingprecision_priorridge, and under"full"and"diag"a stabilized prior in its place (The update).The clock.
Piapplies once per row whatever the clock between rows, so a weekend between two rows moves the chain one step. The counts decay on the clock but grow bywper row, so the staying probability rises with the rows’ density. A row readsPifrom the counts its own clock has decayed, so after a gap that takes them to nothing it reads the prior’s mean. A row of weight 0 is predicted, learns nothing and moves no clock, as in every model.The transition prior. The prior pulls harder than its count suggests. The counts are the filtered joint of consecutive states, read through the matrix being learned. A matrix pulled toward the prior mean is less sticky, so the filter credits more switches, and the counts follow it. The pull was measured on a sticky two-state chain, the states three noise standard deviations apart and learned from their true values. At
transition_prior = 10, 4,000 rows left the matrix 0.088 from the truth (the 95th percentile over 50 streams), where the pseudo-counts alone would move it about 0.006. The pull still fades with the rows, so the estimate is consistent. At the default the 95th percentile was 0.035, 0.016 and 0.0066 at 4,000, 16,000 and 64,000 rows, about halving with each fourfold increase.One limit is accepted: under
transition_prior = 0andlearn = Truethe counts are only what the rows put there. A state the first rows do not favor can get no count, and the learned matrix then keeps it out. That needs no extreme separation: on the same chain, 7 streams of 50 left a state under 10% of the counts, where the chain spends a third of its rows in it. None did at 0.1 or above. A prior above 0 keeps every move possible.Seeding. The held rows age as
weight_sumdoes, so the states start at the weightweight_sumsays, not at the rows’ raw weights. The seeding places the states where the held rows are, so a regime absent from them gets no state. Merging a regime with a few percent of the held rows into another regime’s state adds less to the k-means inertia than splitting a larger regime removes, so k-means gives the larger regime the spare state and the small regime shares one. Learning does not move a misplaced state out. Measured on three regimes three noise standard deviations apart, each lasting 50 rows on average, over 50 seeds of 5,000 rows: the worst share of rows in their true state was 0.95 from 1,000 rows, 0.81 from 500 and 0.46 from 50. The model holdswarm_rowsrows ofdvalues until the states are seeded, and the rows it holds report nothing.Limits. A single extreme row can be captured by one state, moving its mean far from the data. A state’s means are weighted means, which a row of zero responsibility leaves as they are, so a state that stops winning keeps its mean, and its covariance broadens toward the prior as its weight decays (under
"tied"it keeps its spread too). To guard against a captured state, raiseprior_rows(precision_priorunder"tied"), give the states withlearn = False, or clean the rows in the query before the bank.A regime in the covariance alone. A regime that lives only in the covariance needs the covariances to start from. The default seeding is k-means over the rows, and zero-mean states differ in nothing k-means can see, so it splits the rows by direction and the filter never recovers. On streams that stay in one of two zero-mean states, it puts 55% of the rows in the true state, the rows before seeding counted as right, and about half of the rows after seeding. The same filter given the true
covsput 98% there, without learning and when it went on learning alike: each given state forgets toward the covariance it was given, so a state that wins no rows goes on reading its own regime (docs/REGIMES.md §1). Passmeansandcovs, or a feature in which the regime is a shift in location.