Finding Groups Without Answers
Every model so far learned from labels: the species, the grower, whether an order was late. Often there are no labels. A shop has purchase records but no list of customer types; a researcher has measurements but no categories. You can still ask whether the samples fall into natural groups. That is clustering, a form of unsupervised learning: the algorithm groups similar samples using the features alone.
Clustering is a way to explore data, not to discover hidden truth. The algorithm always produces groups, even in data that has none, and the groups it finds depend on choices you make. Interpreting them is your job.
k-Means
k-means is the most widely used clustering method. You choose the number of clusters, k. Each cluster is described by its centre, the average position of its points. The algorithm:
- chooses k starting centres; scikit-learn uses a method called
k-means++, which spreads them out; - assigns every point to its nearest centre;
- moves each centre to the average of the points assigned to it;
- repeats steps 2 and 3 until the centres stop moving significantly.

Follow the loop in the diagram. After the start, the two middle steps feed
each other: new assignments move the centres, and moved centres change the
assignments. When a round no longer moves the centres significantly, the
loop exits with the final clusters. Because the starting centres involve
random choices, random_state is set to make the result repeatable.
Inertia and Choosing k
k-means aims to make clusters tight. It measures tightness with inertia: the sum, over all points, of the squared distance to their cluster's centre. Smaller inertia means points sit closer to their centres.
Inertia cannot choose k for you: it falls as k grows, as a rule, because more centres means every point can be closer to one. With one cluster per point, inertia would be zero. The useful signal is a sharp drop followed by small ones, often called an elbow: adding clusters beyond that point buys little.
Inertia also assumes that clusters are roughly round and similar in spread. For long, curved or very unequal groups, k-means can split the data in ways that look neat but ignore the real structure, as the independent task shows.
The cluster numbers themselves, 0, 1, 2, are arbitrary names. They have no order and no meaning until you look at what each cluster contains.
Exercise: Find the Clusters
You will cluster generated points for k from 2 to 5, choose k from the inertia values, and save a chart of the result.
Starting state: the course environment, active in your terminal. The script generates its own data.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/find-clusters cd ~/ai-practice/find-clustersWindows PowerShell:
mkdir $HOME\ai-practice\find-clusters cd $HOME\ai-practice\find-clustersSave this as
find_clusters.pyin that folder:"""Group generated points with k-means and compare the inertia for several values of k.""" import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans from sklearn.datasets import make_blobs X, _ = make_blobs(n_samples=300, centers=3, random_state=4) # the generator's groups are ignored print("k inertia") for k in range(2, 6): model = KMeans(n_clusters=k, random_state=4).fit(X) print(f"{k} {model.inertia_:.0f}") model = KMeans(n_clusters=3, random_state=4).fit(X) print("Points per cluster:", np.bincount(model.labels_)) print("Centres:", model.cluster_centers_.round(1).tolist()) fig, ax = plt.subplots() for cluster, marker in zip(range(3), ["o", "s", "^"]): points = X[model.labels_ == cluster] ax.scatter(points[:, 0], points[:, 1], marker=marker, label=f"cluster {cluster}") centres = model.cluster_centers_ ax.scatter(centres[:, 0], centres[:, 1], marker="x", color="black", s=100, label="centres") ax.legend() fig.savefig("clusters.png") print("Saved clusters.png") -
Run it:
python find_clusters.pyOutput, which should match exactly:
k inertia 2 1211 3 542 4 478 5 419 Points per cluster: [ 96 100 104] Centres: [[9.5, 4.6], [4.1, -5.6], [9.5, 0.9]] Saved clusters.png
How the Script Works
The data. make_blobs generates 300 points in two dimensions around 3
centres. It also returns which centre generated each point, but the script
discards that with _: clustering works without labels, as real data would.
Two dimensions keep the result easy to picture; the method works the same
with many features.
Comparing k. For each k from 2 to 5, the script fits k-means and prints
inertia_, rounded to a whole number.
The chosen model. With n_clusters=3, labels_ gives each point's
cluster number and np.bincount counts the points in each: 96, 100 and 104.
cluster_centers_ holds the three centres, rounded to one decimal.
The chart. The loop draws each cluster's points with a different marker,
selecting them with X[model.labels_ == cluster], and the centres are drawn
as black crosses.
What the results show. Inertia falls sharply from 1,211 to 542 when going from two to three clusters, then only slightly: to 478 and 419. Three is the elbow. The cluster sizes are close to the 100 points per generated group; a few points that lie between two groups were assigned to the neighbouring centre. With real data you would now inspect each cluster to decide whether it means anything, for example by comparing the average features of each.
Success: the output matches; you can justify k = 3 from the inertia values and explain why k = 5 is not better despite its lower inertia.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| Different inertia values or cluster sizes | A random_state was changed or removed | Restore random_state=4 in both places |
| The cluster numbers of the same groups differ from the listing | The numbering is arbitrary and can change with settings | Compare cluster sizes and centres, not numbers |
No clusters.png | The script stopped early, or ran in another folder | Read the error message; run ls in the exercise folder |
ModuleNotFoundError | The course environment is not active | Activate it and rerun |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf find-clusters lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse find-clusters lsCheck that the first
lsshowsfind-clustersbefore removing it. Do the independent task first.
Independent task: make_moons generates two interleaving half-circles,
like two crescent moons. Write a short script that generates 300 such points
with make_moons(n_samples=300, noise=0.05, random_state=4), clusters them
with k-means using n_clusters=2 and random_state=4, and prints the share
of points that end up grouped with their own moon. Since cluster numbers are
arbitrary, compute the share both ways round, (labels == y).mean() and
(labels != y).mean(), and take the larger. Predict the result first.
Check Your Understanding
- A colleague tries k from 2 to 20 and picks 20 because it has the lowest inertia. What is wrong with that choice?
- A customer-clustering run produces cluster 0 with 40% of customers. A manager concludes that cluster 0 is "the most important" segment. What is wrong with that reasoning?
Answer and Reasoning
Independent task
from sklearn.cluster import KMeans
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=300, noise=0.05, random_state=4)
labels = KMeans(n_clusters=2, random_state=4).fit(X).labels_
agreement = max((labels == y).mean(), (labels != y).mean())
print(f"Share of points grouped with their own moon: {agreement:.2f}")
It prints 0.75: a quarter of the points are grouped with the wrong moon.
k-means looks for round groups around centres, so it cuts the two crescents
with a roughly straight boundary instead of following their curves. The
clusters look tidy but do not match the real structure. Here you know the
true groups because the data was generated; with real data you would not,
which is why clusters must be checked, not trusted.
Understanding check
- Inertia falls as k grows, as a rule, so the lowest value at the largest k says nothing. Look for the elbow, where adding clusters stops helping much, and check whether the clusters mean something.
- The number 0 is an arbitrary name, and size alone says nothing about importance. The manager would need to look at what distinguishes the customers in each cluster, and how much each group matters to the business.