Skip to content

ENH Fix the eigsh call in spectral embedding - #33262

Merged
jeremiedbb merged 32 commits into
scikit-learn:mainfrom
dkobak:spectral-eigsh
Apr 23, 2026
Merged

jeremiedbb merged 32 commits into
scikit-learn:mainfrom
dkobak:spectral-eigsh

Conversation

@dkobak

@dkobak dkobak commented Feb 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #33242

This fixes the way eigsh() is called in spectral embedding. As a result, it gets faster:

import numpy as np
from sklearn.manifold import SpectralEmbedding
from sklearn.datasets import make_swiss_roll

X, _ = make_swiss_roll(n_samples=10_000)
%time Z = SpectralEmbedding(eigen_solver="arpack", affinity="rbf", eigen_tol=0).fit_transform(X)

On my machine, this runs in 24 seconds on current main, and in 11 second after my fix. I am using affinity="rbf" here to get a dense N x N affinity matrix (with sparse matrix it's much faster).

@dkobak

dkobak commented Feb 11, 2026

Copy link
Copy Markdown
Contributor Author

Oh wow, some tests fail but only in some environments (on my local machine all tests pass). At the moment I have no idea why.

@ogrisel

ogrisel commented Feb 11, 2026

Copy link
Copy Markdown
Member

You can set SKLEARN_TESTS_GLOBAL_RANDOM_SEED=all to run the global_random_seed-parametrized tests with all admissible RNG seeds.

@dkobak

dkobak commented Feb 11, 2026

Copy link
Copy Markdown
Contributor Author

@ogrisel Thanks, I did not know about it. But this does not seem to be the problem here. On my machine

SKLEARN_TESTS_GLOBAL_RANDOM_SEED="all" pytest sklearn/cluster/tests/test_spectral.py 

passes for all seeds, but here we see some failing tests in test_spectral.py in some environments. Also, some tests in test_spectral_embedding.py are also failing in some environments but that file does not use global_random_seed at all...

This must be due to some ARPACK-related differences, right? I only changed one single thing that only affects one eigsh call...

@dkobak

dkobak commented Feb 11, 2026

Copy link
Copy Markdown
Contributor Author

OK it seems the issue was due to conversion between different scipy.sparse formats (I found similar thing discussed in a closed PR), so I rewrote it to avoid such conversion.

@dkobak

dkobak commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor Author

OK I followed an advice of @lobpcg found in some very old comment thread #14647 (comment) and updated the PR accordingly. Tests look better now, but some tests still fail in some environments. One of the failing tests is test_precomputed_nearest_neighbors_filtering which has recently caused problems here #31262 where @ogrisel implemented some fix. Not sure why it fails now with this PR.

@dkobak

dkobak commented Feb 12, 2026

Copy link
Copy Markdown
Contributor Author

Status update. I have fixed everything and all tests now pass :-) I added one new test and had to fiddle with some of the old tests to make them less fragile. This is ready for review @ogrisel.

In the process I changed my actual fix to the eigsh call. I failed to run it on I - L without failing tests in some environments for strange reasons. But then I found an old comment by @lobpcg (#14647 (comment)) where he says that this is a weird way to run eigsh anyway, and we should call it on L directly, with sigma set close to 0. I agree that conceptually it makes more sense. So I implemented this now. HOWEVER, I don't see a consistent runtime improvement anymore.

So this PR boils down to some refactoring and improved tests, but I do not claim increased runtime... What do you think?

@adrinjalali

Copy link
Copy Markdown
Member

As you say, it looks like in the end we can't get the performance benefit we were hoping, and what I'm not sure of, is if the change is required. Would it make sense to only update the inline comment for future contributors not to chase the same route as you did and leave it at that?

@lobpcg

lobpcg commented Feb 16, 2026

Copy link
Copy Markdown
Contributor

I support the proposed changes. The PR fixes the current undocumented and meaningless setup. It also removes simply unnecessary operations -L thus has performance benefits even though not as dramatic as originally hoped for.

@dkobak

dkobak commented Feb 17, 2026

Copy link
Copy Markdown
Contributor Author

@adrinjalali @lobpcg I ran the runtime comparison a bit more systematically (multiple runs for two sample sizes) and the good news is, I do see a runtime improvement after all!

The code is:

X, _ = make_swiss_roll(n_samples=N) # I tried 5000 and 10000
%time Z = SpectralEmbedding(eigen_solver="arpack", affinity="rbf", eigen_tol=0).fit_transform(X)

Results:
comparison

@dkobak

dkobak commented Feb 17, 2026

Copy link
Copy Markdown
Contributor Author

@lobpcg In the code, if ARPACK with shift-invert fails with a RuntimeError, then LOBPCG is used instead. Do you know how to trigger this situation? I would like to add a unit test that checks that this situation is handled correctly, but I have no idea how to trigger this.

        try:
            ...
            ... = eigsh(laplacian, k=n_components, sigma=-1e-5, which="LM", tol=tol, v0=v0)
            ...
        except RuntimeError:
            # When submatrices are exactly singular, an LU decomposition
            # in arpack fails. We fallback to lobpcg
            warnings.warn("ARPACK has failed, falling back to LOBPCG.")
            eigen_solver = "lobpcg"

@lobpcg

lobpcg commented Feb 18, 2026 •

Copy link
Copy Markdown
Contributor

@lobpcg In the code, if ARPACK with shift-invert fails with a RuntimeError, then LOBPCG is used instead. Do you know how to trigger this situation? I would like to add a unit test that checks that this situation is handled correctly, but I have no idea how to trigger this.

        try:
            ...
            ... = eigsh(laplacian, k=n_components, sigma=-1e-5, which="LM", tol=tol, v0=v0)
            ...
        except RuntimeError:
            # When submatrices are exactly singular, an LU decomposition
            # in arpack fails. We fallback to lobpcg
            warnings.warn("ARPACK has failed, falling back to LOBPCG.")
            eigen_solver = "lobpcg"

Choose sigma to make the shifted Laplacian singular, i.e. use an eigenvalue of the Laplacian. Precompute it a priori for the given example and hard code it to save the test time.

@dkobak

dkobak commented Feb 26, 2026

Copy link
Copy Markdown
Contributor Author

@adrinjalali Gentle ping to check out my updated more systematic runtime comparison above :-)

@lobpcg

lobpcg commented Feb 26, 2026

Copy link
Copy Markdown
Contributor

Choose sigma to make the shifted Laplacian singular, i.e. use an eigenvalue of the Laplacian. Precompute it a priori for the given example and hard code it to save the test time.

Well, but the actual code uses sigma=-1e-5 and all eigenvalues are non-negative. Does it mean that eigsh should not fail and we can remove the entire try ... except condition with fallback to LOBPCG?

I thought it was in a unit test not the function itself.

Well, ARPACK should not fail for that specific reason with such a call in theory but it's a complicated algorithm so I would keep the check to be safe. Only maybe change the comment to reflect the current status of the choice of the shift in this PR.

@dkobak dkobak changed the title Fix the eigsh call in spectral embedding PERF Fix the eigsh call in spectral embedding Mar 3, 2026
@dkobak dkobak changed the title PERF Fix the eigsh call in spectral embedding ENH Fix the eigsh call in spectral embedding Mar 10, 2026
@dkobak

dkobak commented Mar 12, 2026

Copy link
Copy Markdown
Contributor Author

@antoinebaker Maybe you would also be interested in taking a look at this PR. Would be great to have your review! Cheers.

@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 @dkobak ! The code path for the dealing with the eigen_solver is much clearer now.

LGTM overall, a few minor comments below.

Comment thread sklearn/manifold/_spectral_embedding.py Resolved
@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Apr 1, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Apr 1, 2026
@dkobak

dkobak commented Apr 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @antoinebaker, all suggestions merged/implemented.

@jeremiedbb jeremiedbb added this to the 1.9 milestone Apr 9, 2026

@jeremiedbb jeremiedbb 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.

LGTM. Thanks @dkobak !

@jeremiedbb
jeremiedbb enabled auto-merge (squash) April 23, 2026 15:32
@jeremiedbb
jeremiedbb merged commit aaa103d into scikit-learn:main Apr 23, 2026
31 checks passed
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.

The eigsh call in spectral embedding is done wrong and differently from what is described in the comments

6 participants