Sub topic 1
What clustering is and where k-means fits
Prerequisites
This chapter assumes you know the following:
- Basic Python and NumPy array operations, such as indexing, slicing, and
axisarguments. - The mean and the Euclidean distance between two vectors.
- A feature matrix, where rows are samples and columns are features.
- The basic idea of supervised versus unsupervised learning.
You do not need to know scikit-learn yet. Later chapters introduce it.
By the end of this chapter you should be able to explain what clustering is, say how it differs from classification, and describe where k-means sits among clustering methods. The remaining chapters build the algorithm piece by piece.
What clustering is
Clustering is the task of splitting a set of samples into groups so that samples in the same group are more similar to each other than to samples in other groups. The groups are called clusters. No one tells the algorithm what the groups are. It finds them from the structure of the data.
Clustering is a form of unsupervised learning. In unsupervised learning, the training data has features but no target column. There is no y to predict. The input is only a feature matrix X with shape (n_samples, n_features).
A clustering algorithm returns one label per row. Those labels are integers such as 0, 1, 2. They are arbitrary names. Cluster 2 in one run is not "the same" cluster as cluster 2 in another run, and the number carries no order or meaning.
Typical uses include:
- Customer segmentation: grouping customers by purchase behavior so each group can be studied or targeted separately.
- Image compression: replacing every pixel color with the color of its cluster center, which reduces the palette to a few colors.
- Exploratory analysis: checking whether a dataset has obvious groups before building anything else.
- Preprocessing: using cluster membership or distance to cluster centers as new features for a supervised model.
- Anomaly screening: flagging points that sit far from every cluster center.
Clustering versus classification
Classification is supervised. You give the model examples with known labels, it learns a rule, and it predicts labels for new samples. Clustering has no known labels to learn from.
| Aspect | Classification | Clustering |
|---|---|---|
| Learning type | Supervised | Unsupervised |
| Training input | `X` and labels `y` | `X` only |
| Goal | Predict a known label | Discover groups |
| Number of classes | Fixed by the labels | Often chosen by you |
| Evaluation | Compare predictions with true labels | No ground truth, so use internal measures or judgment |
| Label meaning | Labels have fixed meaning | Cluster ids are arbitrary |
The last two rows matter most in practice. In classification you can compute accuracy because the answer is known. In clustering there is usually no answer key. A clustering is "good" only relative to some criterion, such as compactness of the groups, or relative to how useful it is for your task. Two different algorithms can both produce valid clusterings of the same data that disagree with each other.
A common mistake is to treat cluster labels as ground truth. They are a summary of the data under a particular algorithm, a particular distance, and a particular choice of settings.
What counts as "similar"
Every clustering method needs a definition of similarity. Most use a distance between feature vectors, and smaller distance means more similar. K-means uses squared Euclidean distance. For two vectors a and b with d features, the Euclidean distance is the square root of the sum of squared differences across features.
This has a direct consequence. The clusters you get depend on which features you include and on their units. A feature measured in thousands will dominate a feature measured in fractions. A later chapter covers scaling in detail. For now, remember that the notion of similarity is part of your modeling choice, not something the algorithm discovers for you.
Where k-means fits
Clustering methods fall into several families. They differ in what they assume a cluster looks like.
| Family | Idea | Example algorithms | Needs number of clusters up front |
|---|---|---|---|
| Centroid-based | Each cluster is represented by a center point | k-means, k-medoids | Yes |
| Hierarchical | Build a tree of nested clusters by merging or splitting | Agglomerative clustering | No, you cut the tree afterward |
| Density-based | Clusters are dense regions separated by sparse regions | DBSCAN, HDBSCAN | No |
| Distribution-based | Data comes from a mixture of probability distributions | Gaussian mixture models | Yes |
K-means is the standard centroid-based method. The letter k is the number of clusters, and you must supply it before running the algorithm. Each cluster is represented by its centroid, which is the mean of the points assigned to it. Every point belongs to exactly one cluster: the one with the nearest centroid. This is called a hard assignment, as opposed to the soft assignment of a Gaussian mixture, where each point has a probability of belonging to each cluster.
K-means is popular for practical reasons:
- It is simple to explain and to implement in a few lines of NumPy.
- Each iteration costs time proportional to
n_samples * k * n_features, so it scales to large datasets. - It produces centroids that are easy to interpret, because each centroid is a point in the original feature space.
- It gives a new point a cluster by a single nearest-centroid lookup.
It also comes with assumptions that this tutorial examines later. Because it uses means and squared distances, it favors clusters that are compact, roughly round, and of similar size. It is also sensitive to scale and to outliers, and it can finish in different answers depending on where it starts.
The idea in one picture
The algorithm alternates between two simple moves. Given a set of centroids, assign each point to the nearest one. Given an assignment, move each centroid to the mean of its points. Repeating these moves until nothing changes is the whole method.
The following chapters expand each box of this diagram: what distance and centroid mean, what quantity the loop minimizes, why it stops, how to choose the starting centroids, and how to pick k.
A first look at the output
You can see what clustering produces before learning how it works. The code below creates three groups of 2D points and runs the algorithm from a small hand-written function. It uses the NumPy implementation that a later chapter explains line by line.
import numpy as np
from sklearn.datasets import make_blobs
def kmeans(X, k, n_iter=100, seed=0):
rng = np.random.default_rng(seed)
centroids = X[rng.choice(len(X), size=k, replace=False)]
for _ in range(n_iter):
# Assignment step: index of the nearest centroid for each point
dists = np.linalg.norm(X[:, None, :] - centroids[None, :, :], axis=2)
labels = dists.argmin(axis=1)
# Update step: mean of each cluster (keep old centroid if a cluster is empty)
new_centroids = np.array([
X[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
for j in range(k)
])
if np.allclose(new_centroids, centroids):
break
centroids = new_centroids
inertia = ((X - centroids[labels]) ** 2).sum()
return labels, centroids, inertia
X, true_groups = make_blobs(n_samples=300, centers=3, cluster_std=1.0, random_state=42)
labels, centroids, inertia = kmeans(X, k=3)
print("X shape: ", X.shape)
print("labels shape: ", labels.shape)
print("centroids shape:", centroids.shape)
print("cluster sizes: ", np.bincount(labels))Read the output this way:
Xhas shape(300, 2): 300 samples and 2 features.labelshas shape(300,): one integer per sample, between 0 and 2.centroidshas shape(3, 2): one center per cluster, in the same feature space asX.np.bincount(labels)counts how many points landed in each cluster.
The exact sizes depend on the data and the seed. The true_groups array holds the labels that make_blobs used when generating the points. A real clustering problem has no such array. Here it exists only so you can check the result against a known answer.
Common errors at this stage
These mistakes come from misunderstanding what clustering is, before any code runs.
- Treating clusters as real categories. K-means always returns
kclusters, even on data with no group structure. Uniform random noise will be split intokneat pieces. The output is a partition of the space, not proof that groups exist. - Comparing label numbers across runs. Different seeds or different data give different numbering. Compare the partition itself.
- Ignoring units. Putting income in dollars next to age in years makes income control the distance. The clusters will reflect income and almost nothing else.
- Feeding in categorical codes. If a column holds category ids such as 1, 2, 3, the mean of those ids has no meaning. K-means needs numeric features where averaging makes sense.
- Expecting to choose k automatically. The algorithm does not decide how many clusters exist. You supply
k, and later chapters cover ways to guide that choice. - Using it on a problem that is really classification. If you already have labels for the groups you care about, a supervised model is the better tool.
How this chapter connects to the rest
The tutorial follows the dependency order of the ideas:
- Distance and centroids define what "near" and "center" mean.
- The k-means objective, called inertia, is the number the algorithm tries to make small.
- Lloyd's algorithm is the assign-and-update loop that reduces inertia.
- Convergence explains why the loop stops, and why it stops at a local minimum rather than the best possible answer.
- Initialization, including k-means++, controls where the loop starts.
- Feature scaling fixes the unit problem described above.
- The scikit-learn
KMeansclass packages all of this for real use. - The elbow method and silhouette score help you choose
k. - The limitations chapter shows which data shapes break the method.
- The final chapter covers mini-batch k-means and alternative algorithms.
Keep one question in mind throughout. For any clustering result, ask what the algorithm assumed about the shape of a cluster, and whether your data matches that assumption.
Exercise
You have a table of 10,000 customers with columns for annual spend, number of orders, and days since last purchase. There is no column that says which segment each customer belongs to. Explain why this is a clustering problem and not a classification problem, and name two things you must decide before running k-means.
Show answer
Classification needs a labeled target to learn from, and this table has none. The goal is to discover segments, not to predict a known label, so it is unsupervised and fits clustering. Before running k-means you must decide the number of clusters k, because the algorithm does not choose it. You must also decide how to put the features on comparable scales, because annual spend, order count, and days since last purchase have very different units and the larger-valued feature would dominate the Euclidean distance. Choosing which features to include is also a valid answer.
Exercise
A colleague runs k-means with k=4 on a dataset of uniformly random points and says, "The algorithm found four customer groups, so four groups exist." What is wrong with this reasoning?
Show answer
K-means always returns exactly k clusters, whatever the data looks like. On uniformly random points it simply cuts the space into four regions around four centroids. The result shows that the algorithm ran, not that the data contains four natural groups. The colleague needs to check cluster quality and stability, for example with the silhouette score and by comparing runs with different seeds, and to confirm the clusters make sense for the application.
Exercise
Which of these is a hard assignment and which is a soft assignment: (a) k-means, (b) a Gaussian mixture model? Give the practical difference for a single point.
Show answer
(a) K-means uses hard assignment: each point belongs to exactly one cluster, the one with the nearest centroid. (b) A Gaussian mixture model uses soft assignment: each point gets a probability of belonging to each cluster. For a point lying between two clusters, k-means returns one label and hides the ambiguity, while a mixture model returns, for example, 0.55 for one cluster and 0.45 for the other.