GARETH GRANTTECHNOLOGY · DATA · INNOVATION
Explore

32 / Predictive analytics

Customer segmentation with clustering

Clustering groups observations according to similarities in chosen features, without known outcome labels. It can organise exploratory customer or operational analysis, but the resulting groups are a modelling choice to validate, not proof that the business has discovered fixed natural customer types.

AdvancedFitted example + Python

The business question

Are there useful groups of customers or jobs with similar observed behaviour?

  • Explore purchase-frequency and spending patterns before designing service packages.
  • Group jobs by observed complexity, duration or resource use for process investigation.
  • Create candidate segments whose stability and business usefulness can be tested.

How the method works

K-means starts with a chosen number of clusters and iteratively assigns observations to their nearest centre, then updates each centre to its assigned observations’ mean. The objective is to reduce the sum of squared distances within clusters. Because different initial centres can give different results, repeated initialisations and a fixed random seed make an example more reproducible.

Distance is defined by the features and their scales. Annual rand spend can dominate purchase count unless the analysis deliberately rescales them. Standardising each input gives each feature comparable variation in this example, but that is a substantive weighting decision rather than an automatically correct business choice. Features also need consistent observation windows and sensible handling of missing or extreme values.

Internal measures such as silhouette describe separation under the selected distance definition; they do not measure profit or whether a campaign will work. Evaluate stability across resamples and later periods, interpret centres in original units and check whether the groups lead to a useful, deliverable action. For future assignment, fit preprocessing on the appropriate training data and apply it consistently to new observations.

The calculation

K-means minimises Σ_k Σ_(i in cluster k) ||z_i−centre_k||², where z_i contains the chosen scaled features
Read the symbols
SymbolMeaning
kA cluster label; the number of clusters is chosen by the analyst.
z_iFeature vector for observation i after the stated preprocessing.
centre_kMean feature vector of the observations assigned to cluster k.
silhouetteA within-versus-between distance summary; higher values indicate separation under that definition.

A worked business example

ILLUSTRATIVE SCENARIO

Constructed six-customer teaching data use purchases during a fixed period and total spend in that same period.

Inputs

  • Customer pairs (purchases, rand spend): (1,100), (2,120), (2,80), (8,900), (9,1000), (10,1100).
  • Standardise both columns using their observed means and scales.
  • Fit K-means with two clusters, random_state=42 and n_init=10.

Work through the numbers

  1. Standardisation makes purchase-count and spend variation comparable for the distance calculation.
  2. The fitted groups each contain three customers.
  3. Back-transformed centres are approximately (1.67 purchases, R100) and (9 purchases, R1,000).
  4. The silhouette score on this constructed sample is approximately 0.8788.
The method separates low-activity and high-activity examples under the specified feature scaling.

The strong separation was deliberately built into the tiny teaching dataset. It is not evidence that two segments are optimal in a real customer base or that a new loyalty offer would improve retention.

Run and inspect the fitted example

This method needs a richer model-fitting workflow. The complete runnable Python example below shows the fit and relevant checks; use the downloadable notebook to change the data and rerun it.

Download the worked notebook

Apply it at work

  1. State the action a segmentation could enable and select features measured over consistent customer windows.
  2. Inspect distributions and outliers, then choose and document feature transformations and weighting.
  3. Fit several defensible cluster counts and initialisations; inspect centres, separation and stability.
  4. Validate on later customers or periods and test a segment-specific action against an appropriate comparison.

Check these assumptions

  • The selected features and distance definition describe similarity relevant to the intended business action.
  • The dataset covers the customer or job population adequately and is not mainly a sample-selection artefact.
  • K-means’ compact, roughly spherical grouping preference is a useful approximation for the feature space.
  • Scaling, transformations and future assignment rules are consistently applied.

Common mistakes and how to avoid them

  • Naming clusters loyal, valuable or risky without validating those outcomes invents meaning beyond the features.
  • Choosing the largest silhouette or the prettiest plot alone ignores feasibility, stability and business relevance.
  • A segment may simply reflect measurement duration, currency units or missing-data practices rather than useful customer behaviour.

How this can help the business

  • A service team can investigate different workloads and needs before designing distinct support processes.
  • Marketing can use candidate groups to organise controlled tests while measuring incremental contribution rather than assuming segmentation itself creates value.
A decision rule to adapt

Use a segmentation when it is interpretable, stable enough for its purpose and linked to an action that performs better in a measured pilot than the existing approach.

When to use another approach

Consider explicit rule-based RFM segments, mixture models for overlapping groups, density-based methods for irregular clusters, or supervised models when a labelled target is available.

Reproduce the worked example in Python

The code is self-contained for this example. Dependencies and run instructions are included with the downloadable notebook.

Show executable code and recorded output
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
customers = np.array([[1,100],[2,120],[2,80],[8,900],[9,1000],[10,1100]])
scaler = StandardScaler()
scaled = scaler.fit_transform(customers)
model = KMeans(n_clusters=2, random_state=42, n_init=10).fit(scaled)
centres = scaler.inverse_transform(model.cluster_centers_)
print("Cluster sizes:", np.bincount(model.labels_).tolist())
print("Centres: purchases, rand spend:", np.round(centres,2).tolist())
print("Silhouette:", round(silhouette_score(scaled,model.labels_),4))

Recorded output

Cluster sizes: [3, 3]
Centres: purchases, rand spend: [[1.67, 100.0], [9.0, 1000.0]]
Silhouette: 0.8788
Download all worked examples

Sources and further reading

Concepts are linked to primary teaching or technical sources. The business examples are illustrative applications, not reported client results.