Skip to content

FEA Add EMeans clustering - #1

Open
maxmbay wants to merge 9 commits into
mainfrom
emeans
Open

maxmbay wants to merge 9 commits into
mainfrom
emeans

Conversation

@maxmbay

@maxmbay maxmbay commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Opened inside this fork for a first look and for comparison with another prototype (cakedev0/scikit-learn#46), as asked on the feature request scikit-learn/scikit-learn#35383. It is not a submission to scikit-learn: that request is still labelled "Needs Decision - Include Feature".

Trimmed after a first review: the parameters are down to n_clusters, init, n_epochs, batch_size and random_state, fit takes dense data only, and the user guide section and the example moved to the branch emeans-docs.

What this adds

sklearn.cluster.EMeans, an implementation of e-means from Bessa et al., "e-means: outperforming k-means (in one-tenth the epochs)", 2026. All credit for the method goes to its authors. The algorithm and its fitted constants follow their reference implementation in faiss (contrib/e_means, MIT license). No faiss code is copied.

E-means is mini-batch k-means where each center is the ratio of exponential moving averages of the sums and numbers of its samples. It adds a cosine decay of the learning rate, a batch size and an initial learning rate set by scaling laws of n_samples, n_clusters and n_epochs, a reassignment of unused clusters by splitting every 5 steps, and a closing step that sets each center to the mean of its samples of the last epoch.

API: EMeans(n_clusters=8, *, init="random", n_epochs=5, batch_size="auto", random_state=None), with fit(X, y=None). Fitted attributes: cluster_centers_, labels_, inertia_, batch_size_, n_steps_.

  • sklearn/cluster/_e_means.py: the estimator, on _BaseKMeans, so predict, transform, score and float32 behave as in KMeans.
  • sklearn/cluster/_e_means_minibatch.pyx: one mini-batch step. The samples are assigned in parallel over chunks of 256, as in an iteration of Lloyd, then summed by cluster sequentially, in the order of the mini-batch, so that the result does not depend on the number of threads.
  • Tests and the API reference entry.

Not included: sparse input, sample_weight, verbose, parameters for the learning rate and for the reassignment threshold, the spherical variant, partial_fit, GPU and distributed versions, faiss's max_points_per_centroid subsampling, and the changelog fragment.

Where to look first

  • Fidelity to the reference. From the same initial centers and random numbers, and with the same nearest-center search, the final centers match faiss's NumpyEmeans bit for bit (12 fits over 6 problems, 285 reassignments, re-run after the trimming). Checked before the trimming only: the centers and running weights after every step (1,013 steps over 4 problems), and the real faiss.knn (faiss-cpu 1.15.1), with which 8 of 14 fits are identical and the others diverge at a float32 assignment tie and end within 6e-5 relative inertia. This covers float32 data.
  • Sequential sums. Summing a mini-batch by cluster is single-threaded by design. It is the first place to look for the cost of an epoch against an iteration of Lloyd on many cores. The other prototype sorts the batch by label and updates the centers in parallel instead.
  • Threads. A mini-batch is assigned with at most one thread per chunk of 256 samples. The work threshold tuned on one machine is gone.
  • Reassignment threshold. Fixed at a tenth of the mean running weight, as in the reference, and off for n_features <= 2. On Yolanda it leaves e-means 1.25% above the best inertia found (see the benchmark comment).
  • labels_ and inertia_. The reference returns the assignments of the last epoch. Here, as in MiniBatchKMeans, an extra pass assigns each sample to its closest final center.

Benchmarks

Fronts of inertia against fit time for KMeans, MiniBatchKMeans and EMeans at matched budgets are in the first comment. They were measured before the trimming and have not been re-measured: the trimming removes a pass over the data from fit and changes the number of threads used on small mini-batches. The sparse datasets and the reassignment_ratio=0.01 runs of that comment use features that are no longer in this branch.

This pull request includes code written with the assistance of AI.
The code has been reviewed by a human, the author of this pull request.

🤖 Generated with Claude Code

maxmbay and others added 5 commits November 11, 2026 00:08
Implementation of e-means (Bessa et al., 2026, arXiv:2611.09501), following
the reference implementation in faiss/contrib/e_means: mini-batch k-means
where each center is the ratio of exponential moving averages of the sums
and weights of its samples, with a cosine decay of the learning rate, a
batch size and an initial learning rate set by scaling laws, and
reassignment of unused clusters by splitting.

Co-Authored-By: Claude <[email protected]>
Assign the samples of a mini-batch to their closest center and sum them by
cluster in Cython, from the indices of the mini-batch, instead of slicing
the data and using a sparse matrix product at each step. The exponential
moving average update of the centers is also done in Cython.

The samples are assigned in parallel and summed sequentially, in the order
of the mini-batch, so that the result does not depend on the number of
threads.

Co-Authored-By: Claude <[email protected]>
Keep the arithmetic of the exponential moving average update in the
floating type of the data, as in the reference implementation. With this,
the Cython kernel gives the same centers, bit for bit, as the previous
NumPy implementation on dense data.

Co-Authored-By: Claude <[email protected]>
Compare the centers with those computed by NumpyEmeans from
faiss.contrib.e_means on a small problem, from the same initial centers
and with the same random numbers.

Co-Authored-By: Claude <[email protected]>
Add a gallery example comparing the inertia reached by EMeans, KMeans and
MiniBatchKMeans for a given number of passes over the data, and state the
time and memory complexity, the scalability and the parallelism of EMeans
in the user guide.

Co-Authored-By: Claude <[email protected]>
@maxmbay
maxmbay marked this pull request as ready for review November 11, 2026 15:52
@maxmbay maxmbay self-assigned this Nov 11, 2026
@maxmbay

maxmbay commented Nov 11, 2026

Copy link
Copy Markdown
Owner Author

Inertia against fit time, at matched budgets

Each estimator is fitted over a grid of budgets and settings, with early stopping off. A point is one setting: its median fit time and median inertia over 3 seeds, or 1 seed on the four datasets of about 1M samples. The front of an estimator is the set of its points that none of its other points beats on both. Inertia is -score(X) for the three. Apple M3 Pro, 12 threads, Accelerate BLAS, float32 data, on an otherwise idle machine.

  • KMeans: Lloyd from random and k-means++ init, tol=0, n_init=1. max_iter goes up to 1000 on the five small datasets, 300 on the two Yolanda ones, and 256, 128 or 64 on the 1M-scale ones. Elkan from a random init on the datasets under 1M samples.
  • MiniBatchKMeans: batch sizes 1024, 8192 and 65536 (1024 only under 1M samples), max_no_improvement=None, n_init=1, up to 50 passes under 1M samples and up to 10 above.
  • EMeans: random init with the "throughput" batch size law, n_epochs from 0.25 up to 100 on the small datasets, 50 on Yolanda, 32 or 16 on the 1M-scale ones. Under 1M samples also the "quality" law and a k-means++ init. Everything below is with the default reassignment_ratio unless stated.

Data: DEEP1M is the first 1M vectors of the DEEP1B base set. GloVe-100 is the train split of glove-100-angular from ann-benchmarks, scaled to unit norm. RCV1 comes from fetch_rcv1. Yolanda is OpenML 42705, standardized.

image

Around 1M samples (1 seed)

Fastest fit within a given distance of the best inertia found, KMeans / EMeans:

Dataset Within 1% Within 0.3% Within 0.1%
DEEP1M, 1M x 96, 1024 clusters 5.4 s / 1.3 s 10.5 s / 2.1 s 28.9 s / 3.8 s
DEEP1M, 1M x 96, 4096 clusters 21.4 s / 4.5 s 77.9 s / 7.4 s never / 12.9 s
GloVe-100, 1.18M x 100, 1024 clusters 3.4 s / 1.0 s 12.4 s / 2.6 s 35.6 s / 4.6 s
RCV1 (sparse), 804k x 47k, 128 clusters 17.4 s / 2.7 s 18.2 s / 6.8 s 64.3 s / 6.8 s
  • EMeans is ahead at every level on the four datasets: 3 to 6 times faster to 1%, 3 to 11 times faster to 0.3%.
  • On DEEP1M with 1024 clusters, 8 epochs (3.8 s) end below KMeans after 256 iterations (79 s). With 4096 clusters, 8 epochs (12.9 s) end 0.25% below KMeans after 128 iterations (163 s). On GloVe, 16 epochs (8.9 s) end below 256 iterations (96 s).
  • MiniBatchKMeans gets within 1% on RCV1 only (6.2 s).
  • reassignment_ratio=0.01 does not help here: it is within 0.07% of the default from 2 epochs on for DEEP1M and GloVe, and 0.05 to 0.2% worse on RCV1.

Smaller datasets (3 seeds)

Same reading, KMeans / EMeans:

Dataset Within 1% Within 0.3%
Yolanda, 400k x 100, 256 clusters 0.48 s / never 1.2 s / never
Yolanda, 100k subsample, 2048 clusters 5.7 s / never 6.6 s / never
20 newsgroups, LSA-256 with unit norm, 18.8k x 256, 128 clusters 0.16 s / 0.020 s never / 0.20 s
20 newsgroups, TF-IDF (sparse), 11k x 25.6k, 20 clusters 0.022 s / 0.063 s 0.069 s / 0.12 s
Gaussian mixture (synthetic), 200k x 64, 256 clusters 0.22 s / 0.13 s 1.45 s / 0.30 s
Blobs (synthetic), 300k x 16, 100 clusters 0.29 s / 0.057 s never / 0.14 s
Gaussian (synthetic), 500k x 2, 50 clusters 0.27 s / 0.078 s never / 0.085 s

"never" means not within the budgets tried.

  • On the five small datasets KMeans runs to convergence (28 to 730 iterations) and ends 0.14 to 0.54% above the best EMeans fit. EMeans reaches 1% between 1.7 and 8 times faster on four of them.
  • On the small sparse TF-IDF data, KMeans reaches 1% 2.8 times faster.
  • On Yolanda, EMeans with the default reassignment threshold (0.1, as in the reference) stalls 1.25% above the best with 256 clusters and 4.5% above with 2048.
  • With reassignment_ratio=0.01 and 256 clusters, it reaches 1% in 0.25 s (KMeans: 0.48 s) and 0.3% in 3.9 s (KMeans: 1.2 s), and ends 0.21% above the best. With 2048 clusters it ends 1.8% above the best in 4.4 s, the lowest of all the settings under 5 s. Past that, Lloyd from a k-means++ init takes over (1% at 5.7 s, 0.1% at 9.3 s).

The stall on Yolanda comes from the reassignment of unused clusters: clusters under 10% of the mean running weight are refilled by splitting large ones, which pushes towards balanced clusters. On this heavy-tailed data, KMeans after 60 iterations has 18 of its 256 clusters under 10% of the mean size, and EMeans with the default has 3 (one seed each). The default of reassignment_ratio is worth discussing.

Caveats

  • One seed around 1M samples, where KMeans has not converged at its largest budget (256 iterations on DEEP1M with 1024 clusters and on GloVe, 128 with 4096 clusters, 64 on RCV1).
  • On RCV1, EMeans is at its best with 2 epochs. With 4 to 16 epochs it ends 0.15 to 0.2% higher.
  • reassignment_ratio=0.01 was added after seeing the Yolanda result, so it was chosen with hindsight.
  • The budgets were not all timed in the same pass. The same work ran up to 20% faster in a later pass than in the first one.
  • One machine.

maxmbay and others added 4 commits November 11, 2026 16:50
Keep the first version of EMeans minimal: fit only accepts dense data,
without sample weights nor verbose output. They can be added later
without breaking anything. fit_predict and fit_transform are overridden
since those of the base class pass sample_weight to fit.

Co-Authored-By: Claude <[email protected]>
Remove learning_rate_init, reassignment_ratio and the "quality" and
"throughput" values of batch_size, along with the learning_rate_init_
attribute. The initial learning rate, the choice of the batch size law
and the reassignment of unused clusters are those of the reference
implementation.

Co-Authored-By: Claude <[email protected]>
The mini-batches were only assigned with several threads above an amount
of work tuned on one machine. Use at most one thread per chunk of 256
samples instead, as for an iteration of Lloyd's algorithm. Also compute
the squared norms of the samples only for the k-means++ initialization,
which is the only place where they are used: this removes a
single-threaded pass over the data from fit.

Co-Authored-By: Claude <[email protected]>
Remove the user guide section and the gallery example of EMeans from
this branch, along with the links to them in the docstring, to keep the
first version small. They are kept on a separate branch.

Co-Authored-By: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant