← All posts

Machine learning algorithms › Unsupervised learning

What is k-means clustering? Grouping data without labels

What k-means clustering is, the four steps it repeats, how to choose k, why scaling matters, and where it falls short, with Python examples I ran myself.

If you spend some time with data analysis or machine learning, the name k-means tends to come up early. It shows up in marketing analysis that sorts customers into a few groups by how they shop, and in image processing that cuts down the number of colors in a photo. Lately you hear it in vector search, too. That’s because it’s used to group and compress the huge numbers of vectors that sentences and images get turned into, and the paper introducing the search library Faiss treats k-means as one of its basic tools.

k-means clustering splits data into a chosen number of groups, k, so that each point sits close to the center of its own group. The center is the mean of the points in that group, which is where the “means” in the name comes from. Grouping similar things like this is called clustering, and since it finds structure from the data alone, without answer labels, it belongs to unsupervised learning.

Four steps, repeated until the centers stop moving

What k-means does comes down to four steps.

  1. Pick k centers. The simplest way is to choose k points from the data at random.
  2. Assign every point to its nearest center.
  3. For each group, take the mean of its points and move the center there.
  4. Repeat steps 2 and 3 until the centers stop moving.

It may help to picture opening k shops in a neighborhood. Every household goes to its nearest shop, and each shop moves to the middle of its regulars’ homes. Repeat that a few times, and the shops gradually settle into place.

The value that shrinks along the way is the sum of the squared distances from each point to its center, which scikit-learn calls inertia (user guide). Moving a point to a closer center never increases it, and neither does moving a center to the mean, because the mean is the spot that makes the sum of squared distances within a group as small as possible. That’s why the algorithm always stops eventually. There’s no guarantee, though, that where it stops is the best answer.

A method that began at Bell Labs in 1957

These four steps are often called Lloyd’s algorithm, and scikit-learn’s KMeans uses this method by default (algorithm="lloyd"). At Bell Labs, Stuart P. Lloyd was working on pulse-code modulation (PCM), which sends a signal by replacing each value with one of a few representative values, and he used this loop to find the representatives that keep the noise smallest. His paper only appeared in IEEE Transactions on Information Theory in 1982. According to his note at the end, it’s a nearly verbatim copy of an internal draft logged at the lab on July 31, 1957.

According to the history of k-means that Hans-Hermann Bock put together in 2008, the name k-means was first used by MacQueen in a 1967 paper. He gave the name to a sequential method, though, one that takes one point at a time and updates only its nearest center. And several people, Steinhaus in 1956 among them, came up with similar methods on their own.

Writing k-means by hand in numpy

Writing it yourself shows how short the four steps really are. I used make_blobs to create 300 points in 2D drawn from four groups, threw away the group numbers, and ran it six times, changing only the random choice in step 1.

import numpy as np
from sklearn.datasets import make_blobs

# 300 points around 4 centers in 2D; the labels are dropped
X, _ = make_blobs(n_samples=300, centers=4, random_state=16)

def kmeans(X, k, seed):
    rng = np.random.default_rng(seed)
    centers = X[rng.choice(len(X), size=k, replace=False)]  # 1. pick k points as centers
    for n_iter in range(1, 101):
        dist = ((X[:, None, :] - centers[None, :, :]) ** 2).sum(axis=2)
        labels = dist.argmin(axis=1)  # 2. assign each point to its nearest center
        new = np.array([X[labels == j].mean(axis=0) for j in range(k)])  # 3. move to the mean
        if np.allclose(new, centers):  # 4. stop when no center moves
            break
        centers = new
    inertia = dist.min(axis=1).sum()  # sum of squared distances to the nearest center
    return centers, inertia, n_iter

for seed in range(6):
    _, inertia, n_iter = kmeans(X, k=4, seed=seed)
    print(f"seed {seed}: stopped after {n_iter} rounds, inertia {inertia:.1f}")
seed 0: stopped after 6 rounds, inertia 513.1
seed 1: stopped after 5 rounds, inertia 958.9
seed 2: stopped after 4 rounds, inertia 953.8
seed 3: stopped after 4 rounds, inertia 513.1
seed 4: stopped after 7 rounds, inertia 513.1
seed 5: stopped after 7 rounds, inertia 513.1

The data and the code were the same, yet four runs stopped at 513.1 while seeds 1 and 2 stopped in the 950s. When I printed the centers for seed 1, two centers had landed in the same group, while two other groups sitting close together were sharing a single center. From there, reassigning points and moving centers no longer lowers the inertia. A state like this, which isn’t the best answer but can’t be improved by small changes, is called a local minimum.

Choosing starting points with k-means++ and n_init

A well-known way to ease this problem is k-means++, which David Arthur and Sergei Vassilvitskii presented at the SODA conference in 2007. It picks the first center at random, then picks each next center with probability proportional to the squared distance to the nearest center chosen so far, so points far from the existing centers are more likely to be chosen. The paper proves that starting this way keeps the expected inertia within a factor proportional to log k of the best possible answer, and its experiments showed gains in both speed and accuracy.

In scikit-learn 1.9.1, KMeans uses greedy k-means++ by default, which draws several candidates at each step and keeps the best one. n_init sets how many times to run with different starting points before keeping the result with the lowest inertia. Its default, 'auto', means one run when starting with k-means++ and ten when starting at random (KMeans docs). Up to version 1.3 the default was 10, so older material may describe it differently.

Choosing k with the elbow method and silhouette scores

You have to choose k yourself, and two methods come up often. The elbow method raises k step by step and looks for the point where the drop in inertia suddenly gets small. You can’t simply pick the lowest inertia, since it generally keeps falling as k grows. The silhouette score gives each point a score between -1 and 1 by comparing its average distance to the points in its own cluster with its average distance to the points in the nearest other cluster, then averages those scores. Closer to 1 means well separated, near 0 means the clusters overlap, and it isn’t defined for k=1 (silhouette_score docs).

from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

for k in range(1, 8):
    km = KMeans(n_clusters=k, random_state=0).fit(X)
    sil = f"{silhouette_score(X, km.labels_):.3f}" if k > 1 else "-"
    print(f"k={k}  inertia {km.inertia_:7.1f}  silhouette {sil}")
k=1  inertia  8127.4  silhouette -
k=2  inertia  2578.4  silhouette 0.575
k=3  inertia  1003.9  silhouette 0.627
k=4  inertia   513.1  silhouette 0.633
k=5  inertia   454.5  silhouette 0.547
k=6  inertia   423.8  silhouette 0.545
k=7  inertia   383.6  silhouette 0.475

At k=4, scikit-learn reached 513.1 in a single run, the same as the good answer from my code, and the centers matched to two decimal places. The inertia nearly halves from k=3 to k=4 but drops only 58.6 from 4 to 5, so the elbow method points to 4. The silhouette scores for k=3 and k=4, though, are almost the same at 0.627 and 0.633. That’s because two of the four groups sit close together, so the boundary between them isn’t sharp. scikit-learn’s k-means assumptions example also says that real data has no uniquely defined true number of clusters, and that you should decide using data-based criteria along with what you’re trying to do.

Why the units of your features change the result

Because k-means works with distances, features measured in different units change the result. If you group customers by age and yearly spending, a 20-year age gap counts the same as a 20-dollar difference in spending. The example below makes two groups that differ only in age (around 30 and 50, 150 people each) and gives both the same spread of spending. It then compares the result before and after standardization, which subtracts each feature’s mean and divides by its standard deviation. The score, the adjusted Rand index (ARI), is 1 when the clusters match the real groups and close to 0 when they’re no better than a random split (adjusted_rand_score docs).

from sklearn.metrics import adjusted_rand_score
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(2)
# The two groups differ only in age
age = np.concatenate([rng.normal(30, 4, 150), rng.normal(50, 4, 150)])
spend = rng.normal(2000, 500, 300)
group = np.repeat([0, 1], 150)
customers = np.column_stack([age, spend])

for name, data in [("raw", customers), ("scaled", StandardScaler().fit_transform(customers))]:
    labels = KMeans(n_clusters=2, random_state=0).fit_predict(data)
    print(f"{name:<6} ARI {adjusted_rand_score(group, labels):.2f}")
raw    ARI 0.00
scaled ARI 0.97

Left as it was, the two centers had almost the same ages, 39 and 41, and differed only in spending, at $2,392 and $1,602, so the split followed spending alone. After standardization, it found the real groups almost exactly. Of course, how much weight each feature deserves is up to the person doing the grouping, so standardizing isn’t always the right answer.

When it fits and when it doesn’t

k-means fits well when the features are numbers and the groups are roughly round and of similar size. The computation is simple, so it tends to be fast even on a lot of data, and since each center is the mean of its group, the result is easy to read. That’s also why it’s often used for customer segmentation. To reduce the colors in a photo, you treat each pixel’s red, green, and blue values as a point, group the points into k clusters, and paint each pixel with its center’s color. Replacing many values with k representatives like this is called vector quantization, and scikit-learn’s vector quantization example reduces a photo’s 256 gray levels to 8. Lloyd’s PCM problem is the one-dimensional version of the same idea.

On the other hand, because every point is attached to its nearest center, the boundary between two groups is always straight. scikit-learn’s documentation also notes that inertia assumes convex clusters that spread evenly in every direction, so it handles elongated or irregular shapes poorly. Let’s check with two interlocking crescents of 150 points each.

from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons

Xm, ym = make_moons(n_samples=300, noise=0.05, random_state=0)
models = {"k-means": KMeans(n_clusters=2, random_state=0), "DBSCAN": DBSCAN(eps=0.3)}
for name, model in models.items():
    print(f"{name:<7} ARI {adjusted_rand_score(ym, model.fit_predict(Xm)):.2f}")
k-means ARI 0.23
DBSCAN  ARI 1.00

k-means cut the plane in two with a straight line and couldn’t follow the crescents. DBSCAN grows clusters by connecting areas where points are densely packed. So without being told k, it took a neighborhood distance (eps) and found both crescents exactly, and because it marks points away from dense areas as noise, outliers throw it off less. If each group has its own shape, a Gaussian mixture model is another option. It learns how stretched each group is and in which direction, and scikit-learn’s documentation treats k-means as a special case of this model in which every group has the same shape.

Beyond that, k-means can’t use categorical features as they are, since you can’t take their mean, and a few far-off points can pull a center toward them. With a great many features, distances tend to get inflated, so scikit-learn’s documentation suggests reducing the dimensions with PCA first.

If you’re trying it for the first time

If you’re new to this, I’d suggest putting the code above into one file, running it, and then changing random_state or cluster_std in make_blobs to watch how the elbow and the silhouette scores move. For your own data, scikit-learn’s comparison of clustering methods is a good place to look for the method that fits. I ran these examples on November 2, 2026, with Python 3.13.12, NumPy 2.5.4, and scikit-learn 1.9.1.

AI tools helped with the research for this post.