Repository navigation
Description
Warning
This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.
Introduce yourself
I'm a data scientist working as Sr. Quantitative analyst for the Los Angeles Dodgers. Most of my professional work lives in-house, but I'd like to give back to the broader community so I've decided spend more of my free time pursuing open source projects. SKL was a staple of my (previous) life as a scientist, and of course plays a role in my career outside of academia.
Describe the workflow you want to enable
I'd like to get KMeans-quality centers in a handful of passes over the data. In the runs below KMeans needed 19 to 229 iterations, and MiniBatchKMeans is cheap per pass but ends with worse inertia. Usage would be EMeans(n_clusters=256, n_epochs=5).fit(X), with the rest of the KMeans interface (predict, transform, score, sparse input, sample_weight).
Describe your proposed solution
e-means is a mini-batch k-means published in November 2026 by Bessa et al. at Meta FAIR: https://arxiv.org/abs/2611.09501. Each center is an exponential moving average of the points assigned to it, and the learning rate decays along a cosine. The batch size and the initial learning rate are computed from scaling laws that the authors fitted, so the user only chooses the number of epochs. Their reference code is in faiss, https://github.com/facebookresearch/faiss/tree/main/contrib/e_means, and their benchmark scripts are in https://github.com/facebookresearch/faiss/tree/main/benchs/e_means.
The paper reports that e-means reaches the loss of 25 Lloyd iterations in 1.4 to 2.6 epochs on embedding datasets.
I have a prototype built on scikit-learn's existing k-means Cython code. On five datasets on my laptop it fit 1.8 to 17 times faster than KMeans, and its inertia was between 0.7% lower and 0.5% higher. The 17x case was 200,000 points in 64 dimensions with 256 clusters: 0.56 s against 9.5 s. All five datasets are synthetic or small, so these numbers need a proper benchmark behind them.
From the same initial centers and random numbers, the prototype gives the same centers as faiss's NumpyEmeans at every step, except where two centers tie at float32 precision.
The paper is from this month, so this is nowhere near the 3 years and 200 citations in the FAQ. I'm opening this because the FAQ also allows a clear-cut improvement on a widely used method, and I'd like to know if you think this qualifies.
Describe alternatives you've considered, if relevant
MiniBatchKMeans was slower than the prototype in the same runs and finished 0.3% to 2.8% above KMeans in inertia. #30051 also changes the learning rate of mini-batch k-means. If this doesn't belong in core I can publish it as a scikit-learn-contrib package.
Additional context
The prototype comes with tests and docs, and I can open a draft PR once this is triaged. It doesn't copy any faiss code. I used AI assistance (Claude Code) to write it but have reviewed the changes thoroughly and believe in the work.
Activity
github-actions commentedon Nov 11, 2026
Thanks for the work you've done so far. The goal of this comment is to set expectations.
Deciding on new features or substantial changes is a lengthy process. It frequently happens that no maintainer is available to take on this task right now.
Please do not create a Pull Request before a decision has been made regarding the proposed work. Making this decision can often take a significant amount of time and effort.
cakedev0 commentedon Nov 11, 2026
Personally, I think we should add it.
I have a prototype too, I've been working quite a lot on k-means lately so I might have good ideas to stir Claude in the right directions (performance wise). I'll open a draft PR soo, I'd happy if you can give it a review and compare it with your prototype (quality wise and performance wise).
cakedev0 commentedon Nov 11, 2026
I'm also benchmarking against various existing implementations of kmeans on embedding datasets and other kind of datasets (lower dimensions, and I will include sparse datasets too I think). I'll draw Pareto fronts of inertia vs fit time.
maxmbay commentedon Nov 11, 2026
Thanks @cakedev0. I’d encourage a broader discussion about the decision to proceed before going full-bore with a PR. FWIW, my local branch is already PR-sized: an
EMeansestimator on top of_BaseKMeans, a Cython mini-batch kernel for dense and CSR input, tests, a user guide section and a gallery example. Onfloat32dense data it is bitwise identical to the published faiss’sNumpyEmeansat every step when both use the same NN search.cakedev0 commentedon Nov 11, 2026
Context: we're going to release 1.10 soon and 1.11 will be in 6 months, I'd like to move fast to have a chance of having that in 1.10.
Can you open a PR on your fork with your code ? I'm happy to take a first quick look.
maxmbay commentedon Nov 11, 2026
Gotcha, didn’t think about the release cadence. My branch is up as a draft PR on my fork: maxmbay/scikit-learn#1 · FEA Add EMeans clustering. I’m also running a Pareto sweep of inertia against fit time (KMeans, MiniBatchKMeans and EMeans over seven datasets x three seeds) and will post the fronts when they're done.
cakedev0 commentedon Nov 11, 2026
My prototype: cakedev0#46, it's less complete but it's quite faster according to claude (to double check). In terms of tests, we should probably merge the tests from both PRs.
Some feedback on your PR:
Both our PR include sparse support, but I'm not sure we need it for the first version. For now, I'm not benchmarking sparse datasets. I might remove that from my PR to keep it as minimal as possible.
I'm running a Pareto sweep on:
I'm using the scikit-learn nightly package: it contains a significant optimization of the k-means++ init.
Early results:
maxmbay commentedon Nov 12, 2026
Thanks, yeah I agree with all of that. I’ll cut mine down to your signature, dense only and without sample_weight, and move the user guide and example to a follow-up PR. The thread cutoff is the one constant I fitted on my machine (the others are the reference’s), and I’ll replace it with your rule of no more threads than chunks. Your update, parallel over centers, is a better design than my single-threaded sum, so I’d rather end up with one kernel, yours, with my tests on top, including the check against centers from faiss’s NumpyEmeans. One thing for your sweep: on Yolanda the dead-cluster threshold of 0.1 leaves e-means 1.25% above the best inertia and 0.01 removes most of that, which may be one of the regimes where KMeans still wins. My branch is on main from Nov 10, so it has the k-means++ speed-up too.
Makes sense that your prototype runs faster. Its center update runs in parallel and it has no machine-tuned constant, so it is likely faster, but I did not time it.
betatim commentedon Nov 12, 2026
I don't think this needs to be in 1.10.
This is exciting stuff, but from spending about 30s on it I am not sure what is special about this compared to other breakthroughs that have come in the past. scikit-learn is not a library that wants to be a trailblazer, we follow the well trodden paths that are established and make them very nice, correct, performant and well maintained. sklearn-contrib packages are a much better place for fast moving, new things.
8 remaining items
cakedev0 commentedon Nov 12, 2026
I'll look into it, but at first sight it looks like it has a slightly different API (
batch_size, no tolerance, factionaln_epochsinstead of integermax_iter, and an order of magnitude smaller:n_epochsis more between 1 and 10 whilemax_iteris between 10 and 1000).Personally, I tend to always prefer to have two different classes/functions/... to do two different things. I've often seen cases where merging similar but slightly different semantics into a single API ending up in a bad API.
cakedev0 commentedon Nov 13, 2026
Do you have some advice for that? ^^ In particular: whose buy-in matters most, and what would convince you?
What I've done so far:
betatim commentedon Nov 13, 2026
Have a coffee with some of the probabl people maybe, chat with Christian about it. Let's talk about it at the next monthly maintainer meeting. I'm not sure it is an exact science really.
cakedev0 commentedon Nov 13, 2026
Sounds good to me 😄
betatim commentedon Nov 13, 2026
As someone who only followed this via the excitement of others: does a lower number of iterations mean significantly faster execution? Less work must mean a faster run time, but maybe it only takes things from "fast" to "a bit faster"? Maybe it allows new workflows because they go from taking "enough time to get distracted" to "no change to get distracted by cat pictures"?
Put differently, is there a cool use-case example for "random person from the internet" that we can have?
cakedev0 commentedon Nov 13, 2026
See the benchmarks: https://pr-187.sklbench-dashboard-preview.pages.dev/kmeans_pareto (they keep evolving with my iterations on the package).
Or if you just want my package vs scikit-learn (nightly build so it has my recent optimization): https://pr-187.sklbench-dashboard-preview.pages.dev/kmeans_pareto#implementation=scikit-learn-lloyd,sklearn-contrib-emeans,cuml-kmeans,faiss-e-means-triton-fp32&machine=intel-core-ultra-desktop
Basically, I think that e-means epochs makes Llyod iterations mostly obsolete. Combined with k-means|| it's very strong in many cases (some of which random init fails totally). Sometimes k-means++ init can still be useful, the Pareto front of sklearn-contrib-emeans doesn't include it yet.
In short: it often reaches same inertia (up to 1e-3 relative difference) ~10x faster. On sparse data, it's even ~20-40x faster!
cakedev0 commentedon Nov 13, 2026
In my previous positions, we were clustering embeddings from recommendation models (a lot of people do that in recommender systems I believe, dimension is 30-250 and you sometimes want quite small clusters, which means many clusters). And the speed was a real problem, someone even developed a "Hierarchical k-means" to deal with that, but it was quite bad in terms of clusters quality (and terribly bad in terms of inertia). This algorithm (+ a good implementation) would have saved use a lot of computation time and head scratching time.
betatim commentedon Nov 13, 2026
Maybe clustering embeddings of sentences/images/what have you could make for a nice user example then?
S-B-Iqbal commentedon Nov 15, 2026
Independent data point for this discussion - not a competing proposal.
I wrote an independent implementation of e-means from the paper
(BSD-3, import
emeans, source: github.com/S-B-Iqbal/emeans) and benchmarked it honestly on onelaptop. Caveats first: Apple M2 with serial kernels (no -fopenmp on Apple clang), so compare
epochs rather than seconds; synthetic Gaussian blobs; n_train = 100 000 with k = 512, inside the
range the paper's scaling laws were fitted on (B = 8192, alpha0 = 0.733). Metric =
(MSE - MSE_Lloyd@25)/MSE_Lloyd@25, median of 5 seeds, both methods at equal epoch budgets:
Three readings:
Table 4. We needed 2-4 epochs at n_train = 10 000, so the automatic batch size and step do
matter as the laws intend. At d = 96 e-means is also faster than Lloyd@25 (1.5 s vs 2.3 s).
-15.5 % at d = 32 against -33.9 % at d = 96.
it did at n_train = 10 000. So the strongest case is not "add another estimator" but landing
the transferable parts in MiniBatchKMeans (cosine-annealed step with a floor; last-epoch-mean
finalization, which gives
fit(X).labels_ == predict(X)for free; automatic batch size and peakstep; split-based revival instead of random reassignment) as the
algorithm="e-means"route@glevv suggested.
Protocol, CSV, plots and every losing case:
benchmarks/report.md. Parity with the existingprototypes (thanks @cakedev0, @maxmbay):
docs/upstream/parity-matrix.md. Our implementationdiffers by supporting
sample_weightand streamingpartial_fit- happy to upstream either towhichever package maintainers prefer rather than duplicate effort.
ogrisel commentedon Nov 16, 2026
Let's recall our inclusion rules for new algorithms, in particular:
Since e-means has significant differences in its solver and new hparams, it's hard to consider it an incremental improvement of k-means or minibatch k-means even it optimizes the same objective function and same hypothesis space.
But the improvement in the Pareto tradeoffs over
KMeans(with or without kmeans++ init) and ourMiniBatchKMeansis indeed real and so massive (10x to 100x from what I can see) that indeed scikit-learn might become obsolete for clustering purposes if we strictly interpret our inclusion criteria. This is typically a case for "clear-cut improvement" IMHO.+1 for discussing this at the next monthly meeting.
It would also be interesting to include
scikit-learn-intelex's implementation ofKMeansto the mix to double check that the "clear-cut improvement" against another strong implementation on CPU (even though current benchmark results already compare against the scikit-learnmainbranch that includes #35140 (optimized kmeans++ init).Also for the sake of completeness, I would be curious to see e-means and k-means with random inits and augmented with "breathing iterations" can compete with kmeans++ and kmeans|| alternatives on a Pareto analysis. (see also the previous inclusion discussion for Breathing KMeans).
ogrisel commentedon Nov 16, 2026
That's an interesting suggestion to consider.
Pros
FutureWarningto change the defaults.Cons
(MiniBatch)Kmeansclasses since some hparams might only be relevant for a particular algorithm.ogrisel commentedon Nov 16, 2026
Another alternative:
Introduce a new
EMeansclass with apartial_fitmethod and deprecateMiniBatchKMeansin its favor since ourMiniBatchKMeansimplementation is not that popular and not competitive anymore.cakedev0 commentedon Nov 16, 2026
I had a quick look and I'd leave breathing iterations out of this discussion: they improve the inertia, but at a cost that puts them far from the Pareto front.
A breathing cycle is two passes over the data to compute the error and the utility of each center, plus two Lloyd iterations to convergence (one after adding the m centers, one after removing m). So one cycle costs more passes than a whole e-means fit with the default 5 epochs, and it took 8 to 27 cycles to converge in my runs.
ogrisel commentedon Nov 17, 2026
Thanks for checking. That's good to know. I agree to leave that away (or moved to a separate discussion if needed).
cakedev0 commentedon Nov 17, 2026
The scikit-learn-intelex runs are in-progress.
In the meantime, I wrote an example about the algorithm-wise added value my package brings on top of e-means: https://cakedev0.github.io/sklearn-contrib-emeans/auto_examples/plot_init_and_revival.html
I made those improvements based on road network (on which they are very needed) and some higher dimension datasets (10 to 100) where the gain is more around a few percent of inertia.
Edit: not just a few percent actually, on credit card fraud dataset (30 features), the default e-means (as implemented in faiss) is 2.5x higher inertia than with my improvements!