rheon.spec.kmeans

rheon.spec.kmeans(name: str, *, features: list[str], n_clusters: int, warm_rows: int | None = None, init: Literal['first', 'farthest', 'k-means++', 'lloyd'] | None = None, seed: int | None = None, update_every_rows: int | None = None, split_merge: float | None = None, split_merge_every_rows: int | None = None, dead_frac: float | None = None, standardize: bool = True, scale_floor: float | None = None, warm_span: float | timedelta | str | _Expr | None = None, update_every: float | timedelta | str | _Expr | None = None, split_merge_every: float | timedelta | str | _Expr | None = None, **common: Unpack[CommonKwargs]) → dict[str, Any][source]

Exponentially weighted k-means over the feature columns.

Use it to assign each row to one of a fixed number of clusters whose centers follow the stream, with the cluster read before the row is learned, so it is out-of-sample like every prediction. Use micro() where the number of clusters is not known, and hmm() where a row’s cluster depends on the one before it.

Parameters

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, drift and the rest. This model’s own:

n_clusters

The number of centers. Required, at least 1, and at most 65,536 (2^16): every row is compared with every center.

warm_rows, init, seed

Seeding. The first warm_rows learned rows are held, at least n_clusters: a smaller value is refused. Default 500, or n_clusters where that is more. The rows held are bounded at 256 MiB, each row its values, its weight and 24 bytes besides (48 bytes a row at two features): the refusal names the largest warm_rows that fits. Then the centers are placed by init:

init

the centers

"lloyd" (the default)

the best, by inertia, of ten "k-means++" starts, each followed by weighted Lloyd passes over the rows held until no row changes center

"k-means++"

greedy k-means++, scikit-learn’s: each center after the first is the best of 2 + floor(ln n_clusters) rows drawn by their squared distance from the centers so far, the one that leaves the least inertia

"farthest"

Gonzalez, from the first row

"first"

the first n_clusters distinct rows

seed, at least 0, drives the two random rules: the same seed gives the same centers. Default 0 (None is 0), so a run draws the same centers every time. The rows held are replayed into the centers and freed, so from the row that completes seeding, memory grows with the model’s state alone. Outputs are withheld until seeding and until weight_sum reaches min_weight. Seeding in Notes gives its timing and the rules at its edges.

update_every_rows

How many learned rows the model gathers, each into its nearest center’s batch, before it moves the centers by them, at least 1. Default 1, plain sequential k-means. Set it above 1 for mini-batch k-means: the centers then move once every that many rows.

warm_span

The warm-up over a span of the clock in place of warm_rows: the learned rows from the first through the first row at least warm_span after it, once they are at least n_clusters. 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 holds warm_span + 1 rows: the seeding of warm_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 beside warm_rows.

update_every, split_merge_every

The same two cadences on the clock: the centers move, or the split-merge check runs, every this long, as well as every update_every_rows or split_merge_every_rows learned rows, whichever comes first, counted from the seeding. Each is a number of the clock’s units (rows where the spec has no clock) or a duration, at least 0, 0 every row. Given alone, the count beside it is none. On a clock of one unit a row, update_every = n is update_every_rows = n to the bit.

split_merge, split_merge_every_rows

Move a center to a cluster that appears after seeding. Every split_merge_every_rows learned rows (default 100, at least 1), the two closest centers are merged where their distance is under split_merge times the sum of their radii and enough far rows have gathered. The freed center is placed at the mean of the far rows of the cluster that has gathered the most of them. split_merge is finite and at least 0, default 0.5. 0 turns off the merge and the far rows both, so every row is learned. Far rows, split and merge in Notes gives the rule.

dead_frac

Re-place a center whose weight has decayed below dead_frac * weight_sum / n_clusters the same way, on whatever far rows there are. Default 0.05, and 0 disables it. At least 0 and below 0.5: at 0.5 the re-placed center starts at the floor itself. A center whose cluster vanished is re-placed log2(1 / dead_frac) half-lives later (4.3 at the default, 2 at 0.25). The rule runs at a split-merge check, so beside split_merge = 0, which runs none, the default is 0 and a value above 0 is refused. Dead centers in Notes gives the measurements.

standardize

Measure distances in units of each feature’s exponentially weighted standard deviation, tracked alongside the centers. The coordinates themselves are never rescaled, so the centers stay in the features’ units. 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. docs/OUTPUTS.md#kmeans gives each field’s type and when it is null:

cluster

The nearest center’s index (i64), before the row is learned; null until seeding, and while the row is withheld.

dist, dist_second

The distance to that center, and to the runner-up, the second-nearest (null when n_clusters == 1), so dist_second - dist is the margin. Under standardize it is in units of each feature’s exponentially weighted (EW) standard deviation, and otherwise in the features’ own units.

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, null where they were not: below_min_settled_frac first of all, while settled_frac is below min_settled_frac where that is set, then below_min_weight on the first rows under the default min_weight, then below_warm_rows on the rest of the rows held to seed the centers from.

coef

The centers: n_clusters rows of len(features), flattened cluster-major. coef_index() lays it out, with cluster reading 0, 1, … and term the feature whose coordinate the position holds.

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 n_clusters of 0 or past 2^16, a warm_rows below n_clusters, and held rows past 256 MiB;

  • an init not in the list, and a seed below 0;

  • an update_every_rows or split_merge_every_rows of 0, an update_every or split_merge_every below 0, a warm_span not finite and above 0, and a warm_span beside warm_rows;

  • a split_merge, dead_frac or scale_floor below 0 or not finite, a dead_frac of 0.5 or more, a dead_frac above 0 beside split_merge = 0, and scale_floor beside standardize=False;

  • a switch of a diagnostic that reads residuals.

The update

Per row, w is the row’s weight, λ = 0.5 ** (Δclock / half_life) its decay (lam ** Δclock under lam), x the features, and c_j and n_j center j and its decayed weight. Δ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 center is the decayed weighted mean of the rows assigned to it (ew_cov()’s mean, per cluster):

j*   = argmin_j |x - c_j|^2          in the units of dist
n'_i = λ * n_i                                for every center i
n'_j = λ * n_j + w
c'_j = (λ * n_j * c_j + w * x) / n'_j         for the nearest j

The distance is in units of each feature’s EW standard deviation under standardize, floored by scale_floor, and in the features’ own units without it. A far row (Far rows, split and merge in Notes) moves neither n_j nor c_j.

Alongside each center the model keeps its exponentially weighted squared radius r2_j, the mean of |x - c_j|^2 over the rows assigned there, which the split-merge rule reads. Rows are folded into per-center batches and applied every update_every_rows learned rows.

Example

This code clusters rows drawn around two planted centers and prints each beside the center the model found:

import numpy as np

rng = np.random.default_rng(5)
centers = np.array([[-2.0, 0.0], [3.0, 1.0]])       # the two planted centers
pick = rng.integers(0, 2, 4_000)
xy = centers[pick] + 0.5 * rng.standard_normal((4_000, 2))
pl.DataFrame({"a": xy[:, 0], "b": xy[:, 1]}).write_parquet("blobs.parquet")

km = rp.spec.kmeans(
    "km", features=["a", "b"], half_life=float("inf"),
    n_clusters=2,
    warm_rows=100,                                    # seed the centers from 100 rows
)
bank = rp.ModelBank([km])
bank.fit(pl.scan_parquet("blobs.parquet"))           # learn every row, keep no output
found = bank.coef().pivot(on="term", index="cluster", values="coef").sort("a")
for (pa, pb), r in zip(centers, found.iter_rows(named=True)):
    print(f"planted ({pa:g}, {pb:g}): found ({r['a']:.2f}, {r['b']:.2f})")
planted (-2, 0): found (-2.00, 0.02)
planted (3, 1): found (3.02, 1.00)

See also

  • micro(), density clustering that finds the number of clusters.

  • hmm(), Gaussian states whose next state depends on the last.

  • ew_class(), Gaussian classes, one for each value of the column label= names.

Notes

Seeding. Seeding under "lloyd", ten starts, runs once per group: 56 to 91 ms at 400 features and 8 centers, against 3.9 ms for "k-means++", its placement and the replay of the 500 rows. A "lloyd" start that is still moving rows after 300 passes stops there and is counted in rheon.polars.ModelBank.solve_failures(); the starts measured on 500 rows needed at most 54. Under "first", seeding waits past warm_rows if it must for n_clusters distinct rows, holding up to max(warm_rows, 1000) rows.

Far rows, split and merge. A row farther from its center than a blob of the typical radius produces (about four standard deviations of |x - c|^2 above it) is far. It is predicted, but summarized instead of learned, so it neither drags the center nor widens the radius. At each check the two closest centers are compared, where there are at least three. If their distance is under split_merge times the sum of their radii, and enough far rows have gathered somewhere (at least three, and five percent of the weight learned since the last check), they are merged. The freed center is placed at the mean of the far rows of the cluster that has gathered the most of them. So a cluster that appears after seeding gets a center without a reset. Far rows still count in the radius at each check as if they sat at the cut, so a cut the data has outgrown widens until the rows are learned again.

Dead centers. The freed center takes half the weight of the cluster it is split from, which keeps the other half, so from a cluster at an equal share both halves start at weight_sum / (2 n_clusters): the floor itself at 0.5. Each check then re-places one of them on the far rows, and the clustering is lost. Over 50 streams with a check every 25 rows, a center whose blob vanished was re-placed once on every stream at 0.45 and below; 3 streams cascaded at 0.5, 29 at 0.6 and all 50 at 0.9. A cluster lighter than dead_frac / n_clusters of the stream loses its center whenever any row is far.

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.