Unsupervised learning
Not every problem has labels. Unsupervised learning finds groups and oddities in your data — and turns them into action.
Learning objectives
- Explain how k-means clustering works
- Scale features before distance-based methods
- Choose k with silhouette scores, the elbow method and business sense
- Use PCA to visualise high-dimensional data
- Flag anomalies for investigation
- Show what goes wrong without scaling
- Turn segments into actions you can measure
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 2000
customers = pd.DataFrame({
"tenure_months": rng.integers(1, 60, n),
"monthly_spend": rng.normal(40, 15, n).clip(5, 120).round(2),
"support_tickets": rng.poisson(1.2, n),
"on_promo": rng.integers(0, 2, n),
"region": rng.choice(["UK", "IE"], n, p=[0.75, 0.25]),
})
# Hidden "true" pattern: short tenure and many tickets raise churn risk
logit = (1.2 - 0.06 * customers["tenure_months"] + 0.55 * customers["support_tickets"]
- 0.02 * customers["monthly_spend"] + 0.4 * customers["on_promo"])
customers["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# Annual value we might want to predict (regression)
customers["annual_value"] = (customers["monthly_spend"] * 12 * (1 - 0.3 * customers["churned"])
+ rng.normal(0, 40, n)).round(2)5.1 Finding structure without labels
Unsupervised learning finds patterns in data without a target. The most common business use is segmentation: grouping customers, products or documents that behave similarly, so you can tailor actions to each group.
There is no "right answer" to check against, which changes how you judge the result. A segmentation is good if it is stable, makes sense to people who know the customers, and leads to different actions for different groups.
5.2 k-means clustering
k-means places k centre points, assigns each example to its nearest centre, moves each centre to the average of its members, and repeats until stable. Because it uses distances, features must be scaled — otherwise a feature measured in hundreds swamps one measured in single digits.
Python · customer segmentationfrom sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
seg_features = ["tenure_months", "monthly_spend", "support_tickets"]
Xs = StandardScaler().fit_transform(customers[seg_features])
km = KMeans(n_clusters=4, n_init=10, random_state=0).fit(Xs)
customers["segment"] = km.labels_
profile = customers.groupby("segment")[seg_features + ["churned"]].mean().round(1)
profile["size"] = customers["segment"].value_counts().sort_index()
print(profile)
Now name the segments from their profiles — "new, low-spend", "loyal high-spenders", "frustrated (many tickets)" — and check the names with people who know the customers.
5.3 How many clusters?
from sklearn.metrics import silhouette_score
for k in range(2, 8):
labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(Xs)
print(k, round(silhouette_score(Xs, labels), 3))
The silhouette score (−1 to 1) measures how well each point fits its own cluster compared with the nearest other cluster. Combine it with the elbow method (where adding clusters stops reducing within-cluster distance much) — and above all with usefulness: can the business act differently on each segment?
Python · the elbow chartimport matplotlib.pyplot as plt
ks = range(1, 9)
inertia = [KMeans(n_clusters=k, n_init=10, random_state=0).fit(Xs).inertia_ for k in ks]
plt.plot(ks, inertia, "o-")
plt.xlabel("Number of clusters (k)"); plt.ylabel("Within-cluster distance (inertia)")
plt.show()
Inertia always falls as k grows, so look for the bend where extra clusters stop buying much. Our synthetic customers were not generated in distinct groups, so there is no sharp elbow and the silhouette scores are modest. Real data is often like this: the segments are a useful way of slicing a continuous crowd, not natural species waiting to be discovered. Say so when you present them.
5.4 Dimensionality reduction with PCA
Principal component analysis (PCA) compresses many features into a few new ones that keep as much variation as possible. It's useful for visualising high-dimensional data in 2D and for removing redundancy.
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
pca = PCA(n_components=2).fit(Xs)
xy = pca.transform(Xs)
print("Variance explained:", pca.explained_variance_ratio_.round(2))
plt.scatter(xy[:, 0], xy[:, 1], c=customers["segment"], s=6, cmap="tab10")
plt.title("Customer segments (PCA projection)")
plt.show()
Each dot is a customer, coloured by segment. The two axes are blends of the original features, so they have no simple business meaning; the chart is for seeing shape and overlap, not for reading off values.
5.5 Anomaly detection
Unsupervised methods can also flag unusual examples — potential fraud, faults or data errors. scikit-learn's IsolationForest is a common starting point. As always, flagged items are leads for human investigation, not verdicts.
from sklearn.ensemble import IsolationForest
iso = IsolationForest(contamination=0.01, random_state=0).fit(Xs)
customers["unusual"] = iso.predict(Xs) == -1
print(customers.loc[customers["unusual"], seg_features].head())
print("Flagged:", customers["unusual"].sum(), "of", len(customers))
contamination=0.01 is you telling the model to flag the most unusual 1%. It will always find that 1%, whether or not anything is wrong, so the number flagged is your choice, not a discovery.
5.6 See why scaling matters
Earlier you were told to scale before clustering. Here is what happens if you don't. Cluster the raw values and compare the result with the scaled segments:
Python · clustering without scalingraw = KMeans(n_clusters=4, n_init=10, random_state=0).fit(customers[seg_features])
customers["segment_raw"] = raw.labels_
print(customers.groupby("segment_raw")[seg_features].mean().round(1))
The unscaled segments differ on tenure and spend, which run into the dozens, while average ticket counts are nearly the same in every group. Tickets range only from 0 to about 6, so they barely affect the distances, and the "frustrated customers" group has vanished. Nothing in the output warns you; the clustering simply ignores a feature you care about.
5.7 From segments to action
A segmentation earns its keep only when each group gets a different treatment, and you measure whether the treatment works. A simple plan for the four segments might look like this:
| Segment (named from its profile) | Action | How you'll know it worked |
|---|---|---|
| New customers | Onboarding emails and a check-in call in month two | Churn in the first six months, against a group that didn't get them |
| Frustrated (many tickets) | Priority support and a follow-up from a named agent | Repeat tickets and churn over the next quarter |
| Loyal high-spenders | Early access to new products; no discounts needed | Spend and retention hold steady |
| Low spenders | Suggestions based on past purchases | Average monthly spend |
Keep a comparison group for each action. Without one you can't tell whether a change came from what you did or would have happened anyway.
Using the segment column, find the segment with the highest churn rate and print its average tenure, spend and tickets. What would you call it?
Your turn# Write your code here, then press RunShow a solution
rates = customers.groupby("segment")["churned"].mean().round(2)
worst = rates.idxmax()
print(rates)
print("Highest churn: segment", worst)
print(customers.loc[customers["segment"] == worst, seg_features].mean().round(1))
# Two segments are almost tied. Low spenders and newer customers both churn about half the time,
# for different reasons, so they need different actions.Compare the average tenure_months, monthly_spend and support_tickets of customers flagged unusual with everyone else. What kind of customer has the isolation forest picked out?
Your turn# Write your code here, then press RunShow a solution
print(customers.groupby("unusual")[seg_features].mean().round(1))
# The flagged group stands out mainly for very high ticket counts.
# Unusual is not the same as wrong. Someone still has to look.Key takeaways
- k-means assigns points to the nearest of k centres and updates centres iteratively.
- Scale features before clustering.
- Choose k using metrics and usefulness.
- PCA compresses features while keeping variation.
- Anomalies are leads for investigation, not verdicts.
- Unscaled clustering silently ignores small-range features.
- A segmentation is only useful if each segment gets a different, measured action.