polars_online.spec.kmeans¶
- polars_online.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, **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, andhmm()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_weightandgroup, are inpolars_online.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, drift and the rest. This model’s own:n_clustersThe number of centers. Required, at least 1, and at most 65,536 (2^16): every row is compared with every center.
warm_rows,init,seedSeeding. The first
warm_rowslearned rows are held, at leastn_clusters: a smaller value is refused. Default 500, orn_clusterswhere 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 largestwarm_rowsthat fits. Then the centers are placed byinit:initthe 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_clustersdistinct rowsseed, at least 0, drives the two random rules: the same seed gives the same centers. Default 0 (Noneis 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 untilweight_sumreachesmin_weight. Seeding in Notes gives its timing and the rules at its edges.update_every_rowsHow 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.
split_merge,split_merge_every_rowsMove a center to a cluster that appears after seeding. Every
split_merge_every_rowslearned rows (default 100, at least 1), the two closest centers are merged where their distance is undersplit_mergetimes 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_mergeis finite and at least 0, default 0.5.0turns off the merge and the far rows both, so every row is learned. Far rows, split and merge in Notes gives the rule.dead_fracRe-place a center whose weight has decayed below
dead_frac * weight_sum / n_clustersthe same way, on whatever far rows there are. Default 0.05, and0disables 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-placedlog2(1 / dead_frac)half-lives later (4.3 at the default, 2 at 0.25). The rule runs at a split-merge check, so besidesplit_merge = 0, which runs none, the default is 0 and a value above 0 is refused. Dead centers in Notes gives the measurements.standardizeMeasure 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.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. docs/OUTPUTS.md#kmeans gives each field’s type and when it is null:
clusterThe nearest center’s index (
i64), before the row is learned; null until seeding, and while the row is withheld.dist,dist_secondThe distance to that center, and to the runner-up, the second-nearest (null when
n_clusters == 1), sodist_second - distis the margin. Understandardizeit is in units of each feature’s exponentially weighted (EW) standard deviation, and otherwise in the features’ own units.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_min_settled_fracfirst of all, whilesettled_fracis belowmin_settled_fracwhere that is set, thenbelow_min_weighton the first rows under the defaultmin_weight, thenbelow_warm_rowson the rest of the rows held to seed the centers from.coefThe centers:
n_clustersrows oflen(features), flattened cluster-major.coef_index()lays it out, withclusterreading0,1, … andtermthe feature whose coordinate the position holds.
Raises
As every builder does (
polars_online.spec),TypeErrorfortargets, which this model does not take, andValueErrornaming the problem for:an empty
features;an
n_clustersof 0 or past 2^16, awarm_rowsbelown_clusters, and held rows past 256 MiB;an
initnot in the list, and aseedbelow 0;an
update_every_rowsorsplit_merge_every_rowsof 0;a
split_merge,dead_fracorscale_floorbelow 0 or not finite, adead_fracof 0.5 or more, adead_fracabove 0 besidesplit_merge = 0, andscale_floorbesidestandardize=False;a switch of a diagnostic that reads residuals.
The update
Per row,
wis the row’s weight,λ = 0.5 ** (Δclock / half_life)its decay (lam ** Δclockunderlam),xthe features, andc_jandn_jcenterjand its decayed weight.Δclockis the clock’s step since the last row the model did not skip, capped atgap_cap, orsession_gapat 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 byscale_floor, and in the features’ own units without it. A far row (Far rows, split and merge in Notes) moves neithern_jnorc_j.Alongside each center the model keeps its exponentially weighted squared radius
r2_j, the mean of|x - c_j|^2over the rows assigned there, which the split-merge rule reads. Rows are folded into per-center batches and applied everyupdate_every_rowslearned 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 = po.spec.kmeans( "km", features=["a", "b"], half_life=float("inf"), n_clusters=2, warm_rows=100, # seed the centers from 100 rows ) bank = po.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 columnlabel=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 inpolars_online.ModelBank.solve_failures(); the starts measured on 500 rows needed at most 54. Under"first", seeding waits pastwarm_rowsif it must forn_clustersdistinct rows, holding up tomax(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|^2above 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 undersplit_mergetimes 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 thandead_frac / n_clustersof the stream loses its center whenever any row is far.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.