60 Mins

Milestone 1: Customer Segmentation Clustering

Casford Cohort Segmentation Engine: Unsupervised Pipeline Construction

Scenario: The Casford Analytics Engine requires a robust, reproducible customer segmentation system. Instead of relying on manual profiling, you are tasked with engineering a fully unsupervised machine learning pipeline. The input dataset consists of key customer behavioral metrics: annual income, spending scores, and transaction frequencies, containing scattered missing values that must be automatically resolved before grouping.

Mission Objectives: Build an end-to-end Scikit-Learn Pipeline that chain-links preprocessing transformers (handling missing entries with median imputation and scaling numeric values to zero mean and unit variance) and terminates with a KMeans clustering estimator. Your solution must cleanly split the synthetic user base into structured customer cohorts.

Goals & Requirements: To successfully pass this milestone, you must construct an pipeline execution workflow that successfully handles missing entries, scales multi-dimensional inputs, and segments the input space. The pipeline must calculate the silhouette score to verify partition stability and output integer-labeled array predictions for deployment pipelines.

Practical Hints: Always scale your numeric metrics because KMeans distance calculations are sensitive to magnitude variations. Ensure you specify a fixed random_state inside the KMeans constructor to achieve reproducible cluster configurations across runs. Handle missing data using SimpleImputer directly inside the Pipeline to avoid data leakage during cross-validation stages.

Operator Note: Verify that your data scaling steps precede KMeans. Running KMeans directly on raw features will bias the cluster centers towards features with massive absolute numerical ranges.
Python 3
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

# 1. Generate Simulated Casford Customer Data
np.random.seed(42)
n_customers = 300
data = {
    'annual_income_k': np.concatenate([np.random.normal(40, 5, 100), np.random.normal(80, 8, 100), np.random.normal(120, 10, 100)]),
    'spending_score': np.concatenate([np.random.normal(20, 8, 100), np.random.normal(50, 10, 100), np.random.normal(80, 8, 100)]),
    'transaction_freq': np.concatenate([np.random.poisson(5, 100), np.random.poisson(15, 100), np.random.poisson(25, 100)])
}
df = pd.DataFrame(data)

# Inject random NaN values to test raw data handling robustly
df.loc[df.sample(frac=0.05, random_state=42).index, 'spending_score'] = np.nan

# 2. Build the End-to-End Pipeline
pipeline = Pipeline([
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler()),
    ('kmeans', KMeans(n_clusters=3, random_state=42, n_init=10))
])

# 3. Fit and Predict Cohorts
cluster_labels = pipeline.fit_predict(df)

# 4. Extract Transformed Data to Compute Evaluation Scores
processed_data = pipeline.named_steps['scaler'].transform(
    pipeline.named_steps['imputer'].transform(df)
)
sil_score = silhouette_score(processed_data, cluster_labels)

print(f"Pipeline operational check passed!")
print(f"Evaluation Silhouette Score: {sil_score:.4f}")
print(f"Identified Customer Group Distribution:\n{pd.Series(cluster_labels).value_counts().to_string()}")
Lab Overview

Objectives & Tasks

Review the tasks below and follow the interactive instructions to complete this module.

Knowledge Check

Ready to test your understanding of Milestone 1: Customer Segmentation Clustering?

Back