Repository navigation
[MRG] Leave KShape/TimeSeriesKMeans unfitted when every initialization fails - #769
Merged
charavelg merged 6 commits intoNov 12, 2026
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #740
When every initialization of
KShaperaisesEmptyClusterError,fit()returned normally with_X_fit = Nonebut kept the
labels_andcluster_centers_written by the last failed attempt (they are assigned before theempty-cluster check raises), and
n_features_in_was set as if the fit had succeeded.check_is_fittedonlytests attribute existence, so
predict()silently returned labels from a model that never converged, andfit_predict()did the same, with no warning unlessverbose=True.TimeSeriesKMeansshares the same_post_fitand had the same behaviour.Changes:
TimeSeriesCentroidBasedClusteringMixin._post_fitresetslabels_,cluster_centers_,inertia_,n_iter_and
_X_fiton total failure, only setsn_features_in_on success, and emits aConvergenceWarningexplaining that no valid clustering was found (and suggesting a smaller
n_clusters/ largern_init).__sklearn_is_fitted__(fitted iffcluster_centers_ is not None), andKShape.predict,TimeSeriesKMeans.predict/transformcallcheck_is_fitted(self)so they raiseNotFittedErrorin that state. Deserialized models still restorecluster_centers_, so they are unaffected.Tests:
test_all_inits_empty_cluster(parametrized overKShapeandTimeSeriesKMeans): 12 identical serieswith
n_clusters=2, asserting the warning, the reset attributes,NotFittedErrorfrompredict/transform,and that a later successful
fiton the same instance works.test_kmeansasserted 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;
KShapewith the defaultn_clusters=3on series of length 2, which only havetwo distinct z-normalized shapes, so no fit could ever succeed;
_configurenow setsn_clusters=2forKShape.Related: #439, #269.