rheon.spec.ew_class¶
- rheon.spec.ew_class(name: str, *, features: list[str], label: str, classes: list[str], covariance_type: Literal['full', 'tied', 'diag'] = 'full', precision_prior: float, window_size: float | timedelta | str | _Expr | None = None, closed: Literal['right', 'both'] = 'right', snapshot_every: float | timedelta | str | _Expr | None = None, max_rows_between_snapshots: int | None = None, window_budget: dict[Literal['thin', 'refuse'], float] | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
A Gaussian classifier on exponentially weighted moments, one set per class.
Use it to predict a row’s class, from a column of classes, by quadratic discriminant analysis, linear discriminant analysis or Gaussian naive Bayes (
covariance_type). Usehmm()where no column gives the class and the model must infer a hidden regime, andkmeans()for clusters with no classes at all.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weightandgroup, are inrheon.spec. Alabelcolumn takes the place oftargets.fit_intercepthas nothing to act on, as there is no regression. No diagnostic that reads residuals applies, and each such switch is refused by name:emit_sigma,emit_metrics,conformal,emit_driftand every other switch that reads residuals. So isemit_feature_health, since this model fits no coefficients of its features. This model’s own:labelThe column that holds each row’s class, read as a key: any dtype with a string form, so
["0", "1"]for an integer column and["true", "false"]for a boolean one. On a row whose class is null, the model predicts the row and moves its clock, and no class learns from it. That is also how to predict rows whose class arrives late: null the class, keep the features.classesEvery value the label can hold, in the order the
p_<class>fields are written. Required, at least two, each named once and none"". A value it does not list is refused, with an error naming the row.covariance_typeThe shape of each class’s covariance, and the work a row takes, for
kfeatures:covariance_typethe shape
per row
"full"(the default, the one shape that sees each class’s correlation between features)a covariance per class (quadratic discriminant analysis)
each class keeps its Cholesky factor, and only the class a row moves is refactored: one
k x kfactorization per learned row. Under awindow_sizeevery class’s covariance moves on every row, so every class is refactored"tied"the weight-averaged one, so the decision boundaries are linear (linear discriminant analysis)
one factorization
"diag"the variances alone, which cannot see a correlation (Gaussian naive Bayes)
knumbers a class to keep and move on a row, where the other two keepk x kprecision_priorA ridge on every class covariance, in the features’ squared units, so that the first rows of a class, whose sample covariance is singular, are predicted with a finite covariance the same in every direction. Required, and finite and above 0: every row is predicted through each class’s inverse covariance, where
ew_cov()inverts only forpartial_corrandmahal. It washes out as the class fills in (The prior scale in Notes).window_size,closedA hard window on the rows each class’s moments are computed from, in clock units, as for
ewridge(): a rowwindow_sizeold or older counts toward no class, andclosed="both"keeps the one exactly that old. A hard window drops old rows entirely, so a classifier can follow class means that move: over a long history two regimes average together and the predicted classes go to chance.weight_sumis the weight inside the hard window, in the output and in themin_weightgate, and a row is predicted against the class moments of the rows inside the hard window.snapshot_every,max_rows_between_snapshots,window_budgetAs for
ewridge():snapshot_everyspaces the hard window’s snapshots on the clock, in clock units,max_rows_between_snapshotscaps the rows between them, whichever comes first, andwindow_budgetbounds each ring in MiB and thins or refuses past the bound. Each is refused withoutwindow_size.
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. docs/OUTPUTS.md#ew_class gives each field’s type and when it is null:classThe class with the largest posterior probability (the first, on a tie), an
Enumofclassesin their order. Null beforemin_weightand while no class has been seen.p_<class>One per class in
classesorder: its posterior probability, so thep_fields sum to 1. Exactly 0 for a class no row has carried yet.weight_sumThe weight the model has accumulated before the row and before the row’s own decay, over every row it accepted, whether its class is null or not.
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_min_weightuntilweight_sumreachesmin_weight. Before any row has carried a class,classis null, and so is the reason onceweight_sumreachesmin_weight.coefThe class means after the row is learned, one per class in
classesorder, each one entry per feature.coef_index()lays the list out as(class, feature), and a class not yet seen is null.
Raises
As every builder does (
rheon.spec),TypeErrorfortargets, since this model takeslabel, andValueErrornaming the problem for:fewer than two
classes, a class listed twice, or a class named"";a
covariance_typeother than"full","tied"or"diag";a
precision_priornot finite or not above 0, and awindow_sizenot finite or not above 0;a
labelalso listed as a feature;a
closedother than"right"or"both", asnapshot_everybelow 0 or not finite, amax_rows_between_snapshotsbelow 1, and awindow_budgetthat is not one key,"thin"or"refuse", or whose MiB is not above 0;closed="both",snapshot_every,max_rows_between_snapshotsorwindow_budgetwithoutwindow_size;a switch that reads residuals, such as
emit_sigma, andemit_feature_health.
And, from a call that learns,
ValueErrorfor a class not inclasses, naming the row.The update
Per row,
wis the row’s weight,λ = 0.5 ** (Δclock / half_life)its decay (lam ** Δclockunderlam), andxits features.Δclockis the clock’s step since the last row the model did not skip, capped atgap_cap, orsession_gapat a session change. Each classckeeps a weightn_c, a meanmu_c, a centered covarianceC_cand a prior scales_c. Before a row is learned, it is predicted against every class seen:pi_c = n_c / sum_c' n_c' omega_c = precision_prior * s_c M_c = C_c + omega_c I ("full") M = sum_c pi_c (C_c + omega_c I) ("tied") M_c = diag(C_c) + omega_c I ("diag") l_c = ln pi_c - 1/2 ln det M_c - 1/2 (x - mu_c)' M_c^-1 (x - mu_c) p_c = exp(l_c - max_c' l_c') / sum_c' exp(l_c' - max l)Then the class of the row learns it:
n_c <- λ n_c + w mu_c <- mu_c + (w / n_c) (x - mu_c) C_c <- weighted Welford on (x - mu_c_old)(x - mu_c_new)' s_c <- s_c * λ n_c_old / (λ n_c_old + w) (stays 1 on the class's first row) n_c' <- λ n_c' every other class c' weight_sum <- λ weight_sum + w
Example
This code learns two classes,
aaround(0, 0)andbaround(2, 1), prints the class means found, and predicts a row at each planted mean:import numpy as np rng = np.random.default_rng(3) lab = rng.choice(["a", "b"], 4_000) x0 = np.where(lab == "a", 0.0, 2.0) + rng.standard_normal(4_000) x1 = np.where(lab == "a", 0.0, 1.0) + rng.standard_normal(4_000) pl.DataFrame({"x0": x0, "x1": x1, "lab": lab}).write_parquet("classes.parquet") cl = rp.spec.ew_class( "cl", features=["x0", "x1"], half_life=float("inf"), label="lab", classes=["a", "b"], covariance_type="tied", # one shared covariance: a linear boundary precision_prior=0.1, # lets a class be predicted from its first row ) bank = rp.ModelBank([cl]) bank.fit(pl.scan_parquet("classes.parquet")) # learn every row, keep no output means = bank.coef().pivot(on="term", index="class", values="coef") for r in means.iter_rows(named=True): print(f"class {r['class']}: mean ({r['x0']:.2f}, {r['x1']:.2f})") new = pl.DataFrame({"x0": [0.0, 2.0], "x1": [0.0, 1.0], "lab": [None, None]}) for r in bank.predict(new).unnest("cl").iter_rows(named=True): print(f"at ({r['x0']:g}, {r['x1']:g}): class {r['class']}, p_b {r['p_b']:.2f}")
class a: mean (0.01, -0.01) class b: mean (1.98, 1.00) at (0, 0): class a, p_b 0.08 at (2, 1): class b, p_b 0.92
See also
ew_cov(), the moments each class keeps, for one set of rows.hmm(), for a regime that no column names.kmeans(), for clusters with no classes.
Notes
The other classes. A row moves only its own class’s mean, covariance and prior scale. The other classes’ weights decay, which moves
pi_c.weight_sumcounts every row the model accepted, whatever its class, somin_weightmeans the same number of rows as in every other model. A row with a null feature is skipped and learns nothing, and a row of weight 0 is predicted and moves no clock.The prior scale.
s_cstarts at 1 and shrinks byλ * n_c / (λ * n_c + w)on every row the class learns but its first, wheren_cis 0 and the scale stays 1, so the ridge washes out as the class fills in, exactly asew_cov()’sprecision_priordoes.