rheon.spec.micro¶
- rheon.spec.micro(name: str, *, features: list[str], eps: float, beta_mu: float | None = None, max_clusters: int | None = None, prune_every: float | timedelta | str | _Expr | None = None, max_rows_between_prunes: int | None = None, macro_link: float | None = None, standardize: bool = True, scale_floor: float | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Density-based clustering over the feature columns, by small decayed summaries linked into clusters.
Use it where the number of clusters is not known, their shapes are not round (moons, rings), rows that belong to no cluster should be reported, or clusters appear and vanish as the stream moves. Use
kmeans()for a fixed number of clusters.Parameters
The model keeps a bounded set of small summaries (DenStream’s micro-clusters), each a decayed weight, center and radius, and reads clusters off them as the chains of established summaries (those that have reached
beta_mu) whose centers lie within a link distance of each other. The stream parameters every builder takes, such asclock,half_life,gap_cap,min_weightandgroup, are inrheon.spec. This model takesfeaturesand notargets.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 the rest. This model’s own:epsThe bound on one summary’s root-mean-square radius, per standardized coordinate (in the features’ own units under
standardize=False): a summary takes a row only while its radius stays withineps * sqrt(p)forpfeatures, so one value means the same at anyp. Required, finite and above 0. About 0.07 for two-dimensional shapes, 0.3 for well-separated Gaussians in twenty dimensions. Both ways to get it wrong show in the outputs:what you see
what it means
what to do
nearly every row is an
outlierandclusterstays nullepsis too small: no summary reachesbeta_mubefore it is prunedincrease
epsn_microis about the number of clustersepsis too coarse: the derived link, set from the summaries’ spacing, then bridges themlower
eps, or setmacro_link=2, which links only summaries that touchbeta_muThe weight at which a summary is established (DenStream’s potential micro-cluster), in rows of the stream’s mean weight. Default 3, finite and above 0. It is DenStream’s point density (DBSCAN’s
MinPts), so it is set against the arrival rate. With half-lifehandvrows in each unit of the clock the stream’s steady-state weight is about1.44 * v * h. So a summary meant to hold a sharesof the stream needsbeta_muof about1.44 * s * v * h.max_clustersThe cap on live summaries, at least 1. Default 200.
prune_every,max_rows_between_prunesA prune, which drops light summaries and links the rest, comes every
prune_everyclock units or everymax_rows_between_pruneslearned rows (at least 1), whichever comes first, assolve_everyandmax_rows_between_solvesschedule a regression’s solve. With neither, every 100 learned rows.prune_everyis finite and at least 0: a number of the clock’s units, a duration on a temporal clock ("10m"), or0for every row. The prune schedule in Notes gives the rules.macro_linkThe link distance
Las a multiple ofeps * sqrt(p):0links nothing, so each summary is its own cluster, and2links summaries that touch. Finite and at least 0. Left out,Lis derived at each prune from the spacing the summaries already show (The link in Notes).standardizeMeasure in units of each feature’s exponentially weighted standard deviation. Default
True.Falsemeasures in the features’ own units.scale_floorUnder
standardize, floor the metric’s variance at this fraction of the feature’s long-run variance, so a feature that goes quiet and then moves again is not infinitely far from every center. Default0.1, and0is the exponentially weighted variance alone. Finite and at least 0. Refused besidestandardize=False, which reads no variance to floor. The scale floor in Notes gives the rule.
Output
One output column, named after the spec, whose value in each row is a record of these fields, all read before the row is learned. docs/OUTPUTS.md#micro gives each field’s type and when it is null:
clusterThe label of the nearest established summary (
i64), null while there is none.distThe distance to that summary’s center, in units of each feature’s EW standard deviation under
standardize, and otherwise in the features’ own units.micro_idThe id of the summary this row goes to (
i64), the one it opens when none can take it.outlierWhether no established summary takes it (
bool).n_clusters,n_microLive clusters and live summaries (
i64), so churn is visible without comparing labels.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:
below_min_settled_fracwhilesettled_fracis belowmin_settled_frac, where that is set, thenbelow_min_weightwhileweight_sumis belowmin_weight, and null after. A row before any summary is established is not withheld: itsclusteranddistare null andoutlieris true.coefThe established summaries, one
[id, label, n, radius, c_1, ..., c_p]row each, flattened, as many rows as there are, socoef_index()does not apply.
Raises
As every builder does (
rheon.spec),TypeErrorfortargets, which this model does not take, andValueErrornaming the problem for:an empty
features;an
epsorbeta_munot finite or not above 0;a
max_clustersormax_rows_between_prunesof 0;a
prune_every,macro_linkorscale_floorbelow 0 or not finite, andscale_floorbesidestandardize=False;a switch of a diagnostic that reads residuals.
The update
A summary is
(n, c, nu2): its decayed weight, its center, and the exponentially weighted (EW) mean squared distance of its rows from the center (DenStream’s radius, with the fading function being the decay). Distances are measured in the metricmw_i = 1 / var_iunderstandardize,var_ifeaturei’s EW variance floored atscale_floortimes its long-run variance (The scale floor in Notes), andmw_i = 1understandardize=False. Soepsis a bound per standardized coordinate (or per unit withoutstandardize), and the bound on a summary’s squared radius in the metric isE = eps**2 * p.xis the row’s features,wthe row’s weight,w_barthe EW mean weight of the rows learned, andλ = 0.5 ** (Δclock / half_life)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. Each row:n_i <- λ n_i every summary j = the nearest established summary, if r2(j, w_bar) <= E else the nearest summary not yet established, if r2(j, w_bar) <= E else none: a new summary opens at x with weight w and the next id r2(j, v) = a nu2_j + a b |x - c_j|^2, a = n_j / (n_j + v), b = v / (n_j + v) nu2_j <- min(r2(j, w), E) c_j the center before the row c_j <- c_j + w / (n_j + w) * (x - c_j) n_j <- n_j + wA summary is established once
n >= beta_mu * w_bar, and is never demoted: it stays established until a prune drops it. Established between two prunes, it takes the label of the nearest established summary withinL, else its own id. A new summary is opened at the capmax_clustersby evicting the lightest summary not yet established, else the lightest established one. At each prune the model drops the light summaries (Pruning in Notes), then links the established summaries by single linkage: centers withinLof each other share a label.A row of weight
wis admitted where a row of the mean weight would be and absorbed with its full weight, so a constant multiple of every weight moves nothing. A zero-weight row is predicted, learns nothing and moves no clock.Example
This code clusters rows drawn around two planted centers, with a third that appears at row 3,000, and prints the clusters the model reads before and after it, and the share of rows it called outliers at the end:
import numpy as np rng = np.random.default_rng(6) centers = np.array([[0.0, 0.0], [5.0, 0.0], [0.0, 5.0]]) pick = rng.integers(0, 2, 6_000) # two blobs from the start pick[3_000:] = rng.integers(0, 3, 3_000) # a third appears at row 3,000 xy = centers[pick] + 0.3 * rng.standard_normal((6_000, 2)) pl.DataFrame({"a": xy[:, 0], "b": xy[:, 1]}).write_parquet("blobs3.parquet") mc = rp.spec.micro( "mc", features=["a", "b"], half_life=1_000.0, eps=0.1, # the spread one summary holds ) out = pl.scan_parquet("blobs3.parquet").rheon.fit_predict([mc]).collect() out = out.unnest("mc") for row in [2_999, 5_999]: print(f"row {row}: {out['n_clusters'][row]} clusters") print(f"outliers in the last 1,000 rows: {out['outlier'][-1_000:].mean():.1%}")
row 2999: 2 clusters row 5999: 3 clusters outliers in the last 1,000 rows: 0.0%
See also
kmeans(), a fixed number of clusters whose centers follow the stream.hmm(), Gaussian states whose next state depends on the last.
Notes
Pruning. A prune drops an established summary lighter than
beta_mu * w_bar, and a summary not yet established lighter than DenStream’sxi(age) * w_bar.ageis the clock that has passed since the summary opened, andhis the half-life:xi(age) = (2 ** (-(age + Tp) / h) - 1) / (2 ** (-Tp / h) - 1) = sum_{i <= age / Tp} 2 ** (-i Tp / h) where age / Tp is whole Tp = ceil(h log2(beta_mu / (beta_mu - 1)))That is the weight of a summary that had taken one row of the mean weight every
Tpclock units since it opened. Both count rows, as DenStream’s do: a stream with more rows to a clock unit fills its summaries faster. With no decay, or withbeta_muat most 1, whereTphas no value, no summary that is not yet established is pruned. An established summary is still dropped belowbeta_mu * w_bar, asw_barrises. Ids are monotone and never reused. A label is the smallest id in its chain, so it survives everything but the loss of that summary.The prune schedule. Without a clock column the clock is the row’s number, the first row being 1, so
prune_every=nprunes on the rowsmax_rows_between_prunes=ndoes while every row has weight. A row of weight zero advances the clock, so a quiet spell still prunes on time, and a gap capped atgap_capcounts as the cap. DenStream checks everyTpclock units (Pruning): giveprune_everythat to follow the paper.The link. Left out,
macro_linkderivesLat each prune as 1.5 times the 90th percentile of the established summaries’ nearest-neighbor distance, never below2 * eps * sqrt(p). So a chain along a shape holds without a constant that fragments one shape and bridges another.The scale floor.
1 / varalone grows as2^QoverQhalf-lives of a feature going quiet (a flag that stops firing, a sensor at rest): a million at twenty, and the row on which the feature moves again is then infinitely far from every center. Floored, the weight grows as2^(Q/8) / scale_floor, about 57 at twenty. The long-run variance is tracked at eight times the half-life, a feature at a time. Each row’s weight and deviation are clipped against it, and its start is the medians of the feature’s first five rows, so a row at the input bound moves it by a factor of 26 at most, which a few of its half-lives undo.