Machine Learning • Machine Learning Algorithms • 14 min read

Clustering and K-Means

Find structure without answer labels

Suppose a bookstore has purchase records but no predefined customer categories. A human might notice that some customers mostly buy textbooks while others prefer fiction. Can a program reveal similar patterns without being told the correct group for each person?

This is the intuition behind clustering. Instead of predicting known labels, a clustering method groups observations according to a chosen notion of similarity. The groups are exploratory descriptions of the data, not automatically meaningful real-world identities.

K-Means starts with a requested number of groups, written as kk. It alternates between assigning each example to its nearest cluster center and updating centers to the average of assigned examples. Repeating these two steps generally reduces the within-cluster sum of squared distances until the procedure stabilizes at a local solution.

For example, with two-dimensional points, you can imagine moving two markers toward the centers of two clouds. But what if the clouds overlap or curve around each other? K-Means may give an unsatisfying split because it favors roughly compact, distance-based clusters.

The essential question is not only, “Did the algorithm form groups?” It is also, “Are those groups stable, interpretable, and useful for the original problem?”

Clustering is an unsupervised machine-learning task that organizes observations into groups based on their similarities. K-Means is a widely used clustering algorithm that partitions numerical observations into a specified number of groups by repeatedly assigning observations to nearby cluster centers and updating those centers.

Clustering can reveal structure in a dataset without requiring labeled target values. However, the resulting groups are mathematical patterns, not automatically meaningful real-world categories. Understanding that distinction is essential when using clustering in AI systems.

1. What is clustering?

Definition: Clustering is the process of grouping observations so that observations within a group are relatively similar under a chosen representation and similarity measure.

Consider an online learning platform with records of how learners interact with lessons. Each learner might be represented by features such as weekly study minutes, number of lessons completed, and frequency of returning to the platform. A clustering algorithm might identify groups of learners with similar activity patterns.

Unlike supervised classification, clustering does not train from predefined labels such as regular learner or occasional learner. The algorithm receives the feature values and discovers partitions or other structures according to its assumptions.

AspectSupervised classificationUnsupervised clustering
Training targetsKnown class labelsNo required class labels
Main goalPredict a specified categoryDiscover structure or groupings
OutputPredicted labels for defined classesCluster memberships or structures
EvaluationCompare with ground truthInternal measures, stability, and domain interpretation; external labels if available
Typical examplePredict whether an email is spamGroup emails by similar content patterns

A cluster identifier such as 0 or 1 is an arbitrary label assigned by the algorithm. It does not have a fixed semantic meaning, and its numerical value does not imply ranking.

2. How similarity is represented

A dataset with nn observations and dd numerical features is often represented as a matrix:

X∈Rn×d.X \in \mathbb{R}^{n\times d}.

Each row is an observation xi\mathbf{x}_i, and each column represents a feature. To decide which observations are close, a clustering algorithm uses a distance or similarity measure.

Euclidean distance measures straight-line distance between two feature vectors:

d(x,y)=∑j=1d(xj−yj)2.d(\mathbf{x},\mathbf{y}) = \sqrt{\sum_{j=1}^{d}(x_j-y_j)^2}.

For instance, the distance between (1,2)(1,2) and (4,6)(4,6) is:

(4−1)2+(6−2)2=25=5.\sqrt{(4-1)^2+(6-2)^2}=\sqrt{25}=5.

This looks straightforward, but a distance measure is only as meaningful as its input representation. A feature measured in thousands can dominate a feature measured between zero and one. Irrelevant features, missing values, encoded categories, and unusually high-dimensional representations can also distort perceived closeness.

For K-Means, numerical Euclidean geometry is central to the algorithm. Standardizing suitable features is often useful, but not always appropriate: the correct scaling reflects what differences should matter for the actual task.

3. What is K-Means?

Definition: K-Means is a partition-based clustering algorithm that divides nn numerical observations into kk nonempty clusters while seeking to minimize the sum of squared Euclidean distances from each observation to its assigned cluster centroid.

The number kk must be selected before fitting the ordinary K-Means model. A centroid is the arithmetic mean of the observations assigned to a cluster, not necessarily an observed data point.

For cluster CjC_j, its centroid is:

μj=1∣Cj∣∑xi∈Cjxi.\boldsymbol{\mu}_j = \frac{1}{|C_j|}\sum_{\mathbf{x}_i\in C_j}\mathbf{x}_i.

K-Means minimizes the within-cluster sum of squares, also called inertia in scikit-learn:

J=∑j=1k∑xi∈Cj∥xi−μj∥22.J=\sum_{j=1}^{k}\sum_{\mathbf{x}_i\in C_j} \left\|\mathbf{x}_i-\boldsymbol{\mu}_j\right\|_2^2.

A smaller JJ means the observations are closer to their assigned centroids for that particular clustering. It does not prove that the clustering is useful, and the objective generally decreases as kk increases. Consequently, inertia alone cannot determine the ideal number of clusters.

4. The K-Means algorithm, step by step

Standard K-Means alternates between two operations: assigning observations to the nearest centroid and recomputing centroids from the assigned observations.

  1. Choose kk. Decide how many clusters to fit.
  2. Initialize centroids. Select starting cluster centers, often with the K-Means++ initialization strategy.
  3. Assignment step. Assign each observation to its nearest centroid according to squared Euclidean distance.
  4. Update step. Replace each centroid with the mean of its assigned observations.
  5. Repeat. Alternate assignment and update until assignments or centroid movement stabilize sufficiently, or a stopping limit is reached.

For a fixed assignment, the mean minimizes the sum of squared Euclidean distances within that cluster. For fixed centroids, assigning each point to its nearest center also minimizes the objective. Thus each ordinary iteration cannot increase the objective, but the algorithm may settle at a local optimum, not the global best clustering.

K-Means workflow from initial cluster centroids to assignment, centroid updates, and final groups
Conceptual K-Means iteration. Crosses indicate centroids. The process repeats beyond these three illustrative panels until a stopping criterion is met.

A small numerical example

Suppose the four one-dimensional observations are 1,2,8,91,2,8,9, and we choose k=2k=2. Initialize centroids at 11 and 88.

  • The observations 11 and 22 are closer to the first centroid.
  • The observations 88 and 99 are closer to the second centroid.
  • The new centroids are (1+2)/2=1.5(1+2)/2=1.5 and (8+9)/2=8.5(8+9)/2=8.5.

Their new assignments remain the same. The final inertia is:

(1−1.5)2+(2−1.5)2+(8−8.5)2+(9−8.5)2=1.(1-1.5)^2+(2-1.5)^2+(8-8.5)^2+(9-8.5)^2=1.

The result is two clusters with centroids 1.51.5 and 8.58.5. Different initializations can lead to different outcomes on more complicated data.

5. Initialization and why K-Means++ matters

Randomly chosen initial centroids can produce poor solutions or inconsistent results. K-Means++ chooses starting centers using a distance-aware strategy that spreads initial centers across the data, improving the chances of a useful result.

Even with K-Means++, one run may be insufficient. Multiple initializations can produce different local optima; fitting several runs and retaining the solution with the lowest inertia is a common practical strategy.

In scikit-learn, n_init controls how many initializations are tried. The exact default and behavior can vary with library version and initialization choice, so set it explicitly when reproducibility matters. A fixed random_state also makes randomized initialization repeatable for the same software environment and input.

6. Choosing the number of clusters

Ordinary K-Means requires a value of kk. There is no universal formula that identifies the correct number of real-world groups.

Elbow method

Fit several values of kk, plot their inertia, and look for a point where adding another cluster produces sharply diminishing improvement. This is an informal heuristic, not a statistical proof. Some datasets have no clear elbow.

Silhouette score

For each observation, the silhouette coefficient compares its average distance to points in its own cluster with its average distance to points in the nearest other cluster:

s(i)=b(i)−a(i)max⁡(a(i),b(i)),s(i)=\frac{b(i)-a(i)}{\max(a(i),b(i))},

where a(i)a(i) is average within-cluster distance and b(i)b(i) is the smallest average distance to another cluster. Scores near 11 indicate stronger separation, scores around 00 indicate overlap, and negative scores may suggest poor assignments.

Silhouette scores are defined for at least two distinct clusters and fewer clusters than samples. They can favor compact, separated groups and do not automatically measure business value or scientific validity.

Stability and domain validity

Recheck the groups across sensible samples, initializations, and reasonable feature transformations. Then ask whether the clusters are interpretable and useful in the actual domain. A high score cannot rescue clusters built from misleading features.

7. Implement K-Means with scikit-learn

This example generates synthetic two-dimensional observations, scales them, fits K-Means for a few candidate values of kk, and compares inertia and silhouette score. The data are intentionally simple so the focus remains on the workflow.

import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler

X, _ = make_blobs(
    n_samples=300,
    centers=[(-4, -3), (0, 4), (5, -1)],
    cluster_std=0.8,
    random_state=42,
)

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

for k in range(2, 6):
    model = KMeans(n_clusters=k, n_init=10, random_state=42)
    labels = model.fit_predict(X_scaled)
    score = silhouette_score(X_scaled, labels)
    print(f"k={k}, inertia={model.inertia_:.2f}, silhouette={score:.3f}")

final_model = KMeans(n_clusters=3, n_init=10, random_state=42)
cluster_ids = final_model.fit_predict(X_scaled)

# Convert centroids back into the original feature units.
centroids_original = scaler.inverse_transform(final_model.cluster_centers_)

print("Cluster sizes:", np.bincount(cluster_ids))
print("Centroids in original units:\n", centroids_original)

How to interpret the results: cluster_ids assigns one arbitrary cluster number to each observation. cluster_centers_ contains the fitted centroids in scaled feature space. Reversing the scaling makes centroid coordinates easier to interpret in their original units. The candidate scores can inform a choice of kk, but they do not certify a meaningful grouping.

This is an exploratory example. In an actual clustering application, fit transformations on the designated development data and apply the fitted transformations to future observations. Evaluate stability and downstream usefulness on appropriate separate data when making generalization claims.

Assigning a new observation

To classify a new observation by proximity to already fitted centroids, transform it with the same fitted scaler before calling predict:

new_observation = np.array([[0.2, 3.7]])
new_scaled = scaler.transform(new_observation)
assigned_cluster = final_model.predict(new_scaled)
print("Assigned cluster ID:", int(assigned_cluster[0]))

This returns an assignment under the learned partition, not a prediction of a verified class or a calibrated probability.

8. Interpreting clusters responsibly

After fitting, compare each cluster’s feature distributions, size, and stability. A centroid can help describe an average profile, but averages may conceal variation within a group. For skewed features, distributions or robust summaries may be more informative.

For the learner-activity example, an analyst might observe a group with short sessions and infrequent visits. Calling this group unmotivated learners would be an unsupported psychological judgment. A defensible label would describe measured behavior, such as low recent activity, with clear definitions and limitations.

Avoid treating cluster identities as permanent: rerunning K-Means after new data arrives can alter cluster boundaries and numeric identifiers. Any application depending on a particular group should use documented matching and monitoring rather than assume that cluster 1 means the same thing forever.

9. Strengths and limitations

StrengthLimitation or caution
Straightforward and widely implementedRequires specifying kk
Efficient for many numerical datasetsCan converge to a local optimum
Produces interpretable centroids in the chosen featuresAssumes squared Euclidean distance is useful
Works well for reasonably compact, separated groupsCan struggle with elongated, nested, or uneven-density clusters
Supports assigning new points to fitted clustersSensitive to outliers and irrelevant or unscaled features

Why cluster shape matters

K-Means tends to describe groups as regions around centroids. If data form two interlocking crescents, for example, nearby-centroid partitions may cut across the curved groups instead of discovering each crescent as a unit.

Likewise, one large diffuse group and one very small dense group may not be represented well by a simple equal-importance centroid objective. K-Means does not automatically discover arbitrary shapes, hierarchical relationships, or variable-density structures.

Outliers and empty clusters

A distant observation contributes a large squared-distance penalty and may shift a centroid away from most points. Empty clusters can also arise during iteration; practical implementations must handle them. Inspect outliers, use appropriate features, and consider alternative algorithms when the data violate K-Means assumptions.

10. Other clustering approaches

K-Means is only one family of clustering methods. Different structures call for different tools.

MethodMain ideaUseful situation
Agglomerative hierarchical clusteringRepeatedly merges similar groups into a hierarchyExploring nested group relationships
DBSCANForms clusters from density-connected observationsIrregularly shaped dense clusters and noise detection
HDBSCANExplores clusters of varying density using hierarchical density structureData with uneven cluster densities
Gaussian mixture modelsFits a probabilistic mixture of Gaussian componentsSoft component membership under distributional assumptions
K-MedoidsUses representative observed points as centersWhen medoids or alternative dissimilarities are useful

A Gaussian mixture can assign probabilities of membership under its fitted model, while standard K-Means assigns each observation to one cluster. Neither makes clusters automatically meaningful or causally explanatory.

11. Applications in AI and data science

Exploratory data analysis: Identify recurring numerical profiles before choosing a predictive task.

Customer or user segmentation: Group measured behavior to inform research or experiments, while avoiding unsupported assumptions about motivations or personal traits.

Image compression: Represent similar pixel colors with a small palette of cluster centroids, accepting reconstruction error.

Document or embedding exploration: Group vector representations to inspect themes. The embedding model and distance metric strongly influence the resulting clusters.

Anomaly screening: Examine observations unusually far from cluster centers, with care: distance from a centroid is not in itself proof of an anomaly.

Representation learning workflows: Use clusters as exploratory or auxiliary signals, while checking that the induced groups are reliable enough for any downstream purpose.

12. Common mistakes to avoid

  • Assuming clusters are ground-truth categories. They are outputs of a chosen model and representation.
  • Choosing kk solely by minimum inertia. Inertia generally decreases as clusters are added.
  • Skipping feature scaling without checking units. Large-scale features may dominate squared distance.
  • Applying K-Means directly to arbitrary category codes. Numeric codes can create artificial distances between categories.
  • Interpreting cluster IDs as ordered labels. Their values are arbitrary.
  • Believing all data have natural clusters. Algorithms can form partitions even when there are no clearly separated groups.
  • Ignoring instability. Different seeds, samples, and preprocessing choices can change the result.
  • Calling every distant observation fraudulent or anomalous. Distance is a signal to investigate, not a definitive conclusion.

13. Check your understanding

  1. Why is K-Means called unsupervised learning?
  2. What does a centroid represent, and can it lie outside the observed dataset?
  3. Why is scaling important when clustering height and annual income together?
  4. Why can K-Means converge without reaching the global minimum of inertia?
  5. Why does the smallest possible inertia not identify the best value of kk?
  6. What is the difference between K-Means cluster IDs and class labels learned by a supervised classifier?
  7. When might DBSCAN be preferable to K-Means?
Show suggested answers
  1. It does not require predefined target labels for its input observations.
  2. A centroid is the component-wise mean of a cluster and need not coincide with any training observation.
  3. Different measurement scales can distort Euclidean distances, causing one feature to dominate.
  4. Alternating assignment and update steps can settle into different local minima depending on initialization.
  5. Adding more centroids tends to reduce inertia, so complexity and interpretability must also be considered.
  6. Cluster IDs name discovered groups; supervised labels refer to defined target classes supplied during training.
  7. DBSCAN can be preferable for irregular cluster shapes, explicit noise points, or structures that are poorly described by centroid-based partitions.

References and further reading

Related articles in

Image preview

Fit