Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ Changelogs for this project are recorded in this file since v0.2.0.
* Support for sklearn version 1.5 is dropped
* Support for Python versions 3.10 is dropped

### Fixed

* `KernelKMeans` no longer keeps the `labels_` of a failed attempt when every initialization leads to an empty cluster. The model is now left unfitted (`labels_` is `None` and `predict` raises `NotFittedError`) and a `ConvergenceWarning` is emitted. ([#788](https://github.com/tslearn-team/tslearn/issues/788))

## [v0.10.0]

### Added
Expand Down
46 changes: 42 additions & 4 deletions tests/test_clustering.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest

from scipy.spatial.distance import cdist
from sklearn.exceptions import ConvergenceWarning, NotFittedError

from tslearn.clustering import (
EmptyClusterError,
Expand Down Expand Up @@ -63,11 +64,13 @@ def test_kernel_kmeans():
random_state=rng).fit(time_series)
np.testing.assert_allclose(gak_km.labels_, gak_km.predict(time_series))

gak_km = KernelKMeans(n_clusters=101,
verbose=False,
max_iter=5,
random_state=rng).fit(time_series)
with pytest.warns(ConvergenceWarning, match="empty cluster"):
gak_km = KernelKMeans(n_clusters=101,
verbose=False,
max_iter=5,
random_state=rng).fit(time_series)
assert gak_km._X_fit is None
assert gak_km.labels_ is None

with pytest.raises(RuntimeError):
KernelKMeans(n_clusters=101,
Expand All @@ -85,6 +88,41 @@ def test_kernel_kmeans():
assert gak_km.sigma_gak_ is None


def test_kernel_kmeans_all_inits_empty_cluster():
# 15 time series with only 3 distinct values cannot be split into 4
# non-empty clusters, so every initialization raises EmptyClusterError.
# The model must then be left in an unfitted state instead of exposing
# the labels of a failed attempt.
X = np.repeat([0., 1., 5.], 5)[:, None, None]

model = KernelKMeans(n_clusters=4, kernel="rbf", random_state=0)
with pytest.warns(ConvergenceWarning, match="empty cluster"):
model.fit(X)

assert model._X_fit is None
assert model.labels_ is None
assert model.inertia_ == np.inf
assert model.n_iter_ == 0
assert not hasattr(model, "n_features_in_")

with pytest.raises(NotFittedError):
model.predict(X)

model = KernelKMeans(n_clusters=4, kernel="rbf", random_state=0)
with pytest.warns(ConvergenceWarning, match="empty cluster"):
labels = model.fit_predict(X)
assert labels is None

# A regular fit on the same model instance recovers a fitted state
model.set_params(n_clusters=3)
with warnings.catch_warnings():
warnings.simplefilter("error", ConvergenceWarning)
model.fit(X)
assert model.labels_ is not None
assert model.n_features_in_ == 1
np.testing.assert_array_equal(model.predict(X), model.labels_)


def test_kmeans():
n, sz, d = 15, 10, 3
rng = np.random.RandomState(0)
Expand Down
26 changes: 25 additions & 1 deletion tslearn/clustering/kmeans.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""K-means related clustering for time series."""
import warnings

import numpy

from scipy.spatial.distance import cdist

from sklearn.base import ClusterMixin, TransformerMixin, BaseEstimator
from sklearn.cluster._kmeans import _kmeans_plusplus
from sklearn.exceptions import ConvergenceWarning
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.utils import check_random_state
from sklearn.utils.validation import _check_sample_weight
Expand Down Expand Up @@ -248,6 +251,12 @@ def _is_fitted(self):
check_is_fitted(self, "_X_fit")
return True

def __sklearn_is_fitted__(self):
# ``_X_fit`` is None when every initialization failed (see ``fit``),
# in which case the model must not be considered fitted even though
# the attribute exists.
return getattr(self, "_X_fit", None) is not None

def _get_model_params(self):
params = super()._get_model_params()
params.update({"_X_fit": self._X_fit})
Expand Down Expand Up @@ -384,6 +393,21 @@ def fit(self, X, y=None, sample_weight=None):
self.inertia_ = min_inertia
self._X_fit = X
self.n_features_in_ = X.shape[-1]
else:
# Every initialization raised EmptyClusterError: discard the
# attributes left over from the last failed attempt so that the
# model does not look fitted.
self.labels_ = None
self.inertia_ = numpy.inf
warnings.warn(
"All initializations of %s led to at least one empty "
"cluster, so no valid clustering could be found. The model "
"is left unfitted (labels_ is None, and predict will raise "
"NotFittedError). Consider decreasing n_clusters or "
"increasing n_init."
% type(self).__name__,
ConvergenceWarning
)
return self

def _compute_dist(self, K, dist):
Expand Down Expand Up @@ -445,7 +469,7 @@ def predict(self, X):
Index of the cluster each sample belongs to.
"""
X = check_array(X, allow_nd=True, force_all_finite=False)
check_is_fitted(self, "_X_fit")
check_is_fitted(self)
X = check_dims(X, X_fit_dims=self._X_fit.shape, check_n_features_only=True)
K = self._get_kernel(X, self._X_fit)
n_samples = X.shape[0]
Expand Down