Suffolk University • Sawyer Business School

Segments, Structure & Anomalies

Learning without labels: RFM customer segmentation with k-means, choosing k honestly, hierarchical clustering and DBSCAN, PCA and UMAP for seeing high-dimensional data, and Isolation Forest for the transactions that don't belong

Session 10 of 13 · Mon Nov 23
Module: Unsupervised Learning
150 Minutes
Mondays 5:00 PM
Hands-On Learning
01 // LEARNING OBJECTIVES

What You'll Learn Today

By the end of tonight you'll have both the concept and the working code — every objective maps to a cell you run yourself.

01

Segment Customers With RFM + k-Means

Recency, Frequency, Monetary from a million retail transactions, scaled and clustered — then named: Champions, Loyal, At Risk, Hibernating. A segmentation a marketing team can act on Monday.

02

Choose k Without Fooling Yourself

The elbow on inertia, the silhouette score, and the truth: k is a business decision informed by the data, not decided by it.

03

See High-Dimensional Data

PCA as the linear projection that keeps the most variance; UMAP as the nonlinear map that keeps neighborhoods. What each is for and what each distorts.

04

Find What Doesn't Belong

Isolation Forest scores every point by how easy it is to isolate. Fraud, sensor faults, data-entry errors — anomaly detection when labels are rare or absent.

02 // SESSION AGENDA

Today's Journey

A business question, a dataset, a model — and the judgment to evaluate it.

5:00 PM - 5:20 PM

Milestone 2 Debrief & Learning Without a Target

20 minutes

The best baselines and metrics from Milestone 2, then a shift: nine sessions with a y column, and now none. Unsupervised learning finds structure — groups, directions, outliers — and the business supplies the meaning. Meet the data: Online Retail II, 1,067,371 transactions from a UK gift retailer, 2009–2011.

  • No target means no accuracy — evaluation is about usefulness, stability, and whether the segments make sense to the people who own them
  • From transactions to customers: one groupby turns a million rows into ~5,900 RFM profiles
5:20 PM - 5:45 PM

k-Means, Step by Step

25 minutes

Pick k centroids, assign every customer to the nearest, move each centroid to the mean of its members, repeat until nothing moves. The k-Means Explorer runs it one step at a time. Then the two things that go wrong: bad initialization (k-means++ fixes it) and unscaled features (StandardScaler and a log on the dollar column fix that).

  • k-means finds compact, roughly spherical clusters of similar size — it will find them even when they aren't there
  • Log-transform Monetary and Frequency before scaling: a $50,000 customer should not be a cluster of one
5:45 PM - 6:05 PM

How Many Segments? Elbow, Silhouette, and Judgment

20 minutes

Inertia falls with every extra k; the elbow is where it stops falling fast. Silhouette measures how much closer each point is to its own cluster than the next one. On the retail data both point to 4–5 — and the marketing team can staff campaigns for four. That settles it.

  • Silhouette above 0.5 is clean structure; 0.25–0.5 is typical business data; below that you are slicing a continuum
  • Profile every cluster (mean R, F, M, size) and name it — a cluster without a name is not a segment
6:05 PM - 6:15 PM

Break

10 minutes

Stretch, coffee, name your favorite cluster.

6:15 PM - 6:40 PM

Other Shapes: Hierarchical, DBSCAN, Gaussian Mixtures

25 minutes

Agglomerative clustering builds a dendrogram you can cut at any height — no k up front. DBSCAN finds dense regions of any shape and labels the rest noise. Gaussian mixtures give soft memberships: a customer can be 70% Loyal and 30% At Risk. Same RFM data, three different stories.

  • DBSCAN's eps and min_samples replace k — and its 'noise' label is a free anomaly detector
  • Use the dendrogram to explain to a manager why 4 clusters and not 7
6:40 PM - 7:05 PM

Seeing High Dimensions: PCA and UMAP

25 minutes

PCA rotates the data to the directions of greatest variance; the first two components are the best flat picture of a 20-column table and the explained-variance curve tells you how much you lost. UMAP bends space to keep neighbors together — better pictures, less trustworthy distances. Both make a cluster plot possible.

  • PCA loadings tell you what each component means: PC1 on RFM is 'overall value', PC2 is 'recency vs. frequency'
  • Never cluster on a UMAP embedding and call the distances real — cluster on the scaled features, plot on the embedding
7:05 PM - 7:30 PM

Anomalies: Isolation Forest & Your Project

25 minutes

Random trees isolate outliers in a few splits and normal points in many; the average path length is the anomaly score. On a simulated card-transaction stream with 1% fraud, Isolation Forest puts roughly a third of the fraud into the top 5% of scores with no labels at all — a starting point for the review queue, not a finished detector. Then the project: if yours has no label, tonight’s segmentation notebook is your template; if it has a clock, next week’s forecasting notebook is.

  • contamination sets the alert rate; the business sets contamination — how many alerts can the fraud team review per day?
  • Milestone 3 (tuned model + error analysis) due Mon Nov 30; Milestone 4 (dry run) Mon Dec 7, slides on Canvas by 5:00 PM
FEATURED VIDEO

StatQuest — K-means Clustering

Assign, update, repeat — and why you run it more than once.

FEATURED VIDEO

StatQuest — PCA Main Ideas in 5 Minutes

Directions of greatest variance, explained with a picture.

03 // INTERACTIVE RESOURCES

Tools & Learning Materials

Notebooks, readings, explorers, and the stories behind the methods.

Hands-On

Session 10 Notebook — Segments, Structure & Anomalies

RFM from Online Retail II, k-means with elbow and silhouette, cluster profiles and names, agglomerative and DBSCAN, PCA loadings and UMAP, and Isolation Forest on a synthetic fraud stream.

Open in Colab
Play

The k-Means Explorer

Customers on a recency × frequency plane. Step the algorithm one assignment at a time, re-initialize, change k, and watch the elbow chart and the segment table update — including the case where k-means confidently finds clusters that aren't there.

Open the explorer
Data

Online Retail II — the dataset (UCI)

1,067,371 transactions from a UK-based online gift retailer, Dec 2009 – Dec 2011, with customer IDs, quantities, prices, and countries. Cancellations are the invoices starting with 'C'.

Open the dataset page
Interactive

Naftali Harris — Visualizing K-Means Clustering

Place centroids by hand and step the algorithm on several datasets, including the ones where k-means fails. The original explorer our K-Means Explorer is modeled on.

Open the explainer
Interactive

Naftali Harris — Visualizing DBSCAN Clustering

Density-based clustering step by step: watch core points, border points, and noise get labeled on smiley faces and moons.

Open the explainer
Interactive

Setosa — Principal Component Analysis, Explained Visually

Rotate a 2-D and a 3-D cloud and watch the principal components find the directions of greatest variance.

Open the explainer
Reading

ISLP, Chapter 12 — Unsupervised Learning

PCA (12.2), k-means and hierarchical clustering (12.4), with the honest section on how unstable clusters can be. Read 12.2 and 12.4.

Read Chapter 12 (free PDF)
Reading

scikit-learn User Guide — Clustering

The comparison table at the top — which algorithm for which shape, scale, and use case — is the single most useful page in the clustering literature.

Open the guide
Go Deeper

scikit-learn User Guide — Novelty and Outlier Detection

Isolation Forest, Local Outlier Factor, One-Class SVM, and the elliptic envelope compared on the same toy data. Read it before you pick a method for a real fraud problem.

Open the guide
Story

Story: Mastercard Decision Intelligence — Scoring 150 Billion Transactions

Industry reporting on Mastercard's real-time fraud scoring: higher detection and materially fewer false declines, each decision in under 50 milliseconds. Anomaly scores plus supervised models plus a threshold the business chose — tonight and Session 6 combined.

Read the report
Video

StatQuest — K-means Clustering & PCA Main Ideas

Search the index for 'K-means' and 'PCA main ideas'. Eight and five minutes respectively. Also embedded on this page.

Watch on YouTube
Refresher

Refresher: Principal Component Analysis (ISOM 730 notebook)

Prof. Arslan's earlier notebook: PCA on digits and faces, choosing the number of components, and PCA as noise filtering. The picture-heavy version of tonight's PCA segment. Hosted in the course repo — opens in Colab with one click.

Open in Colab
04 // HANDS-ON ACTIVITIES

Learning by Doing

Open the notebook and build it with us.

Activity 1

From a Million Transactions to Four Segments

Build RFM features for every customer in Online Retail II, scale them properly, choose k with the elbow and silhouette, profile the clusters, and give each one a name and a marketing action.

1

Transactions → customers

Drop cancellations (invoice starts with 'C') and rows without a customer ID. Group by customer: Recency = days since last invoice, Frequency = number of invoices, Monetary = total spend.

2

Scale like you mean it

log1p on Frequency and Monetary (right-skewed), then StandardScaler on all three. Look at the histograms before and after.

3

Choose k

KMeans(n_init=10) for k = 2…10; plot inertia and silhouette_score. Pick k where both agree and marketing can act.

4

Profile and name

groupby cluster: mean R, F, M in original units, plus size. Name each (Champions, Loyal, At Risk, Hibernating…) and write one action per segment.

python
import pandas as pd, numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

raw = pd.read_excel('online_retail_II.xlsx', sheet_name=None)          # UCI zip → xlsx, two sheets
df = pd.concat(raw.values()).dropna(subset=['Customer ID'])
df = df[~df['Invoice'].astype(str).str.startswith('C') & (df['Quantity'] > 0)]
df['Amount'] = df['Quantity'] * df['Price']
snapshot = df['InvoiceDate'].max() + pd.Timedelta(days=1)

rfm = df.groupby('Customer ID').agg(
    Recency=('InvoiceDate', lambda d: (snapshot - d.max()).days),
    Frequency=('Invoice', 'nunique'),
    Monetary=('Amount', 'sum'))
Z = StandardScaler().fit_transform(np.column_stack([rfm['Recency'], np.log1p(rfm['Frequency']), np.log1p(rfm['Monetary'])]))

for k in range(2, 9):
    labels = KMeans(n_clusters=k, n_init=10, random_state=835).fit_predict(Z)
    print(f'k={k}: silhouette {silhouette_score(Z, labels, sample_size=3000, random_state=835):.3f}')

km = KMeans(n_clusters=4, n_init=10, random_state=835).fit(Z)
rfm['segment'] = km.labels_
print(rfm.groupby('segment').agg(n=('Recency', 'size'), Recency=('Recency', 'mean'), Frequency=('Frequency', 'mean'), Monetary=('Monetary', 'mean')).round(1))

Look at the profile table and the names write themselves: a small cluster with low recency, high frequency, high spend — Champions; a large cluster that bought once, long ago — Hibernating. Now the question that makes this a business deliverable rather than a plot: what do you do differently for each? Champions get early access; At Risk get a win-back offer; Hibernating get nothing (the offer costs more than they are worth). A segmentation is only as good as the four sentences that follow it.

05 // KEY TAKEAWAYS

What to Remember

k-means finds compact clusters of similar size and finds them whether or not they exist. Scale (and log) first, use k-means++, and use the elbow and silhouette to inform k — then let the business decide.

PCA keeps variance; UMAP keeps neighborhoods. Cluster on the scaled features, plot on the embedding, and read PCA loadings to name the axes.

Isolation Forest scores by how easy a point is to isolate — anomaly detection with no labels. The alert rate is a business choice: how many cases can the fraud team review tomorrow?

06 // HOMEWORK

Before Next Session

Complete these before next Monday — they are the practice that makes the next session land.

Milestone 3 + Practice (pick a track, ungraded) Milestone 3 is due Mon Nov 30, 11:59 PM, on Canvas: your tuned model with an error analysis and a half-page model card (the full list is in Session 9). Practice, ungraded, for projects that need it — Track A, Segmentation: RFM on Online Retail II, a defended choice of k (elbow + silhouette + business reasoning), a profile table with a name and a one-sentence marketing action per segment, a PCA scatter colored by segment, and a paragraph on how you would measure whether the segmentation worked. Track B, Forecasting (after Session 11): hourly bike demand with a seasonal-naive baseline, a lag-feature gradient-boosting model evaluated with TimeSeriesSplit, MAE by hour-of-day, and one paragraph on what the model gets wrong on holidays. Either track: run it for yourself; nothing to submit.
07 // PRACTICE

Test Yourself

Exam-style questions for the ideas in this session — Trust & Structure. Every wrong answer names the misconception behind it.

Q31 6,000 customers, 80,000 tickets, plain KFold. Why 0.91 is a mirage. Q32 Read a SHAP waterfall the way a loan officer must. Q33 A 90% conformal interval. What exactly is being promised? Q34 RFM clustering on raw dollars. Guess which column wins. Q35 Equal accuracy, unequal false negatives. Is the model fair? Q36 4% MAPE offline, 14% live. The split that saw the future.

All of Trust →

Coming Next

Session 11: Forecasting — Time Series With ML & Foundation Models

Why random splits lie on time series, lag and rolling features, gradient boosting as a forecaster, classical baselines with StatsForecast, and zero-shot forecasting with Chronos-2 and TimesFM.

Time SeriesForecastingFoundation Models