- class sklearn.cluster.KMeans(n_clusters=8, *, init='k-means++', n_init='auto', max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True, algorithm='lloyd')[source]¶
K-Means clustering.
Read more in the User Guide.
- Parameters:
- n_clustersint, default=8
The number of clusters to form as well as the number ofcentroids to generate.
For an example of how to choose an optimal value for
n_clusters
refer toSelecting the number of clusters with silhouette analysis on KMeans clustering.- init{‘k-means++’, ‘random’}, callable or array-like of shape (n_clusters, n_features), default=’k-means++’
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 example of how to use the different
init
strategy, see the exampleentitled A demo of K-Means clustering on the handwritten digits data.- n_init‘auto’ or int, default=’auto’
Number of times the k-means algorithm is run with different centroidseeds. The final results is the best output of
n_init
consecutive runsin terms of inertia. Several runs are recommended for sparsehigh-dimensional problems (see Clustering sparse data with k-means).When
n_init='auto'
, the number of runs depends on the value of init:10 if usinginit='random'
orinit
is a callable;1 if usinginit='k-means++'
orinit
is an array-like.New in version 1.2: Added ‘auto’ option for
n_init
.Changed in version 1.4: Default value for
n_init
changed to'auto'
.- max_iterint, default=300
Maximum number of iterations of the k-means algorithm for asingle run.
- tolfloat, default=1e-4
Relative tolerance with regards to Frobenius norm of the differencein the cluster centers of two consecutive iterations to declareconvergence.
- verboseint, default=0
Verbosity mode.
- random_stateint, RandomState instance or None, default=None
Determines random number generation for centroid initialization. Usean int to make the randomness deterministic.See Glossary.
- copy_xbool, default=True
When pre-computing distances it is more numerically accurate to centerthe data first. If copy_x is True (default), then the original data isnot modified. If False, the original data is modified, and put backbefore the function returns, but small numerical differences may beintroduced by subtracting and then adding the data mean. Note that ifthe original data is not C-contiguous, a copy will be made even ifcopy_x is False. If the original data is sparse, but not in CSR format,a copy will be made even if copy_x is False.
- algorithm{“lloyd”, “elkan”}, default=”lloyd”
K-means algorithm to use. The classical EM-style algorithm is
"lloyd"
.The"elkan"
variation can be more efficient on some datasets withwell-defined clusters, by using the triangle inequality. However it’smore memory intensive due to the allocation of an extra array of shape(n_samples, n_clusters)
.Changed in version 0.18: Added Elkan algorithm
Changed in version 1.1: Renamed “full” to “lloyd”, and deprecated “auto” and “full”.Changed “auto” to use “lloyd” instead of “elkan”.
- Attributes:
- cluster_centers_ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers. If the algorithm stops before fullyconverging (see
tol
andmax_iter
), these will not beconsistent withlabels_
.- labels_ndarray of shape (n_samples,)
Labels of each point
- inertia_float
Sum of squared distances of samples to their closest cluster center,weighted by the sample weights if provided.
- n_iter_int
Number of iterations run.
- n_features_in_int
Number of features seen during fit.
New in version 0.24.
- feature_names_in_ndarray of shape (
n_features_in_
,) Names of features seen during fit. Defined only when
X
has feature names that are all strings.New in version 1.0.
See also
- MiniBatchKMeans
Alternative online implementation that does incremental updates of the centers positions using mini-batches. For large scale learning (say n_samples > 10k) MiniBatchKMeans is probably much faster than the default batch implementation.
Notes
The k-means problem is solved using either Lloyd’s or Elkan’s algorithm.
The average complexity is given by O(k n T), where n is the number ofsamples and T is the number of iteration.
The worst case complexity is given by O(n^(k+2/p)) withn = n_samples, p = n_features.Refer to “How slow is the k-means method?” D. Arthur and S. Vassilvitskii -SoCG2006. for more details.
In practice, the k-means algorithm is very fast (one of the fastestclustering algorithms available), but it falls in local minima. That’s whyit can be useful to restart it several times.
If the algorithm stops before fully converging (because of
tol
ormax_iter
),labels_
andcluster_centers_
will not be consistent,i.e. thecluster_centers_
will not be the means of the points in eachcluster. Also, the estimator will reassignlabels_
after the lastiteration to makelabels_
consistent withpredict
on the trainingset.Examples
>>> from sklearn.cluster import KMeans>>> import numpy as np>>> X = np.array([[1, 2], [1, 4], [1, 0],... [10, 2], [10, 4], [10, 0]])>>> kmeans = KMeans(n_clusters=2, random_state=0, n_init="auto").fit(X)>>> kmeans.labels_array([1, 1, 1, 0, 0, 0], dtype=int32)>>> kmeans.predict([[0, 0], [12, 3]])array([1, 0], dtype=int32)>>> kmeans.cluster_centers_array([[10., 2.], [ 1., 2.]])
For a more detailed example of K-Means using the iris dataset seeK-means Clustering.
For examples of common problems with K-Means and how to address them seeDemonstration of k-means assumptions.
For an example of how to use K-Means to perform color quantization seeColor Quantization using K-Means.
For a demonstration of how K-Means can be used to cluster text documents seeClustering text documents using k-means.
For a comparison between K-Means and MiniBatchKMeans refer to exampleComparison of the K-Means and MiniBatchKMeans clustering algorithms.
Methods
See AlsoK-Means & Other Clustering Algorithms: A Quick Intro with PythonK-Means Clustering in Python: Step-by-Step Example - StatologyTutorial for K Means Clustering in Python Sklearn - MLK - Machine Learning KnowledgeK Means Clustering with Pythonfit(X[,y,sample_weight])
Compute k-means clustering.
fit_predict(X[,y,sample_weight])
Compute cluster centers and predict cluster index for each sample.
fit_transform(X[,y,sample_weight])
Compute clustering and transform X to cluster-distance space.
get_feature_names_out([input_features])
Get output feature names for transformation.
get_metadata_routing()
Get metadata routing of this object.
get_params([deep])
Get parameters for this estimator.
predict(X[,sample_weight])
Predict the closest cluster each sample in X belongs to.
score(X[,y,sample_weight])
Opposite of the value of X on the K-means objective.
set_fit_request(*[,sample_weight])
Request metadata passed to the
fit
method.set_output(*[,transform])
Set output container.
set_params(**params)
Set the parameters of this estimator.
set_predict_request(*[,sample_weight])
Request metadata passed to the
predict
method.set_score_request(*[,sample_weight])
Request metadata passed to the
score
method.transform(X)
Transform X to a cluster-distance space.
- fit(X, y=None, sample_weight=None)[source]¶
Compute k-means clustering.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the datawill be converted to C ordering, which will cause a memorycopy if the given data is not C-contiguous.If a sparse matrix is passed, a copy will be made if it’s not inCSR format.
- yIgnored
Not used, present here for API consistency by convention.
- sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observationsare assigned equal weight.
sample_weight
is not used duringinitialization ifinit
is a callable or a user provided array.New in version 0.20.
- Returns:
- selfobject
Fitted estimator.
- fit_predict(X, y=None, sample_weight=None)[source]¶
Compute cluster centers and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed bypredict(X).
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
- yIgnored
Not used, present here for API consistency by convention.
- sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observationsare assigned equal weight.
- Returns:
- labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
- fit_transform(X, y=None, sample_weight=None)[source]¶
Compute clustering and transform X to cluster-distance space.
Equivalent to fit(X).transform(X), but more efficiently implemented.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
- yIgnored
Not used, present here for API consistency by convention.
- sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observationsare assigned equal weight.
- Returns:
- X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space.
- get_feature_names_out(input_features=None)[source]¶
Get output feature names for transformation.
The feature names out will prefixed by the lowercased class name. Forexample, if the transformer outputs 3 features, then the feature namesout are:
["class_name0", "class_name1", "class_name2"]
.- Parameters:
- input_featuresarray-like of str or None, default=None
Only used to validate feature names with the names seen in
fit
.
- Returns:
- feature_names_outndarray of str objects
Transformed feature names.
- get_metadata_routing()[source]¶
Get metadata routing of this object.
Please check User Guide on how the routingmechanism works.
- Returns:
- routingMetadataRequest
A MetadataRequest encapsulatingrouting information.
- get_params(deep=True)[source]¶
Get parameters for this estimator.
- Parameters:
- deepbool, default=True
If True, will return the parameters for this estimator andcontained subobjects that are estimators.
- Returns:
- paramsdict
Parameter names mapped to their values.
- predict(X, sample_weight='deprecated')[source]¶
Predict the closest cluster each sample in X belongs to.
In the vector quantization literature,
cluster_centers_
is calledthe code book and each value returned bypredict
is the index ofthe closest code in the code book.- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict.
- sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observationsare assigned equal weight.
Deprecated since version 1.3: The parameter
sample_weight
is deprecated in version 1.3and will be removed in 1.5.
- Returns:
- labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
- score(X, y=None, sample_weight=None)[source]¶
Opposite of the value of X on the K-means objective.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
New data.
- yIgnored
Not used, present here for API consistency by convention.
- sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observationsare assigned equal weight.
- Returns:
- scorefloat
Opposite of the value of X on the K-means objective.
- set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') → KMeans[source]¶
Request metadata passed to the
fit
method.Note that this method is only relevant if
enable_metadata_routing=True
(see sklearn.set_config).Please see User Guide on how the routingmechanism works.The options for each parameter are:
True
: metadata is requested, and passed tofit
if provided. The request is ignored if metadata is not provided.False
: metadata is not requested and the meta-estimator will not pass it tofit
.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 theexisting request. This allows you to change the request for someparameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as asub-estimator of a meta-estimator, e.g. used inside aPipeline. Otherwise it has no effect.
- Parameters:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
sample_weight
parameter infit
.
- Returns:
- selfobject
The updated object.
- set_output(*, transform=None)[source]¶
Set output container.
See Introducing the set_output APIfor an example on how to use the API.
- Parameters:
- transform{“default”, “pandas”}, default=None
Configure output of
transform
andfit_transform
."default"
: Default output format of a transformer"pandas"
: DataFrame output"polars"
: Polars outputNone
: Transform configuration is unchanged
New in version 1.4:
"polars"
option was added.
- Returns:
- selfestimator instance
Estimator instance.
- set_params(**params)[source]¶
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects(such as Pipeline). The latter haveparameters of the form
<component>__<parameter>
so that it’spossible to update each component of a nested object.- Parameters:
- **paramsdict
Estimator parameters.
- Returns:
- selfestimator instance
Estimator instance.
- set_predict_request(*, sample_weight: bool | None | str = '$UNCHANGED$') → KMeans[source]¶
Request metadata passed to the
predict
method.Note that this method is only relevant if
enable_metadata_routing=True
(see sklearn.set_config).Please see User Guide on how the routingmechanism works.The options for each parameter are:
True
: metadata is requested, and passed topredict
if provided. The request is ignored if metadata is not provided.False
: metadata is not requested and the meta-estimator will not pass it topredict
.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 theexisting request. This allows you to change the request for someparameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as asub-estimator of a meta-estimator, e.g. used inside aPipeline. Otherwise it has no effect.
- Parameters:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
sample_weight
parameter inpredict
.
- Returns:
- selfobject
The updated object.
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') → KMeans[source]¶
Request metadata passed to the
score
method.Note that this method is only relevant if
enable_metadata_routing=True
(see sklearn.set_config).Please see User Guide on how the routingmechanism works.The options for each parameter are:
True
: metadata is requested, and passed toscore
if provided. The request is ignored if metadata is not provided.False
: metadata is not requested and the meta-estimator will not pass it toscore
.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 theexisting request. This allows you to change the request for someparameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as asub-estimator of a meta-estimator, e.g. used inside aPipeline. Otherwise it has no effect.
- Parameters:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
sample_weight
parameter inscore
.
- Returns:
- selfobject
The updated object.
- transform(X)[source]¶
Transform X to a cluster-distance space.
In the new space, each dimension is the distance to the clustercenters. Note that even if X is sparse, the array returned by
transform
will typically be dense.- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
- Returns:
- X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space.
Examples using sklearn.cluster.KMeans
¶
Release Highlights for scikit-learn 1.1
Release Highlights for scikit-learn 1.1
Release Highlights for scikit-learn 0.23
Release Highlights for scikit-learn 0.23
A demo of K-Means clustering on the handwritten digits data
A demo of K-Means clustering on the handwritten digits data
Bisecting K-Means and Regular K-Means Performance Comparison
Bisecting K-Means and Regular K-Means Performance Comparison
Color Quantization using K-Means
Color Quantization using K-Means
Comparison of the K-Means and MiniBatchKMeans clustering algorithms
Comparison of the K-Means and MiniBatchKMeans clustering algorithms
Demonstration of k-means assumptions
Demonstration of k-means assumptions
Empirical evaluation of the impact of k-means initialization
Empirical evaluation of the impact of k-means initialization
K-means Clustering
K-means Clustering
Selecting the number of clusters with silhouette analysis on KMeans clustering
Selecting the number of clusters with silhouette analysis on KMeans clustering
Clustering text documents using k-means
Clustering text documents using k-means