Stop 11 · Unsupervised LearningProjects · 1/1

Customer Segmentation With K-Means

Part of the Machine Learning Roadmap

In short

Sending the same offer to every customer wastes money. This project groups an online store's customers by how recently, how often and how much they buy, then turns each group into a marketing action. It shows you can make unsupervised results useful.

Group customers of an online store into segments using features like recency, frequency and monetary value (RFM), then describe each segment and suggest a marketing action. It shows you can turn unsupervised results into business decisions.

The jaadu behind a busy kirana counter sorts customers' shopping bags into four colour-coded baskets on the shelf behind it.

Think of it like this

The kirana owner's mental register

A kirana owner knows his regulars without a computer: the aunty who buys every morning, the student who comes once a month for a big stock-up, the family that hasn't visited since Diwali. He treats each group differently. RFM plus k-means writes that mental register down for 50,000 online customers.

Watch it happen

From transactions to segments

Transactions
RFM per customer
Log + scale
K-means
Actions

1/5Start with invoice lines: customer, date, quantity, price.

The big ideas

What you need to know

Recency

Days since the last purchase. Lower is better. It's often the strongest signal of who will buy again.

Frequency

How many separate orders. Count invoices, not line items.

Monetary

Total spend. Remove returns and cancelled orders first, or a few big refunds will distort it.

End with actions

A segment is only useful if the business can do something different for it. Profile each one with averages and sizes.

How it works

Project steps

  1. 1

    Clean

    Use the UCI Online Retail dataset. Drop rows without a customer ID, cancelled invoices and negative quantities.

  2. 2

    Build RFM

    Group by customer and compute recency, frequency and monetary value.

  3. 3

    Transform

    log1p the skewed columns and standardise.

  4. 4

    Cluster

    Choose k with elbow and silhouette, then fit k-means.

  5. 5

    Profile and act

    Average RFM per cluster, give names, and write one marketing action each.

See it in code

Walk through the code

python
1import numpy as np2import pandas as pd3from sklearn.cluster import KMeans4from sklearn.pipeline import make_pipeline5from sklearn.preprocessing import FunctionTransformer, StandardScaler6 7df = pd.read_excel("Online Retail.xlsx", parse_dates=["InvoiceDate"])8df = df.dropna(subset=["CustomerID"])9df = df[(df["Quantity"] > 0) & (~df["InvoiceNo"].astype(str).str.startswith("C"))]10df["Amount"] = df["Quantity"] * df["UnitPrice"]11 12snapshot = df["InvoiceDate"].max() + pd.Timedelta(days=1)13rfm = df.groupby("CustomerID").agg(14    recency=("InvoiceDate", lambda d: (snapshot - d.max()).days),15    frequency=("InvoiceNo", "nunique"),16    monetary=("Amount", "sum"),17)18 19model = make_pipeline(FunctionTransformer(np.log1p), StandardScaler(),20                      KMeans(n_clusters=4, n_init=10, random_state=0))21rfm["segment"] = model.fit_predict(rfm[["recency", "frequency", "monetary"]])22 23profile = rfm.groupby("segment").agg(["mean", "count"]).round(1)24print(profile)

1/4Load, drop rows with no customer, remove cancellations (invoice numbers starting with C) and compute line amounts.

RFM segmentation of the UCI Online Retail dataset in one pipeline.

Save yourself the pain

Common mistakes

Oops

Clustering raw monetary values where a few customers spend 1,000 times the median.

Do this instead

Apply log1p before scaling, or those few outliers will form their own clusters and squash everyone else together.

Oops

Ending the project with a scatter plot and cluster numbers.

Do this instead

Name each segment, like 'loyal big spenders' or 'lapsed one-timers', and recommend a concrete action for each.

Your mission

Ship the segmentation

~90 min

Quick check

Why take log1p of frequency and monetary before k-means?

Go deeper

  1. 1Compute RFM features from the Online Retail dataset.
  2. 2Choose k with silhouette scores and name each segment, like 'loyal big spenders'.
  3. 3Suggest one campaign per segment in the README.

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge