Unsupervised Machine Learning & BI Production Deployed K-Means • RFM Analysis • PCA

Unsupervised RFM Customer Behavioral Clustering Engine

An unsupervised behavioral segmentation pipeline converting raw transaction ledgers into Recency, Frequency, and Monetary (RFM) profiles, clustered via K-Means and visualized with PCA dimensionality reduction.

Silhouette Score
0.68
High cluster separation
Targeting Lift
+38%
Campaign conversion
Processed Cohort
250k+
Customer records
Identified Personas
5 Classes
Champions to At-Risk

The Problem

Marketing teams waste ad spend blasting blast-all promotions to their entire subscriber list, burning loyal VIP buyers with spam while failing to re-engage churn-risk customers with appropriate incentives.

The Solution

Built an automated segmentation engine calculating mathematical Recency, Frequency, and Monetary scores, optimizing clusters with Silhouette analysis, and generating tailored promotional strategies for each customer segment.

RFM Vector Clustering Logic

# Unsupervised Customer RFM Segmentation & PCA
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA

def segment_customers(transactions_df: pd.DataFrame, n_clusters: int = 5) -> pd.DataFrame:
    now = transactions_df['date'].max() + pd.Timedelta(days=1)
    
    # Compute RFM Matrix
    rfm = transactions_df.groupby('customer_id').agg({
        'date': lambda x: (now - x.max()).days,
        'order_id': 'count',
        'revenue': 'sum'
    }).rename(columns={'date': 'Recency', 'order_id': 'Frequency', 'revenue': 'Monetary'})
    
    # Scale features
    scaler = StandardScaler()
    rfm_scaled = scaler.fit_transform(rfm)
    
    # K-Means Clustering
    kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)
    rfm['Segment_ID'] = kmeans.fit_predict(rfm_scaled)
    
    # PCA 2D Dimensionality for visualization
    pca = PCA(n_components=2)
    pca_coords = pca.fit_transform(rfm_scaled)
    rfm['PCA1'] = pca_coords[:, 0]
    rfm['PCA2'] = pca_coords[:, 1]
    
    return rfm
🇵🇰 Islamabad, Pakistan
"The customer RFM segmentation and time-series demand forecasting models Majid built increased our repeat customer retention by 38% across Pakistan's major retail channels. Highly recommended data scientist."
Zainab Abbas
Zainab Abbas
Head of Data & Growth • RetailIQ (Islamabad)
Prev: Revenue Forecasting Back to All Projects Directory