Skip to content

Add e-means clustering (EMeans) #35383

Open

Description

@maxmbay

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

  1. added
    Needs Decision
    Needs Decision - Include Feature
    and removed
    Needs Triage
    Needs Decision
    on Nov 11, 2026
  2. github-actions commented on Nov 11, 2026

    @github-actions

    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.

  3. cakedev0 commented on Nov 11, 2026

    @cakedev0
    Member

    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).

  4. cakedev0 commented on Nov 11, 2026

    @cakedev0
    Member

    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.

  5. maxmbay commented on Nov 11, 2026

    @maxmbay
    Author

    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 EMeans estimator on top of _BaseKMeans, a Cython mini-batch kernel for dense and CSR input, tests, a user guide section and a gallery example. On float32 dense data it is bitwise identical to the published faiss’s NumpyEmeans at every step when both use the same NN search.

  6. cakedev0 commented on Nov 11, 2026

    @cakedev0
    Member

    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.

  7. maxmbay commented on Nov 11, 2026

    @maxmbay
    Author

    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.

  8. cakedev0 commented on Nov 11, 2026

    @cakedev0
    Member

    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:

    • The API is too complete I think: let's keep it minimal for now, so it has more change to be merged quickly (before the next release), and we can add more parameters/knobs by the next release.
    • The user guide and example could go in a separate PR, but they are definitely useful.
    • It seems tuned on your laptop. This can lead to over-fitting some choices to some particular hardware (but well, it's simpler, and we could also tune the performance by the next release).

    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:

    • an powerful intel laptop
    • a good intel desktop
    • an AMD EPYC cloud VM (64 cores)
    • an Intel Xeon socket (86 cores - but limited to 64 threads)
    • a MacBook Pro with an M2 chip
    • Also: an Nvidia L4 GPU (I'm running different GPU implems on this one, including the faiss e-means)

    I'm using the scikit-learn nightly package: it contains a significant optimization of the k-means++ init.

    Early results:

    • MiniBatchKMeans does really bad...
    • There are some regimes/datasets where KMeans still seems to be useful.
  9. maxmbay commented on Nov 12, 2026

    @maxmbay
    Author

    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.

  10. betatim commented on Nov 12, 2026

    @betatim
    Member

    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.

  11. 8 remaining items

  12. cakedev0 commented on Nov 12, 2026

    @cakedev0
    Member

    more like additional algorithm KMeans(algorithm='e-means'), or maybe MiniBatchKMeans(algorithm='e-means')

    I'll look into it, but at first sight it looks like it has a slightly different API (batch_size, no tolerance, factional n_epochs instead of integer max_iter, and an order of magnitude smaller: n_epochs is more between 1 and 10 while max_iter is 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.

  13. cakedev0 commented on Nov 13, 2026

    @cakedev0
    Member

    Make sure to spend some time on the "build consensus for inclusion" step

    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:

    • kept the wheel building recipe and the code style close to scikit-learn's, so that upstreaming is mostly a copy
    • kept the API small (it's easier to add things than to remove/change them). The main risk I've taken is the k-means|| init, but I think it's extremely relevant.
  14. betatim commented on Nov 13, 2026

    @betatim
    Member

    Do you have some advice for that? ^^

    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.

  15. cakedev0 commented on Nov 13, 2026

    @cakedev0
    Member

    Sounds good to me 😄

  16. betatim commented on Nov 13, 2026

    @betatim
    Member

    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?

  17. cakedev0 commented on Nov 13, 2026

    @cakedev0
    Member

    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!

  18. cakedev0 commented on Nov 13, 2026

    @cakedev0
    Member

    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.

  19. betatim commented on Nov 13, 2026

    @betatim
    Member

    Maybe clustering embeddings of sentences/images/what have you could make for a nice user example then?

  20. S-B-Iqbal commented on Nov 15, 2026

    @S-B-Iqbal

    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 one
    laptop. 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:

    dataset epochs to Lloyd@25 EMeans@1 EMeans@5 worst seed MiniBatch@5 (tuned)
    d = 96 1.0 (5/5 seeds) -19.0 % -33.9 % -28.5 % -47.3 %
    d = 32 1.0 (4/5 seeds) -8.3 % -15.5 % -13.1 % -41.1 %

    Three readings:

    1. The epochs claim reproduces here: one epoch reaches the Lloyd@25 test MSE, against 1.4-2.6 in
      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).
    2. The win is dimension-dependent, which matches the embedding regime described above (d ~ 30-250):
      -15.5 % at d = 32 against -33.9 % at d = 96.
    3. A validation-tuned MiniBatchKMeans still wins on test MSE at every equal-epoch budget here, as
      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 peak
      step; 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 existing
    prototypes (thanks @cakedev0, @maxmbay): docs/upstream/parity-matrix.md. Our implementation
    differs by supporting sample_weight and streaming partial_fit - happy to upstream either to
    whichever package maintainers prefer rather than duplicate effort.

  21. ogrisel commented on Nov 16, 2026

    @ogrisel
    Member

    Let's recall our inclusion rules for new algorithms, in particular:

    We only consider well-established algorithms for inclusion. A rule of thumb is at least 3 years since publication, 200+ citations, and wide use and usefulness. A technique that provides a clear-cut improvement (e.g. an enhanced data structure or a more efficient approximation technique) on a widely-used method will also be considered for inclusion.

    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 our MiniBatchKMeans is 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 of KMeans to 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-learn main branch 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).

  22. ogrisel commented on Nov 16, 2026

    @ogrisel
    Member

    For me it does not look like a separate estimator, more like additional algorithm KMeans(algorithm='e-means'), or maybe MiniBatchKMeans(algorithm='e-means')

    That's an interesting suggestion to consider.

    Pros

    • avoid class proliferation;
    • make it easier to point existing k-means users to a faster/better alternative, possibly with a FutureWarning to change the defaults.

    Cons

    • since the e-means algorithm is quite different from the traditionally taught LLoyd K-Means, users might find it confusing, especially in educational contexts;
    • I anticipate that hparams settings might get complex to align if we decide to consider e-means as an alternative internal solver for the (MiniBatch)Kmeans classes since some hparams might only be relevant for a particular algorithm.
  23. ogrisel commented on Nov 16, 2026

    @ogrisel
    Member

    Another alternative:

    Introduce a new EMeans class with a partial_fit method and deprecate MiniBatchKMeans in its favor since our MiniBatchKMeans implementation is not that popular and not competitive anymore.

  24. cakedev0 commented on Nov 16, 2026

    @cakedev0
    Member

    I would be curious to see e-means and k-means with random inits and augmented with "breathing iterations"

    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.

  25. ogrisel commented on Nov 17, 2026

    @ogrisel
    Member

    Thanks for checking. That's good to know. I agree to leave that away (or moved to a separate discussion if needed).

  26. cakedev0 commented on Nov 17, 2026

    @cakedev0
    Member

    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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs Decision - Include FeatureNew Feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions