Customer Segmentation: RFM Analysis & Unsupervised K-Means

Treating all customers identically is a recipe for wasted marketing spend. In this class, we master Unsupervised Customer Segmentation by combining classical RFM Analysis with K-Means Clustering.

The 3 Dimensions of RFM Modeling

  • Recency (R): Days elapsed since the customer's last interaction. (Low days = High engagement).
  • Frequency (F): Total number of completed orders. (High count = High brand loyalty).
  • Monetary (M): Cumulative revenue generated. (High dollars = High commercial value).

End-to-End Python Pipeline: RFM + K-Means

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

# Sample customer transaction dataset
np.random.seed(42)
n_cust = 500
df_rfm = pd.DataFrame({
    'recency_days': np.random.exponential(scale=45, size=n_cust).astype(int),
    'frequency_orders': np.random.poisson(lam=6, size=n_cust) + 1,
    'monetary_value': np.random.exponential(scale=350, size=n_cust) + 25
})

# Step 1: Preprocessing & Scaling (Mandatory for distance-based clustering!)
scaler = StandardScaler()
rfm_scaled = scaler.fit_transform(df_rfm)

# Step 2: Determine optimal k using Silhouette Analysis
for k in range(2, 6):
    km = KMeans(n_clusters=k, init='k-means++', random_state=42)
    labels = km.fit_predict(rfm_scaled)
    sil_score = silhouette_score(rfm_scaled, labels)
    print(f"k = {k} → Silhouette Score: {sil_score:.4f}")

# Step 3: Fit final 3-cluster segmentation model
final_kmeans = KMeans(n_clusters=3, init='k-means++', random_state=42)
df_rfm['cluster_id'] = final_kmeans.fit_predict(rfm_scaled)

# Step 4: Cluster Profiling
profile = df_rfm.groupby('cluster_id').agg({
    'recency_days': 'mean',
    'frequency_orders': 'mean',
    'monetary_value': 'mean',
    'cluster_id': 'count'
}).rename(columns={'cluster_id': 'customer_count'})

print("\n--- Segment Business Profiles ---\n", profile.round(2))

Translating Clusters into Business Strategy

Cluster 0 (Low Recency, High Frequency, High Monetary) represents your VIP Champions — enroll them in loyalty clubs. Cluster 1 (High Recency, Low Frequency) represents Lapsed / Churned Customers — target them with aggressive win-back email discounts.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is RFM Analysis in marketing data science?

RFM segments customers by three quantitative behavioral metrics: Recency (days since last purchase), Frequency (total count of purchases), and Monetary (total dollar value spent).

Q2. How does the K-Means clustering algorithm work?

K-Means is an unsupervised algorithm that partitions data into k non-overlapping clusters: 1. Initialize k centroids randomly (or via K-Means++), 2. Assign each data point to its nearest centroid (Euclidean distance), 3. Recompute centroid coordinates as the mean of assigned points, 4. Repeat until convergence.

Q3. How do you choose the optimal number of clusters k?

Use the Elbow Method (plotting WCSS/inertia vs. k and finding the bend) paired with the Silhouette Score (measuring how tightly grouped points are to their own cluster vs. neighboring clusters; ranges from -1 to +1).

Q4. Why is feature scaling mandatory before running K-Means?

K-Means relies on Euclidean distance. If 'Annual Income' ranges from $20,000 to $200,000 while 'Purchases' ranges from 1 to 10, the income dimension will completely dominate distance calculations unless scaled.

Q5. What is the K-Means++ initialization algorithm?

Standard K-Means initializes centroids purely at random, which can lead to suboptimal local minima. K-Means++ selects the first centroid randomly and subsequent centroids with probability proportional to the squared distance from existing centroids, spreading them out.

Explore Related Data Science Tutorials & Next Steps

Broaden your statistical analysis, Python data wrangling, and production engineering expertise:

Customer Churn Prediction Modeling

Identify which customer segments exhibit the highest retention risk.

SVD & Principal Component Analysis

Reduce feature dimensions to visualize multi-dimensional clusters.

Streamlit Business Intelligence Dashboards

Display interactive customer segment profiles to marketing executives.

End-to-End Capstone Project Blueprint

Execute an end-to-end customer analytics and segmentation project.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!