Skip to content

[MRG] Leave KShape/TimeSeriesKMeans unfitted when every initialization fails - #769

Merged
charavelg merged 6 commits into
tslearn-team:mainfrom
bhaskargurram-ai:fix/kshape-reset-state-on-failure
Nov 12, 2026
Merged

charavelg merged 6 commits into
tslearn-team:mainfrom
bhaskargurram-ai:fix/kshape-reset-state-on-failure

Conversation

@bhaskargurram-ai

Copy link
Copy Markdown
Contributor

Fixes #740

When every initialization of KShape raises EmptyClusterError, fit() returned normally with _X_fit = None
but kept the labels_ and cluster_centers_ written by the last failed attempt (they are assigned before the
empty-cluster check raises), and n_features_in_ was set as if the fit had succeeded. check_is_fitted only
tests attribute existence, so predict() silently returned labels from a model that never converged, and
fit_predict() did the same, with no warning unless verbose=True. TimeSeriesKMeans shares the same
_post_fit and had the same behaviour.

Changes:

  • TimeSeriesCentroidBasedClusteringMixin._post_fit resets labels_, cluster_centers_, inertia_, n_iter_
    and _X_fit on total failure, only sets n_features_in_ on success, and emits a ConvergenceWarning
    explaining that no valid clustering was found (and suggesting a smaller n_clusters / larger n_init).
  • The mixin implements __sklearn_is_fitted__ (fitted iff cluster_centers_ is not None), and
    KShape.predict, TimeSeriesKMeans.predict / transform call check_is_fitted(self) so they raise
    NotFittedError in that state. Deserialized models still restore cluster_centers_, so they are unaffected.
  • Successful fits are unchanged.

Tests:

  • New test_all_inits_empty_cluster (parametrized over KShape and TimeSeriesKMeans): 12 identical series
    with n_clusters=2, asserting the warning, the reset attributes, NotFittedError from predict/transform,
    and that a later successful fit on the same instance works.
  • Two existing tests relied on the stale state and were adjusted:
    • the forced-init DTW/softdtw case in test_kmeans asserted centroid sizes on a fit that failed on every attempt
      (random noise vs. the hand-written barycenters); it now uses data on which the fit succeeds, so the
      assertion (centroid length follows the init) is actually exercised;
    • the sklearn common checks ran KShape with the default n_clusters=3 on series of length 2, which only have
      two distinct z-normalized shapes, so no fit could ever succeed; _configure now sets n_clusters=2 for KShape.
  • CHANGELOG entry added.

Related: #439, #269.

When every initialization of KShape (or TimeSeriesKMeans, which shares
TimeSeriesCentroidBasedClusteringMixin._post_fit) raised
EmptyClusterError, fit() returned normally with _X_fit = None but kept
the labels_ and cluster_centers_ written by the last failed attempt, and
n_features_in_ was set as if the fit had succeeded. check_is_fitted only
tests attribute existence, so predict() silently returned labels from a
model that never converged, and fit_predict() did the same.

_post_fit now resets labels_, cluster_centers_, inertia_, n_iter_ and
_X_fit on total failure, only sets n_features_in_ on success, and emits
a ConvergenceWarning explaining that no valid clustering was found. The
mixin implements __sklearn_is_fitted__ based on cluster_centers_ so that
check_is_fitted(), and therefore predict()/transform(), raise
NotFittedError in that state. Successful fits are unchanged.

Two existing tests relied on the stale state: the forced-init case of
test_kmeans asserted on the centroids of a fit that failed on every
attempt (it now uses data on which the fit succeeds), and the sklearn
common checks ran KShape with n_clusters=3 on series of length 2, which
only have two distinct z-normalized shapes (KShape is now configured
with n_clusters=2 there).

Fixes tslearn-team#740
charavelg pushed a commit that referenced this pull request Nov 12, 2026
When every initialization raised EmptyClusterError, fit() kept the
labels_ of the last failed attempt and predict() failed with an
AttributeError. Reset labels_ and inertia_, emit a ConvergenceWarning
and make predict() raise NotFittedError, as #769 does for KShape and
TimeSeriesKMeans.

Fixes #788

Co-authored-by: Wleeaf <179125857+wleeaf@users.noreply.github.com>
@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.63%. Comparing base (59e38e0) to head (8ff678c).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #769   +/-   ##
=======================================
  Coverage   96.63%   96.63%           
=======================================
  Files          91       91           
  Lines        9615     9656   +41     
=======================================
+ Hits         9291     9331   +40     
- Misses        324      325    +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@charavelg
charavelg merged commit b6087c0 into tslearn-team:main Nov 12, 2026
21 of 23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants