← Back to case study

PROJECT 079 · PYTHON SOURCE

Wholesale customer segmentation

Study-specific code. Shared modules, dependency versions, and reproduction instructions are included in all project files.

Download Python file ↓
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from portfolio.data import load
from portfolio.constants import *
from portfolio.methods import result, sql, rates, associations, distribution, regression, classification, cluster
from portfolio.engine import execute

META = {'id': 79, 'dataset': 'wholesale', 'title': 'Wholesale customer segmentation', 'question': 'Do customers form interpretable groups based on annual spending patterns?', 'method': 'Three-cluster K-means on standardized log spending, with silhouette and median profiles.', 'action': 'Review cluster profiles with a commercial owner before assigning business labels or actions.', 'limitations': 'Annual customer spending uses source monetary units, not an assumed currency. There are no margins, transactions or dates. Customer segments are descriptive and do not establish promotion response. '}

def analyze():
    df = load('wholesale').copy()
    t,tagged,sil=cluster(df,SPEND,k=3)
    out=result(t,'cluster','customers','Customers',f'Exploratory silhouette={sil:.3f}. Three clusters were prespecified; no claim of natural or stable business segments.',extra={'cluster_assignments':tagged[['row_id','cluster']], 'median_profiles':t})
    return out

if __name__ == "__main__":
    execute(Path(__file__).parent, META, analyze)