MiniBatchKMeans
- class sklearn.cluster.MiniBatchKMeans(n_clusters=8, *, init='k-means++', max_iter=100, batch_size=1024, verbose=0, compute_labels=, , , , , ,
Mini-Batch K-Means clustering.
Read more in the User Guide.
The number of clusters to form as well as the number of centroids to generate.
Method for initialization:
‘k-means++’ : selects initial cluster centroids using sampling based on an empirical probability distribution of the points’ contribution to the overall inertia. This technique speeds up convergence. The algorithm implemented is “greedy k-means++”. It differs from the vanilla k-means++ by making several trials at each sampling step and choosing the best centroid among them.
‘random’: choose n_clusters observations (rows) at random from data
for the initial centroids.
If an array is passed, it should be of shape (n_clusters, n_features) and gives the initial centers.
If a callable is passed, it should take arguments X, n_clusters and a random state and return an initialization.
For an evaluation of the impact of initialization, see the example Empirical evaluation of the impact of k-means initialization.
Maximum number of iterations over the complete dataset before stopping independently of any early stopping criterion heuristics.
Size of the mini batches.
For faster computations, you can set batch_size > 256 * number_of_cores
to enable parallelism
on all cores.
Verbosity mode.
Compute label assignment and inertia for the complete dataset once the minibatch optimization has converged in fit.
Determines random number generation for centroid initialization and random reassignment. Use an int to make the randomness deterministic. See Glossary.
Control early stopping based on the relative center changes as measured by a smoothed, variance-normalized of the mean center squared position changes. This early stopping heuristics is closer to the one used for the batch variant of the algorithms but induces a slight computational and memory overhead over the inertia heuristic.
To disable convergence detection based on normalized center change, set tol to 0.0 (default).
Control early stopping based on the consecutive number of mini batches that does not yield an improvement on the smoothed inertia.
To disable convergence detection based on inertia, set max_no_improvement to None.
Number of samples to randomly sample for speeding up the initialization (sometimes at the expense of accuracy): the only algorithm is initialized by running a batch KMeans on a random subset of the data. This needs to be larger than n_clusters.
If None, the heuristic is init_size = 3 * batch_size if
3 * batch_size < n_clusters, else init_size = 3 * n_clusters.
Number of random initializations that are tried.
In contrast to KMeans, the algorithm is only run once, using the best of
the n_init initializations as measured by inertia. Several runs are
recommended for sparse high-dimensional problems (see
Clustering sparse data with k-means).
When n_init='auto', the number of runs depends on the value of init:
3 if using init='random' or init is a callable;
1 if using init='k-means++' or init is an array-like.
Control the fraction of the maximum number of counts for a center to be reassigned. A higher value means that low count centers are more easily reassigned, which means that the model will take longer to converge, but should converge in a better clustering. However, too high a value may cause convergence issues, especially with a small batch size.
Coordinates of cluster centers.
Labels of each point (if compute_labels is set to True).
The value of the inertia criterion associated with the chosen partition if compute_labels is set to True. If compute_labels is set to False, it’s an approximation of the inertia based on an exponentially weighted average of the batch inertiae. The inertia is defined as the sum of square distances of samples to their cluster center, weighted by the sample weights if provided.
Number of iterations over the full dataset.
Number of minibatches processed.
See https://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf
When there are too few points in the dataset, some centers may be
duplicated, which means that a proper clustering in terms of the number
of requesting clusters and the number of returned clusters will not
always match. One solution is to set reassignment_ratio=0, which
prevents reassignments of clusters that are too small.
See Compare BIRCH and MiniBatchKMeans for a
comparison with BIRCH.
>>> from sklearn.cluster import MiniBatchKMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [
For a comparison of Mini-Batch K-Means clustering with other clustering algorithms, see Comparing different clustering algorithms on toy datasets
Compute the centroids on X by chunking it into mini-batches.
Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous. If a sparse matrix is passed, a copy will be made if it’s not in CSR format.
Not used, present here for API consistency by convention.
Compute cluster centers and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by predict(X).
New data to transform.
Not used, present here for API consistency by convention.
Compute clustering and transform X to cluster-distance space.
Equivalent to fit(X).transform(X), but more efficiently implemented.
New data to transform.
Not used, present here for API consistency by convention.
Get output feature names for transformation.
The feature names out will prefixed by the lowercased class name. For
example, if the transformer outputs 3 features, then the feature names
out are: ["class_name0", "class_name1", "class_name2"].
Only used to validate feature names with the names seen in fit.
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
A MetadataRequest encapsulating
routing information.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Update k means estimate on a single mini-batch X.
Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous. If a sparse matrix is passed, a copy will be made if it’s not in CSR format.
Not used, present here for API consistency by convention.
Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, cluster_centers_ is called
the code book and each value returned by predict is the index of
the closest code in the code book.
New data to predict.
Opposite of the value of X on the K-means objective.
New data.
Not used, present here for API consistency by convention.
Configure whether metadata should be requested to be passed to the method.
Set output container.
Refer to the user guide for more details and Introducing the set_output API for an example on how to use the API.
Configure output of transform and .
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as Pipeline). The latter have
parameters of the form <component>__<parameter> so that it’s
possible to update each component of a nested object.
Estimator parameters.
Configure whether metadata should be requested to be passed to the method.
Configure whether metadata should be requested to be passed to the method.
Transform X to a cluster-distance space.
In the new space, each dimension is the distance to the cluster
centers. Note that even if X is sparse, the array returned by
transform will typically be dense.
New data to transform.
X transformed in the new space.
Biclustering documents with the Spectral Co-clustering algorithm
Comparing different clustering algorithms on toy datasets
Empirical evaluation of the impact of k-means initialization
Comparison of the K-Means and MiniBatchKMeans clustering algorithms
Added in version 1.0.
Number of features seen during fit.
n_features_in_,)Names of features seen during fit. Defined only when X
has feature names that are all strings.
The weights for each observation in X. If None, all observations
are assigned equal weight. sample_weight is not used during
initialization if init is a callable or a user provided array.
Fitted estimator.
The weights for each observation in X. If None, all observations are assigned equal weight.
Index of the cluster each sample belongs to.
The weights for each observation in X. If None, all observations are assigned equal weight.
X transformed in the new space.
Transformed feature names.
The weights for each observation in X. If None, all observations
are assigned equal weight. sample_weight is not used during
initialization if init is a callable or a user provided array.
Return updated estimator.
Index of the cluster each sample belongs to.
The weights for each observation in X. If None, all observations are assigned equal weight.
Opposite of the value of X on the K-means objective.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Metadata routing for sample_weight parameter in fit.
The updated object.
"default": Default output format of a transformer
"pandas": DataFrame output
"polars": Polars output
None: Transform configuration is unchanged
Estimator instance.
Estimator instance.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to partial_fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to partial_fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Metadata routing for sample_weight parameter in partial_fit.
The updated object.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to score.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Metadata routing for sample_weight parameter in score.
The updated object.