Skip to content

adding adaptive learning rate for minibatch k-means - #30051

Open
BenJourdan wants to merge 20 commits into
scikit-learn:mainfrom
gregoryschwartzman:feature_mbkm_adaptive_lr
Open

BenJourdan wants to merge 20 commits into
scikit-learn:mainfrom
gregoryschwartzman:feature_mbkm_adaptive_lr

Conversation

@BenJourdan

Copy link
Copy Markdown

Reference Issues/PRs

None

What does this implement/fix? Explain your changes.

This request implements a recent learning rate for minibatch k-means which can be superior to the default learning rate. We implement this with the flag adaptive_lr that defaults to false.

Details can be found in this paper that appeared in ICLR 2023. Extensive experiments can be found in this manuscript - ignore the kernel k-means results. We also added a benchmark that produces the following plot which shows the learning rate is the same or better than the default on dense datasets.

image

Any other comments?

This is a reasonably small code change. We add a flag to the MinibatchKmeans constructor and the _k_means_minibatch.pyx cython file. The learning rate implementation is straightforward. In the benchmarks, it appears to take a few more iterations for the adaptive learning rate to converge, often resulting in better solutions. When we removed early stopping we observed the running time is about the same.

This should be a cleaner version of #30045 (I made a mess since I'm still pretty new to git).

@github-actions

github-actions Bot commented Oct 12, 2024 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: 2746f34. Link to the linter CI: here

@adrinjalali

Copy link
Copy Markdown
Member

The diff is indeed relatively small, however, the paper is quite recent, and the improvements are marginal. So I'll let @ogrisel , @lorentzenchr , @jeremiedbb, and @GaelVaroquaux weigh in here.

@adrinjalali adrinjalali added the Needs Decision Requires decision label Oct 14, 2024
@ogrisel

ogrisel commented Oct 14, 2024 •

Copy link
Copy Markdown
Member

I have similar feelings. Unfortunately, arxiv.org seems to be unresponsive since yesterday for me. I cannot check the benchmark results from the paper.

@BenJourdan could you please add results for full-batch k-means to your plots? I am wondering if this can allow MB-k-means to reach the same scores as full-batch k-means on those problems.

@BenJourdan

BenJourdan commented Oct 14, 2024 •

Copy link
Copy Markdown
Author

Here are the results with full-batch k-means added:
results_default_params

If you mess around with the early stopping condition tol, this also affects runtime/performance. It's not exactly apples to apples to compare tol values between the mini-batch and full-batch methods but I imagine it's what users may reach for first if they are worried about runtime. max_no_improvement will also have an effect.

This was with tol=1e-1 for all the algorithms:
results_tol_1e-1

This was with tol=1e-2:
results_tol_1e-2

tol=1e-3:
results_tol_1e-3

tol=1e-4:
results_tol_1e-4

I can add more experiments varying max_no_improvement if that helps.

@BenJourdan
BenJourdan force-pushed the feature_mbkm_adaptive_lr branch from 35c5b19 to 158897a Compare October 14, 2024 15:47
@ogrisel

ogrisel commented Oct 17, 2024 •

Copy link
Copy Markdown
Member

Thanks for the update. So from those experiments, it appears that the new lr scheme can empirically help MBKMeans close the (smallish) gap with full-batch KMeans in terms of clustering quality while keeping favorable runtimes for datasets with many data points (e.g. MNIST size or larger).

But since the method was recently published, this PR does not technically meet our inclusion criteria, although we could be less strict in cases where this is an incremental improvement of an existing method implemented in scikit-learn.

I will mention this PR at our next monthly meeting.

@BenJourdan

Copy link
Copy Markdown
Author

What was the verdict @ogrisel?

@adrinjalali

Copy link
Copy Markdown
Member

There were no clear objections to include this, and I think a few of us are in favor of including it.

@BenJourdan

Copy link
Copy Markdown
Author

@ogrisel @adrinjalali what happens next? Should I start updating the branch?

@adrinjalali

Copy link
Copy Markdown
Member

@BenJourdan seems like it.

@BenJourdan
BenJourdan force-pushed the feature_mbkm_adaptive_lr branch from 65e49cb to 320a4b4 Compare November 6, 2024 16:06
@BenJourdan

Copy link
Copy Markdown
Author

Should I keep updating the branch until (if lol) someone gets assigned? Not sure what the convention is.

@gregoryschwartzman

Copy link
Copy Markdown

Hi @ogrisel, @adrinjalali,

Just checking in—since there were no objections during the meeting and some support for inclusion, would it make sense to remove the Needs Decision label and move toward review/approval?

Please let me know what you'd recommend as the next step. Thanks again for your time and feedback so far!

@adrinjalali adrinjalali removed the Needs Decision Requires decision label Apr 23, 2025
@adrinjalali

Copy link
Copy Markdown
Member

I've removed "need decision" here. I think we can move forward with this.

@gregoryschwartzman

Copy link
Copy Markdown

Great! Let us know if we should do anything on our end.

@adrinjalali

Copy link
Copy Markdown
Member

@antoinebaker would you mind having a look at this PR for a review?

@antoinebaker antoinebaker left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR @BenJourdan ! Here a first round of review.

Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
@antoinebaker

Copy link
Copy Markdown
Member

I feel the code could be simplified by first defining a learning rate:

if adaptive_lr:
    lr = sqrt(wsum / wsum_batch)
else:
    lr = wsum / (weight_sums[cluster_idx] + wsum)

and then do the common updates

for feature_idx in range(n_features):
    centers_new[cluster_idx, feature_idx] = (1 - lr) * centers_old[cluster_idx, feature_idx]
for k in range(n_indices):
    sample_idx = indices[k]
    for feature_idx in range(n_features):
        weight_idx =  sample_weight[sample_idx] / wsum
        centers_new[cluster_idx, feature_idx] += lr * weight_idx * X[sample_idx, feature_idx]

@BenJourdan BenJourdan left a comment •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the feedback. I'll add most of your suggestions as are.

Introducing the learning rate to avoid duplicating code is a good idea. However, it's a bit messy since we need to do an optimization that avoids explicitly computing the means of each batch for a given center. I'll have a go at redrafting those parts.

Thanks!

Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_kmeans.py Resolved
@BenJourdan
BenJourdan force-pushed the feature_mbkm_adaptive_lr branch 4 times, most recently from 0bf05ba to 0094c8e Compare May 1, 2025 15:41
@BenJourdan
BenJourdan force-pushed the feature_mbkm_adaptive_lr branch from 0094c8e to 13fe041 Compare May 1, 2025 15:46
@adrinjalali

Copy link
Copy Markdown
Member

@BenJourdan please (at almost all cost) avoid force pushing here. It makes review harder.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds an optional adaptive learning-rate update rule to MiniBatchKMeans, wiring a new adaptive_lr parameter through the Python estimator, the _mini_batch_step helper, and the Cython dense/sparse update kernels, with accompanying documentation and a regression test.

Changes:

  • Add adaptive_lr parameter to MiniBatchKMeans and plumb it through fit/partial_fit into the minibatch update step.
  • Implement adaptive learning-rate center updates in the Cython dense and sparse minibatch update routines.
  • Add a targeted unit test for partial_fit behavior + a whatsnew entry.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.

File Description
sklearn/cluster/tests/test_k_means.py Adds a regression test validating adaptive-LR updates for partial_fit.
sklearn/cluster/_kmeans.py Introduces the adaptive_lr public parameter and passes it through fit/partial_fit to minibatch updates.
sklearn/cluster/_k_means_minibatch.pyx Implements the adaptive learning-rate update rule in dense and sparse center updates.
doc/whats_new/upcoming_changes/sklearn.cluster/30051.enhancement.rst Documents the new adaptive_lr=True feature in the changelog.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an adaptive_lr option to sklearn.cluster.MiniBatchKMeans to update cluster centers using an adaptive learning rate (per the referenced arXiv paper), and wires it through both fit and partial_fit paths with corresponding tests and release notes.

Changes:

  • Introduce adaptive_lr parameter on MiniBatchKMeans and propagate it through _mini_batch_step.
  • Implement adaptive learning-rate center updates in the Cython minibatch update kernels (dense + sparse).
  • Add targeted unit tests for expected update behavior and a whats-new entry.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
sklearn/cluster/_kmeans.py Adds adaptive_lr parameter, validation tweaks, plumbing into minibatch step, and class doc/reference updates.
sklearn/cluster/_k_means_minibatch.pyx Implements adaptive learning rate update rule in dense/sparse minibatch center updates.
sklearn/cluster/tests/test_k_means.py Adds regression tests validating adaptive LR behavior for partial_fit and fit.
doc/whats_new/upcoming_changes/sklearn.cluster/30051.enhancement.rst Documents the new adaptive_lr=True capability in release notes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/tests/test_k_means.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an optional adaptive learning rate path to MiniBatchKMeans, with Cython-level update logic and corresponding tests + release note, to improve minibatch center updates (per arXiv:2304.00419).

Changes:

  • Introduce adaptive_lr parameter on MiniBatchKMeans and thread it through minibatch update calls.
  • Implement adaptive learning rate updates in _k_means_minibatch.pyx for dense and sparse minibatch center updates.
  • Add targeted tests for adaptive_lr behavior and a whatsnew entry.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
sklearn/cluster/tests/test_k_means.py Adds tests covering adaptive LR convergence behavior and rejection of negative sample_weight.
sklearn/cluster/_kmeans.py Adds adaptive_lr parameter plumbing + sample_weight validation changes; updates docs/constraints.
sklearn/cluster/_k_means_minibatch.pyx Implements adaptive learning rate update rule in Cython minibatch update kernels.
doc/whats_new/upcoming_changes/sklearn.cluster/30051.enhancement.rst Announces the new adaptive_lr=True feature in MiniBatchKMeans.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds an optional “adaptive learning rate” variant to MiniBatchKMeans updates (per arXiv:2304.00419), wiring it through the Python estimator API down to the Cython mini-batch center update kernels, with accompanying tests and release notes.

Changes:

  • Add adaptive_lr parameter to MiniBatchKMeans and plumb it through _mini_batch_step into the dense/sparse minibatch update routines.
  • Implement adaptive learning-rate center updates in sklearn/cluster/_k_means_minibatch.pyx.
  • Add targeted tests for fit/partial_fit behavior and negative sample_weight validation; document the enhancement in the whatsnew entry.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
sklearn/cluster/_kmeans.py Exposes adaptive_lr on MiniBatchKMeans, validates sample weights accordingly, and forwards the flag into _mini_batch_step / Cython update calls.
sklearn/cluster/_k_means_minibatch.pyx Adds adaptive learning-rate support to dense and sparse minibatch center update kernels.
sklearn/cluster/tests/test_k_means.py Adds tests covering adaptive LR convergence behavior and negative sample_weight rejection when enabled.
doc/whats_new/upcoming_changes/sklearn.cluster/30051.enhancement.rst Notes the new adaptive_lr=True feature in upcoming release notes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

@BenJourdan

Copy link
Copy Markdown
Author

This needs a changelog, and also some sort of a test for the new setting.

I've added a changelog entry (doc/whats_new/upcoming_changes/sklearn.cluster/30051.enhancement.rst) and some tests:

I also accepted most of copilot's suggestions, although an "all-zero sample weights" check was unnecessary since _check_sample_weight already catches this.

@BenJourdan

Copy link
Copy Markdown
Author

@adrinjalali ready for you to take another look

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would take me quite some time to be able to do a proper review here, but trying to move this forward, I had a chat with my claude on this PR, and after about 2 hours of back and forth and me reading the code, I'm comfortable posting here what claude says. Of course I'd need you to take this as "Adrin thinks this makes sense" rather than "Adrin certainly believes all of this" @BenJourdan . I'm also genuinely curious to hear if these comments are helpful.

Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/_k_means_minibatch.pyx Resolved
Comment thread sklearn/cluster/tests/test_k_means.py Resolved
Comment thread sklearn/cluster/_kmeans.py Resolved
@BenJourdan

BenJourdan commented Mar 19, 2026 •

Copy link
Copy Markdown
Author

Hey @adrinjalali, I applied most of the changes Claude suggested. Most were useful but the one about not calling it an adaptive EMA and the one about weight_sums being accumulated were a little strange. I would say a useful exercise on the whole.

Edit: The suggested change to add the .. versionadded:: 1.9 line to the docstring introduced an error. It should also have include a blank line underneath, otherwise parsing fails. I'll fix that now.

@gregoryschwartzman

Copy link
Copy Markdown

@adrinjalali Gentle ping here. Thanks again for taking a look at this. If there are any remaining changes that would help get this over the line, we’d be very happy to make them.

@gregoryschwartzman

Copy link
Copy Markdown

@adrinjalali @ogrisel @antoinebaker — I’d like to get a definitive outcome on this PR.

It has now been open for nearly two years.

Could a maintainer please do one of the following:

  1. Approve and merge it.
  2. Identify the specific remaining blocker and assign or perform the final review.
  3. Close the PR if the project no longer intends to accept this change.

We’re happy to address concrete blockers, but we can’t keep maintaining an indefinitely idle PR. If nobody has the bandwidth to own the final review, a clear decision to close it is completely fine.

@antoinebaker antoinebaker moved this to PR waiting for reviews in Labs Aug 17, 2026
@lesteve lesteve removed this from Labs Sep 7, 2026

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants