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 as clock, half_life, gap_cap, min_weight and group, are in rheon.spec. This model takes features and no targets. fit_intercept has 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_drift and the rest. This model’s own:

eps

The 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 within eps * sqrt(p) for p features, so one value means the same at any p. 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 outlier and cluster stays null

eps is too small: no summary reaches beta_mu before it is pruned

increase eps

n_micro is about the number of clusters

eps is too coarse: the derived link, set from the summaries’ spacing, then bridges them

lower eps, or set macro_link=2, which links only summaries that touch

beta_mu

The 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-life h and v rows in each unit of the clock the stream’s steady-state weight is about 1.44 * v * h. So a summary meant to hold a share s of the stream needs beta_mu of about 1.44 * s * v * h.

max_clusters

The cap on live summaries, at least 1. Default 200.

prune_every, max_rows_between_prunes

A prune, which drops light summaries and links the rest, comes every prune_every clock units or every max_rows_between_prunes learned rows (at least 1), whichever comes first, as solve_every and max_rows_between_solves schedule a regression’s solve. With neither, every 100 learned rows. prune_every is finite and at least 0: a number of the clock’s units, a duration on a temporal clock ("10m"), or 0 for every row. The prune schedule in Notes gives the rules.

macro_link

The link distance L as a multiple of eps * sqrt(p): 0 links nothing, so each summary is its own cluster, and 2 links summaries that touch. Finite and at least 0. Left out, L is derived at each prune from the spacing the summaries already show (The link in Notes).

standardize

Measure in units of each feature’s exponentially weighted standard deviation. Default True. False measures in the features’ own units.

scale_floor

Under 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. Default 0.1, and 0 is the exponentially weighted variance alone. Finite and at least 0. Refused beside standardize=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:

cluster

The label of the nearest established summary (i64), null while there is none.

dist

The 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_id

The id of the summary this row goes to (i64), the one it opens when none can take it.

outlier

Whether no established summary takes it (bool).

n_clusters, n_micro

Live clusters and live summaries (i64), so churn is visible without comparing labels.

weight_sum

The weight the model has accumulated before the row and before the row’s own decay.

settled_frac

How far the model had come toward its steady state under decay before the row, null where nothing decays.

withheld_reason

Why the row’s fields were withheld: below_min_settled_frac while settled_frac is below min_settled_frac, where that is set, then below_min_weight while weight_sum is below min_weight, and null after. A row before any summary is established is not withheld: its cluster and dist are null and outlier is true.

coef

The established summaries, one [id, label, n, radius, c_1, ..., c_p] row each, flattened, as many rows as there are, so coef_index() does not apply.

Raises

As every builder does (rheon.spec), TypeError for targets, which this model does not take, and ValueError naming the problem for:

  • an empty features;

  • an eps or beta_mu not finite or not above 0;

  • a max_clusters or max_rows_between_prunes of 0;

  • a prune_every, macro_link or scale_floor below 0 or not finite, and scale_floor beside standardize=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 metric mw_i = 1 / var_i under standardize, var_i feature i’s EW variance floored at scale_floor times its long-run variance (The scale floor in Notes), and mw_i = 1 under standardize=False. So eps is a bound per standardized coordinate (or per unit without standardize), and the bound on a summary’s squared radius in the metric is E = eps**2 * p. x is the row’s features, w the row’s weight, w_bar the EW mean weight of the rows learned, and λ = 0.5 ** (Δclock / half_life) the row’s decay (lam ** Δclock under lam). Δclock is the clock’s step since the last row the model did not skip, capped at gap_cap, or session_gap at 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 + w

A 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 within L, else its own id. A new summary is opened at the cap max_clusters by 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 within L of each other share a label.

A row of weight w is 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’s xi(age) * w_bar. age is the clock that has passed since the summary opened, and h is 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 Tp clock 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 with beta_mu at most 1, where Tp has no value, no summary that is not yet established is pruned. An established summary is still dropped below beta_mu * w_bar, as w_bar rises. 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=n prunes on the rows max_rows_between_prunes=n does 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 at gap_cap counts as the cap. DenStream checks every Tp clock units (Pruning): give prune_every that to follow the paper.

The link. Left out, macro_link derives L at each prune as 1.5 times the 90th percentile of the established summaries’ nearest-neighbor distance, never below 2 * eps * sqrt(p). So a chain along a shape holds without a constant that fragments one shape and bridges another.

The scale floor. 1 / var alone grows as 2^Q over Q half-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 as 2^(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.