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 . 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.
| Aspect | Supervised classification | Unsupervised clustering |
|---|---|---|
| Training targets | Known class labels | No required class labels |
| Main goal | Predict a specified category | Discover structure or groupings |
| Output | Predicted labels for defined classes | Cluster memberships or structures |
| Evaluation | Compare with ground truth | Internal measures, stability, and domain interpretation; external labels if available |
| Typical example | Predict whether an email is spam | Group 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 observations and numerical features is often represented as a matrix:
Each row is an observation , 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:
For instance, the distance between and is:
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 numerical observations into nonempty clusters while seeking to minimize the sum of squared Euclidean distances from each observation to its assigned cluster centroid.
The number 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 , its centroid is:
K-Means minimizes the within-cluster sum of squares, also called inertia in scikit-learn:
A smaller 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 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.
- Choose . Decide how many clusters to fit.
- Initialize centroids. Select starting cluster centers, often with the K-Means++ initialization strategy.
- Assignment step. Assign each observation to its nearest centroid according to squared Euclidean distance.
- Update step. Replace each centroid with the mean of its assigned observations.
- 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.
A small numerical example
Suppose the four one-dimensional observations are , and we choose . Initialize centroids at and .
- The observations and are closer to the first centroid.
- The observations and are closer to the second centroid.
- The new centroids are and .
Their new assignments remain the same. The final inertia is:
The result is two clusters with centroids and . 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 . There is no universal formula that identifies the correct number of real-world groups.
Elbow method
Fit several values of , 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:
where is average within-cluster distance and is the smallest average distance to another cluster. Scores near indicate stronger separation, scores around 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 , 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 , 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
| Strength | Limitation or caution |
|---|---|
| Straightforward and widely implemented | Requires specifying |
| Efficient for many numerical datasets | Can converge to a local optimum |
| Produces interpretable centroids in the chosen features | Assumes squared Euclidean distance is useful |
| Works well for reasonably compact, separated groups | Can struggle with elongated, nested, or uneven-density clusters |
| Supports assigning new points to fitted clusters | Sensitive 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.
| Method | Main idea | Useful situation |
|---|---|---|
| Agglomerative hierarchical clustering | Repeatedly merges similar groups into a hierarchy | Exploring nested group relationships |
| DBSCAN | Forms clusters from density-connected observations | Irregularly shaped dense clusters and noise detection |
| HDBSCAN | Explores clusters of varying density using hierarchical density structure | Data with uneven cluster densities |
| Gaussian mixture models | Fits a probabilistic mixture of Gaussian components | Soft component membership under distributional assumptions |
| K-Medoids | Uses representative observed points as centers | When 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 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
- Why is K-Means called unsupervised learning?
- What does a centroid represent, and can it lie outside the observed dataset?
- Why is scaling important when clustering height and annual income together?
- Why can K-Means converge without reaching the global minimum of inertia?
- Why does the smallest possible inertia not identify the best value of ?
- What is the difference between K-Means cluster IDs and class labels learned by a supervised classifier?
- When might DBSCAN be preferable to K-Means?
Show suggested answers
- It does not require predefined target labels for its input observations.
- A centroid is the component-wise mean of a cluster and need not coincide with any training observation.
- Different measurement scales can distort Euclidean distances, causing one feature to dominate.
- Alternating assignment and update steps can settle into different local minima depending on initialization.
- Adding more centroids tends to reduce inertia, so complexity and interpretability must also be considered.
- Cluster IDs name discovered groups; supervised labels refer to defined target classes supplied during training.
- DBSCAN can be preferable for irregular cluster shapes, explicit noise points, or structures that are poorly described by centroid-based partitions.
14. Related concepts
- Machine Learning Paradigms — how unsupervised learning differs from other paradigms.
- Classification, Regression, Clustering, and Other AI Tasks — identifying which problem is being solved.
- Vectors and Matrices — feature vectors and data matrices.
- Vector and Matrix Operations — distances, norms, and the geometry behind clustering.
- Feature Engineering, Encoding, and Scaling — building appropriate feature representations.
- Data Cleaning and Preprocessing — handling missing values, outliers, and invalid records.
- Dimensionality Reduction and PCA — studying lower-dimensional structure and visualization.
- Evaluating Machine Learning Models — thinking carefully about evaluation and validation.
References and further reading
- scikit-learn User Guide: Clustering — K-Means, clustering metrics, and alternative algorithms.
- scikit-learn API: KMeans — parameters, initialization, inertia, and predictions.
- scikit-learn API: silhouette_score — silhouette definition and usage conditions.
- An Introduction to Statistical Learning — broader foundations of unsupervised learning.
Related articles in
- Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
- Decision Trees, Random Forests, and Boosting — Learn how decision trees partition data, how random forests reduce variance through bagging, and how boosting combines sequential learners to improve predictions.
- Dimensionality Reduction and Principal Component Analysis — Understand why high-dimensional data is difficult to analyze, how PCA finds directions of maximum variance, and how to use and evaluate PCA without data leakage.