Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Scikit-Learn · Class

KMeans

KMeans partitions data into a chosen number of clusters by iteratively assigning samples to centroids and updating those centroids. It supports k-means++ or custom initialization and Lloyd or Elkan optimization.

How it works

KMeans partitions samples into a requested number of groups by iteratively assigning points to centroids and updating those centroids. It supports Lloyd’s classical method and Elkan’s triangle-inequality variant, and exposes labels, centers, inertia, and iteration information after fitting.

Syntax

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')

Parameters

NameTypeDescription
n_clustersintNumber of clusters to form and centroids to generate; default 8.
init{'k-means++', 'random'}, callable or array-likeCentroid initialization method: 'k-means++', 'random', a callable, or an array-like of shape (n_clusters, n_features); default 'k-means++'.
n_init'auto' or intNumber of times the algorithm is run with different centroid seeds; default 'auto'.
max_iterintMaximum iterations for one run; default 300.
tolfloatRelative tolerance used to declare convergence; default 1e-4.
verboseintVerbosity mode; default 0.
random_stateint, RandomState instance or NoneControls random centroid initialization; default None.
copy_xboolWhether to copy X before fitting; default True.
algorithm{'lloyd', 'elkan'}K-means algorithm: 'lloyd' or 'elkan'; default 'lloyd'.

Returns

A fitted KMeans estimator; fitting provides cluster_centers_, labels_, inertia_, n_iter_, and n_features_in_.

Key points

  • KMeans is an unsupervised estimator for partitioning observations into clusters.
  • n_clusters sets both the requested cluster count and the number of centroids.
  • init selects how initial centroid positions are obtained; supported choices include k-means++, random, a callable, or an array.
  • max_iter caps the iterations performed during one run.
  • tol determines convergence from the relative change between centers on successive iterations.
  • random_state controls randomness used while initializing centroids.
  • algorithm selects between Lloyd’s and Elkan’s implementations.

Common mistakes

  • Elkan can improve efficiency for well-separated clusters, but its extra distance-related array increases memory use.
  • Choose Lloyd when the additional memory required by Elkan is undesirable.
  • Runtime depends on the cluster count, sample count, and number of iterations, so large datasets or many clusters can be costly.

Example: Cluster points with KMeans

from sklearn.cluster import KMeans

X = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]
model = KMeans(n_clusters=2, random_state=0, n_init="auto")
labels = model.fit_predict(X)
print(labels)
print(model.cluster_centers_)

Fits two clusters to six two-dimensional samples, then prints each sample's cluster index and the learned centroids.

When to use it

Unsupervised segmentation

Group observations without labeled targets.

Vector quantization

Replace each sample with its nearest learned centroid.

Cluster exploration

Explore compact groups in numeric feature space.

Interview questions

QHow does KMeans form clusters?

KMeans creates the requested number of centroids, assigns each sample to a centroid, and updates centroids repeatedly. It stops when convergence criteria are met or the iteration limit is reached.

Follow-up: When can Elkan be preferable? It can be faster when clusters are well defined because it uses the triangle inequality, provided the extra memory is acceptable.

QWhat does n_clusters control?

n_clusters controls both the number of groups and the number of centroids generated. The default is 8, so it should be set to a value appropriate for the problem.

Follow-up: What is a consequence of choosing too many clusters? The model creates more centroids and can increase computation while producing a less useful partition.

QHow do initialization and random_state affect fitting?

The default initialization is k-means++, which selects initial centroids using an empirical probability distribution related to points’ contribution to inertia. The random_state parameter controls centroid-initialization randomness.

Follow-up: How can reproducibility be improved? Supply a fixed random_state and keep the initialization and other configuration unchanged.

  • sklearn.cluster.MiniBatchKMeans
  • sklearn.cluster.BisectingKMeans
  • sklearn.cluster.DBSCAN
  • sklearn.cluster.AgglomerativeClustering

Source: KMeans. Checked 2026-10-15.