8000 FIX Fixed infinite loop in cluster._spectral.discretize (#21271) · thomasjpfan/scikit-learn@39566fe · GitHub
[go: up one dir, main page]

Skip to content

Commit 39566fe

Browse files
martintbthomasjpfanglemaitre
authored
FIX Fixed infinite loop in cluster._spectral.discretize (scikit-learn#21271)
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com> Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com>
1 parent b07b227 commit 39566fe

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

doc/whats_new/v1.0.rst

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@ Version 1.0.2
1212
Changelog
1313
---------
1414

15+
:mod:`sklearn.cluster`
16+
......................
17+
18+
- |Fix| Fixed an infinite loop in :func:`cluster.SpectralClustering` by
19+
moving an iteration counter from try to except.
20+
:pr:`21271` by :user:`Tyler Martin <martintb>`
21+
1522
:mod:`sklearn.decomposition`
1623
............................
1724

@@ -28,7 +35,6 @@ Changelog
2835
descriptions in the generated HTML. :pr:`21493` by
2936
:user:`Aurélien Geron <ageron>`.
3037

31-
3238
.. _changes_1_0_1:
3339

3440
Version 1.0.1

sklearn/cluster/_spectral.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,8 @@ def discretize(
172172

173173
try:
174174
U, S, Vh = np.linalg.svd(t_svd)
175-
svd_restarts += 1
176175
except LinAlgError:
176+
svd_restarts += 1
177177
print("SVD did not converge, randomizing and trying again")
178178
break
179179

sklearn/cluster/tests/test_spectral.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import numpy as np
55
from scipy import sparse
6+
from scipy.linalg import LinAlgError
67

78
import pytest
89

@@ -354,3 +355,19 @@ def test_spectral_clustering_np_matrix_raises():
354355
msg = r"spectral_clustering does not support passing in affinity as an np\.matrix"
355356
with pytest.raises(TypeError, match=msg):
356357
spectral_clustering(X)
358+
359+
360+
def test_spectral_clustering_not_infinite_loop(capsys, monkeypatch):
361+
"""Check that discretize raises LinAlgError when svd never converges.
362+
363+
Non-regression test for #21380
364+
"""
365+
366+
def new_svd(*args, **kwargs):
367+
raise LinAlgError()
368+
369+
monkeypatch.setattr(np.linalg, "svd", new_svd)
370+
vectors = np.ones((10, 4))
371+
372+
with pytest.raises(LinAlgError, match="SVD did not converge"):
373+
discretize(vectors)

0 commit comments

Comments
 (0)
0