Unsupervised Learning and Clustering

Updated · 9 min read
mediumPython 3.13aimachine-learningunsupervised-learningclusteringk-meansscikit-learn

Unsupervised learning is machine learning on data without labels. Nobody tells the model the right answer; it looks for structure on its own, such as groups of similar examples or a simpler way to describe the data. Clustering is the most common kind: it puts similar examples into the same cluster and different examples into different clusters.

This chapter's running example is an online course. Its team wants to know what kinds of learner it has, so it can support each kind differently, but nobody has labeled the students. Clustering finds the groups from study habits alone.

Supervised and Unsupervised Learning

Supervised learningUnsupervised learning
DataFeatures and a labelFeatures only
GoalPredict the label for new examplesFind structure: groups, patterns, simpler descriptions
Example questionWill this family pay late?What kinds of learner do we have?
Checking the resultCompare predictions with real labelsMeasure how tight the groups are, and ask whether they are useful
Common algorithmsRegression, trees, forestsk-means, hierarchical clustering, PCA

Creating the Data

This program creates 300 made-up students with six study features, with a fixed seed so everyone gets the same data. Four kinds of learner are hidden inside, but the saved file has no column saying which is which:

Python
import numpy as np
import pandas as pd
 
rng = np.random.default_rng(25)  # a fixed seed, so everyone gets the same data
# Made-up study habits: four hidden kinds of learner, which clustering has to rediscover without being told
groups = {  # (how many, average hours, videos, quizzes, forum posts, days active, quiz score)
    "steady":   (90, 8, 10, 6, 2, 5, 82),
    "watchers": (80, 6, 18, 1, 0.5, 3, 64),
    "crammers": (70, 4, 4, 3, 1, 1.5, 70),
    "helpers":  (60, 10, 8, 5, 12, 6, 86),
}
rows = []
for name, (n, hours, videos, quizzes, posts, days, score) in groups.items():
    rows.append(pd.DataFrame({
        "hours_per_week": rng.normal(hours, 1.5, n).clip(0.5).round(1),
        "videos_watched": rng.poisson(videos, n),
        "quizzes_taken": rng.poisson(quizzes, n),
        "forum_posts": rng.poisson(posts, n),
        "days_active": rng.normal(days, 0.8, n).clip(1, 7).round().astype(int),
        "avg_quiz_score": rng.normal(score, 6, n).clip(0, 100).round().astype(int),
    }))
students = pd.concat(rows).sample(frac=1, random_state=0).reset_index(drop=True)  # shuffle; no group column
students.to_csv("study_habits.csv", index=False)
print("Saved", len(students), "students with", students.shape[1], "study features")
Output
Saved 300 students with 6 study features

Example: K-Means Clustering

K-means splits the data into k clusters. Each cluster has a center, and every student belongs to the nearest center.

K-means finds four kinds of learner without labels

This program uses study_habits.csv from "Unsupervised Learning and Clustering".

Python
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
 
students = pd.read_csv("study_habits.csv")
X = StandardScaler().fit_transform(students)      # put every feature on the same scale first
 
for k in range(2, 7):                              # try several numbers of groups
    kmeans = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
    print(f"k={k}  inertia {kmeans.inertia_:6.1f}  silhouette {silhouette_score(X, kmeans.labels_):.3f}")
 
kmeans = KMeans(n_clusters=4, n_init=10, random_state=0).fit(X)
students["group"] = kmeans.labels_
profile = students.groupby("group").mean().round(1)
profile["students"] = students["group"].value_counts()
print(profile.T)                                   # one column per group
Output
k=2  inertia 1043.5  silhouette 0.377
k=3  inertia  758.4  silhouette 0.399
k=4  inertia  553.5  silhouette 0.397
k=5  inertia  499.7  silhouette 0.349
k=6  inertia  468.1  silhouette 0.284
group              0     1     2     3
hours_per_week   8.3   4.0   6.2  10.0
videos_watched  10.4   3.7  17.4   8.3
quizzes_taken    6.4   3.4   0.8   4.7
forum_posts      2.2   1.2   0.6  12.1
days_active      5.0   1.6   3.2   6.0
avg_quiz_score  82.8  68.8  64.4  84.0
students        92.0  69.0  81.0  58.0

Explanation: StandardScaler puts all six features on the same scale first, so quiz scores (around 80) don't drown out forum posts (around 2). The loop fits k-means with 2 to 6 clusters and prints two quality measures, explained in the next section. The final model uses 4 clusters, and the profile table shows the average student in each one (the students row shows .0 only because the table mixes whole numbers with averages). Reading the columns, the groups have clear meanings:

GroupStudentsWhat stands outA name for it
0928.3 hours, 6.4 quizzes, 5 days a week, score 82.8Steady learners
169Only 4.0 hours, on 1.6 days a weekCrammers
28117.4 videos but 0.8 quizzes, the lowest score (64.4)Video watchers
35812.1 forum posts, 6 days a week, score 84.0Forum helpers

The hidden groups had 90, 70, 80 and 60 students, so k-means rediscovered them with only a few students placed differently. The numbers 0 to 3 mean nothing; the names come from you, by reading the profiles.

How K-Means Works

StepWhat happens
1. StartIt is used to place k centers, usually at randomly chosen examples
2. AssignEvery example joins its nearest center
3. UpdateEach center moves to the average of its examples
4. RepeatSteps 2 and 3 repeat until the centers stop moving
5. Restartn_init=10 runs the whole thing 10 times from different starts and keeps the best

Choosing the Number of Clusters

K-means needs k before it starts, so you try several values and compare them:

MeasureDescriptionHere
InertiaIt is used to measure the total squared distance from examples to their centers; lower is tighter, but it always falls as k growsDrops by 285, then 205, then only 54: an elbow at k=4
Silhouette scoreIt is used to measure how much closer each example is to its own cluster than to the next one, from −1 to 1; higher is better0.399 at k=3 and 0.397 at k=4, nearly tied

The two measures don't fully agree, which is normal. With k=3, k-means merges the steady learners and the forum helpers into one group, and both groups study a lot. With k=4, the forum helpers get their own group, which is useful because they behave differently. The best k is the one whose groups you can explain and act on, with the measures as a guide.

Example: Hierarchical Clustering

Hierarchical clustering starts with every example as its own cluster and repeatedly merges the two closest clusters, building a tree of merges. Cutting the tree at 4 clusters gives a grouping you can compare with k-means.

This program uses study_habits.csv from "Unsupervised Learning and Clustering".

Python
import pandas as pd
from sklearn.cluster import AgglomerativeClustering, KMeans
from sklearn.metrics import adjusted_rand_score
from sklearn.preprocessing import StandardScaler
 
students = pd.read_csv("study_habits.csv")
X = StandardScaler().fit_transform(students)
 
kmeans_groups = KMeans(n_clusters=4, n_init=10, random_state=0).fit_predict(X)
tree_groups = AgglomerativeClustering(n_clusters=4, linkage="ward").fit_predict(X)   # hierarchical
 
print(pd.crosstab(kmeans_groups, tree_groups, rownames=["k-means"], colnames=["hierarchical"]))
print(f"Agreement (adjusted Rand index): {adjusted_rand_score(kmeans_groups, tree_groups):.2f}")
Output
hierarchical   0   1   2   3
k-means
0             90   0   0   2
1              0   0  69   0
2              2  79   0   0
3              3   0   0  55
Agreement (adjusted Rand index): 0.94

Explanation: AgglomerativeClustering with linkage="ward" merges the pair of clusters that increases spread the least. The cross table shows that each k-means group maps almost entirely to one hierarchical group; only 7 of 300 students are placed differently. The adjusted Rand index measures agreement between two groupings, where 1.0 is identical and 0 is chance, so 0.94 means the two methods found the same structure, which makes the groups more trustworthy.

Comparing Clustering Algorithms

AlgorithmHow it groupsGood forWatch out for
K-meansNearest of k centersRound, similar-sized groups; large dataYou must choose k
HierarchicalMerges closest clusters into a treeSeeing groups at every levelSlow on very large data
DBSCANDense regions of pointsOdd shapes; marking outliersChoosing the density setting
Gaussian mixtureOverlapping bell-shaped groupsA probability of belonging to each groupAssumes bell shapes

Common Mistakes

Clustering unscaled data. The feature with the biggest numbers decides the groups.

Trusting the cluster numbers. Group 2 is not "worse" than group 1; the numbers are arbitrary labels.

Assuming clusters are real. K-means always returns k groups, even in data with no groups at all. Check the measures, compare methods, and look at the profiles.

Choosing k by inertia alone. Inertia always falls as k grows; look for the elbow, not the minimum.

Interview Corner

What is the difference between supervised and unsupervised learning?

Supervised learning trains on labeled examples to predict labels; unsupervised learning has no labels and finds structure, such as clusters or a simpler representation.

How do you choose k in k-means?

Try several values and compare inertia (look for the elbow) and silhouette scores, then check that the resulting groups make sense for the problem. Domain knowledge decides between close candidates.

Practice

Exercise: a fifth group. Fit k-means with n_clusters=5 and print the profile table. Which group splits, and does the new group have a meaning you could name?

Check your understanding:

  1. Why are features scaled before k-means?
  2. What happened to the steady learners and forum helpers when k was 3?
  3. What does an adjusted Rand index of 0.94 tell you?

Quick check: clustering

4 questions
1What does unsupervised learning work with?
2Why does inertia alone not choose k?
3What did the four clusters turn out to be?
4What did hierarchical clustering show?

Key Takeaways

Quick reference

NeedCode
Scale featuresStandardScaler().fit_transform(data)
K-meansKMeans(n_clusters=4, n_init=10).fit(X)
Cluster labelskmeans.labels_
Silhouettesilhouette_score(X, labels)
HierarchicalAgglomerativeClustering(n_clusters=4, linkage="ward")
Compare groupingsadjusted_rand_score(a, b)

Was this tutorial helpful?

Lesson 127 of 186