88from numbers import Integral , Real
99
1010import numpy as np
11- import scipy .sparse as sp
1211
1312from sklearn .base import _fit_context
1413from sklearn .cluster ._k_means_common import CHUNK_SIZE
15- from sklearn .cluster ._k_means_emeans import _emeans_step_dense , _emeans_step_sparse
14+ from sklearn .cluster ._k_means_emeans import _emeans_step
1615from sklearn .cluster ._kmeans import _BaseKMeans , _labels_inertia_threadpool_limit
1716from sklearn .utils import check_array , check_random_state
1817from sklearn .utils ._openmp_helpers import _openmp_effective_n_threads
1918from sklearn .utils ._param_validation import Interval , StrOptions
2019from sklearn .utils .extmath import row_norms
2120from sklearn .utils .parallel import _get_threadpool_controller
22- from sklearn .utils .validation import (
23- _check_sample_weight ,
24- _is_arraylike_not_scalar ,
25- validate_data ,
26- )
21+ from sklearn .utils .validation import _is_arraylike_not_scalar , validate_data
2722
2823# The constants below are the ones of the reference implementation
2924# (faiss/contrib/e_means/base.py), which differ slightly from the paper.
4136# Relative perturbation of the two halves of a split donor center.
4237_SPLIT_EPSILON = 1e-4
4338
44- # Initial EMA weight of each center, relative to the mean sample weight. Tiny,
45- # so that the first batch moves the centers to the mean of their rows.
39+ # Initial EMA weight of each center. Tiny, so that the first batch moves the
40+ # centers to the mean of their rows.
4641_INIT_WEIGHT = 2.0 ** - 16
4742
4843# The reference implementation turns revival off for n_features <= 2, where it
@@ -216,9 +211,6 @@ class EMeans(_BaseKMeans):
216211 smaller batches when `n_features <= 16`. The initial step size is
217212 always given by the scaling law, as a function of the batch size.
218213
219- verbose : int, default=0
220- Verbosity mode.
221-
222214 random_state : int, RandomState instance or None, default=None
223215 Determines random number generation for centroid initialization, the
224216 order of the samples in each epoch and the revival of dead clusters.
@@ -234,8 +226,7 @@ class EMeans(_BaseKMeans):
234226 Labels of each point.
235227
236228 inertia_ : float
237- Sum of squared distances of samples to their closest cluster center,
238- weighted by the sample weights if provided.
229+ Sum of squared distances of samples to their closest cluster center.
239230
240231 n_iter_ : int
241232 Number of epochs run.
@@ -263,7 +254,7 @@ class EMeans(_BaseKMeans):
263254 -----
264255 The algorithm is described in [1]_. For each mini-batch of samples, each
265256 sample is assigned to its nearest center, then each center :math:`c_j` is
266- updated from the sum :math:`s_j` and the weight :math:`n_j` of the samples
257+ updated from the sum :math:`s_j` and the number :math:`n_j` of the samples
267258 assigned to it:
268259
269260 .. math::
@@ -306,7 +297,6 @@ class EMeans(_BaseKMeans):
306297 StrOptions ({"auto" }),
307298 Interval (Integral , 1 , None , closed = "left" ),
308299 ],
309- "verbose" : ["verbose" ],
310300 "random_state" : ["random_state" ],
311301 }
312302
@@ -317,14 +307,12 @@ def __init__(
317307 init = "random" ,
318308 n_epochs = 5 ,
319309 batch_size = "auto" ,
320- verbose = 0 ,
321310 random_state = None ,
322311 ):
323312 self .n_clusters = n_clusters
324313 self .init = init
325314 self .n_epochs = n_epochs
326315 self .batch_size = batch_size
327- self .verbose = verbose
328316 self .random_state = random_state
329317
330318 def _check_params_vs_input (self , X ):
@@ -344,42 +332,29 @@ def _warn_mkl_vcomp(self, n_active_threads):
344332 )
345333
346334 @_fit_context (prefer_skip_nested_validation = True )
347- def fit (self , X , y = None , sample_weight = None ):
335+ def fit (self , X , y = None ):
348336 """Compute e-means clustering.
349337
350338 Parameters
351339 ----------
352- X : { array-like, sparse matrix} of shape (n_samples, n_features)
340+ X : array-like of shape (n_samples, n_features)
353341 Training instances to cluster. It must be noted that the data
354342 will be converted to C ordering, which will cause a memory copy
355343 if the given data is not C-contiguous.
356- If a sparse matrix is passed, a copy will be made if it's not in
357- CSR format.
358344
359345 y : Ignored
360346 Not used, present here for API consistency by convention.
361347
362- sample_weight : array-like of shape (n_samples,), default=None
363- The weights for each observation in X. If None, all observations
364- are assigned equal weight. `sample_weight` is not used during
365- initialization if `init` is a callable or a user provided array.
366-
367348 Returns
368349 -------
369350 self : object
370351 Fitted estimator.
371352 """
372- X = validate_data (
373- self ,
374- X ,
375- accept_sparse = "csr" ,
376- dtype = [np .float64 , np .float32 ],
377- order = "C" ,
378- accept_large_sparse = False ,
379- )
353+ X = validate_data (self , X , dtype = [np .float64 , np .float32 ], order = "C" )
380354 self ._check_params_vs_input (X )
381355 random_state = check_random_state (self .random_state )
382- sample_weight = _check_sample_weight (sample_weight , X , dtype = X .dtype )
356+ # Unit weights for the k-means++ init and the final labels pass.
357+ sample_weight = np .ones (X .shape [0 ], dtype = X .dtype )
383358 self ._n_threads = _openmp_effective_n_threads ()
384359 n_samples , n_features = X .shape
385360 n_clusters = self .n_clusters
@@ -422,56 +397,34 @@ def fit(self, X, y=None, sample_weight=None):
422397 n_steps = sum (math .ceil (n_rows / batch_size ) for n_rows in epochs_n_rows )
423398 revival = n_features > _NO_REVIVAL_MAX_FEATURES
424399
425- # Scaled by the mean sample weight, so that the result doesn't depend
426- # on the scale of the weights.
427- weight_ema = np .full (
428- n_clusters , _INIT_WEIGHT * sample_weight .mean (), dtype = np .float64
429- )
400+ weight_ema = np .full (n_clusters , _INIT_WEIGHT )
430401 epoch_sums = np .zeros ((n_clusters , n_features ), dtype = np .float64 )
431- epoch_weights = np .zeros (n_clusters , dtype = np .float64 )
432- emeans_step = _emeans_step_sparse if sp .issparse (X ) else _emeans_step_dense
433-
434- if self .verbose :
435- print (
436- f"Clustering { n_samples } samples into { n_clusters } clusters in "
437- f"{ self .n_epochs } epochs, batch_size={ batch_size } , initial "
438- f"step size={ initial_step_size :.3g} "
439- )
402+ epoch_counts = np .zeros (n_clusters , dtype = np .float64 )
440403
441404 step = 0
442405 with _get_threadpool_controller ().limit (limits = "sequential_blas_under_openmp" ):
443406 for epoch , n_rows in enumerate (epochs_n_rows ):
444407 is_last_epoch = epoch == len (epochs_n_rows ) - 1
445408 permutation = random_state .permutation (n_samples )
446- epoch_inertia , n_revived = 0.0 , 0
447409 for start in range (0 , n_rows , batch_size ):
448- epoch_inertia += emeans_step (
410+ _emeans_step (
449411 X ,
450- sample_weight ,
451412 permutation [start : min (start + batch_size , n_rows )],
452413 centers ,
453414 weight_ema ,
454415 _scheduled_step_size (initial_step_size , step , n_steps ),
455416 epoch_sums if is_last_epoch else None ,
456- epoch_weights if is_last_epoch else None ,
417+ epoch_counts if is_last_epoch else None ,
457418 n_threads ,
458419 )
459420 step += 1
460421 if revival and step % _REVIVAL_PERIOD == 0 :
461- n_revived += _revive_dead_clusters (
462- centers , weight_ema , random_state
463- )
464- if self .verbose :
465- print (
466- f"Epoch { epoch + 1 } /{ len (epochs_n_rows )} : inertia "
467- f"{ epoch_inertia } (measured on moving centers), "
468- f"{ n_revived } revived clusters"
469- )
422+ _revive_dead_clusters (centers , weight_ema , random_state )
470423
471424 # The final centers are the means of the last epoch's assignments.
472425 # Centers that got no sample in the last epoch keep their EMA position.
473- assigned = epoch_weights > 0
474- centers [assigned ] = epoch_sums [assigned ] / epoch_weights [assigned , None ]
426+ assigned = epoch_counts > 0
427+ centers [assigned ] = epoch_sums [assigned ] / epoch_counts [assigned , None ]
475428
476429 self .cluster_centers_ = centers
477430 self ._n_features_out = n_clusters
@@ -482,3 +435,49 @@ def fit(self, X, y=None, sample_weight=None):
482435 self .n_steps_ = n_steps
483436 self .batch_size_ = batch_size
484437 return self
438+
439+ def fit_predict (self , X , y = None ):
440+ """Compute cluster centers and predict cluster index for each sample.
441+
442+ Convenience method; equivalent to calling fit(X) followed by
443+ predict(X).
444+
445+ Parameters
446+ ----------
447+ X : array-like of shape (n_samples, n_features)
448+ New data to transform.
449+
450+ y : Ignored
451+ Not used, present here for API consistency by convention.
452+
453+ Returns
454+ -------
455+ labels : ndarray of shape (n_samples,)
456+ Index of the cluster each sample belongs to.
457+ """
458+ return self .fit (X ).labels_
459+
460+ def fit_transform (self , X , y = None ):
461+ """Compute clustering and transform X to cluster-distance space.
462+
463+ Equivalent to fit(X).transform(X), but more efficiently implemented.
464+
465+ Parameters
466+ ----------
467+ X : array-like of shape (n_samples, n_features)
468+ New data to transform.
469+
470+ y : Ignored
471+ Not used, present here for API consistency by convention.
472+
473+ Returns
474+ -------
475+ X_new : ndarray of shape (n_samples, n_clusters)
476+ X transformed in the new space.
477+ """
478+ return self .fit (X )._transform (X )
479+
480+ def __sklearn_tags__ (self ):
481+ tags = super ().__sklearn_tags__ ()
482+ tags .input_tags .sparse = False
483+ return tags
0 commit comments