Clustering for BI
Clustering groups similar records (unsupervised) to find customer segments, detect patterns and prepare features for BI reports and analytics.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Clustering is used by engineers to group customers, transactions or products without labelled classes. In BI, clustering helps create customer segments, find anomalies, reduce data for dashboards and prepare features for classification or association-rule mining.
Key ideas
K-means (definition and objective): K-means partitions n numeric data points into K clusters C1..CK by choosing K centroids µ1..µK to minimize the within-cluster sum of squared distances (SSE). Assumptions: numeric attributes, Euclidean distance, K given, and clusters are roughly spherical/equal-variance; K-means is sensitive to outliers.
- Exact objective (law): Given points x1..xn in ℝ^m and partition into clusters S1..SK, K-means minimizes:
- sum_{k=1..K} sum_{x in Sk} ||x - µ_k||^2, where µ_k is the mean (centroid) of Sk.
- The cluster centroid µ_k that minimizes the squared-error for a fixed cluster is the arithmetic mean of points in the cluster (derivation below).
- Exact objective (law): Given points x1..xn in ℝ^m and partition into clusters S1..SK, K-means minimizes:
Derivation (centroid minimizes sum of squared distances): For cluster S, minimize f(µ)=∑{x in S} ||x - µ||^2 with respect to µ. Differentiate component-wise and set gradient 0: ∂f/∂µ_j = -2 ∑{x in S} (x_j - µ_j) = 0 ⇒ µ_j = (1/|S|) ∑_{x in S} x_j for each coordinate. Thus µ = arithmetic mean.
K-medoids (definition): Similar to K-means but each cluster center is an actual data point (medoid). More robust to outliers and can use arbitrary distance functions.
Hierarchical clustering (definition): Builds a tree (dendrogram) of clusters. Two approaches:
- Agglomerative (bottom-up): start with each point as a cluster and iteratively merge closest clusters until one remains.
- Divisive (top-down): start with all points and split clusters.
- Linkage criteria: single-link (min distance), complete-link (max distance), average-link (average pairwise distance). Assumes a distance matrix can be computed.
DBSCAN (definition): Density-Based Spatial Clustering of Applications with Noise. Parameters: eps (neighbourhood radius) and minPts (minimum points to form a dense region). Definitions:
- Core point: point p with |N_eps(p)| >= minPts (including p).
- Border point: not core, but within eps of a core point.
- Noise: neither core nor border.
- Forms clusters by connecting density-reachable points.
- Advantages: finds arbitrary-shaped clusters, handles noise; assumption: clusters are dense regions separated by lower-density regions. Formal notions: a point q is directly density-reachable from a core point p if q ∈ N_eps(p); a point q is density-reachable from p if there is a chain p = p0, p1, …, pn = q where each pi+1 is directly density-reachable from pi (via core points); two points are density-connected if there exists a point o from which both are density-reachable. Border points are not used to expand clusters. Tip: choose eps via the k-distance plot and use minPts ≥ dimensionality + 1 (e.g., 4 in 2D) as a rule of thumb.
Cluster evaluation:
- SSE (sum of squared errors): internal measure used by K-means objective.
- Silhouette score for a point i: s(i) = (b - a) / max(a, b), where a = avg distance to points in same cluster; b = minimum avg distance to points in another cluster. s(i) ∈ [-1,1].
- External measures (if labels exist): purity, adjusted Rand index.
Practical points:
- Always scale/normalize numeric features before distance-based clustering (e.g., standardize to zero mean, unit variance) unless units are comparable.
- Choose K using the elbow method, silhouette, or domain knowledge. Initialize centroids with k-means++ and run multiple random restarts to reduce poor local minima and variance in results.
- For categorical data use algorithms like k-modes or convert categories to numeric embeddings.
Diagrams to draw for university answers:
- For K-means: draw a 2D scatterplot of points, mark initial centroids with large crosses, draw arrows from points to centroids showing assignment, show new centroids and repeat. Label axes x1 and x2, label centroids µ1, µ2, etc.
- For hierarchical: draw points on a line or plane, compute pairwise distances, then draw a dendrogram with vertical axis showing linkage distance. Label cluster merges with the distance values.
Formulas
d_euclid(x,y) = sqrt( sum_{j=1..m} (x_j - y_j)^2 ) — Euclidean distance; x_j, y_j in units of feature j; applies to numeric features.
d_manhattan(x,y) = sum_{j=1..m} |x_j - y_j| — Manhattan (L1) distance.
cosine similarity s(x,y) = (x · y) / (||x|| ||y||); a common cosine distance is d_cos(x,y) = 1 - s(x,y) (note: d_cos is not a metric).
SSE = sum_{k=1..K} sum_{x in C_k} ||x - µ_k||^2 — sum of squared errors; µ_k is centroid of cluster C_k; units: (feature units)^2.
Silhouette s(i) = (b(i) - a(i)) / max(a(i), b(i)) — a(i) = average distance of i to other points in its cluster; b(i) = minimum of average distances to points in other clusters; unitless, range [-1,1].
K-means update (centroid) µ_k = (1/|C_k|) sum_{x in C_k} x — arithmetic mean; applies when objective is SSE and distance is Euclidean.
DBSCAN core condition: |N_eps(p)| >= minPts — N_eps(p) = {q | d(p,q) <= eps}.
Note: If all features share the same physical unit, Euclidean distances carry that unit and SSE carries its square. After standardization (e.g., z-scores) distances become unitless; with heterogeneous units you must scale first or distances are not meaningful.
Worked examples
K-means example (numerical trace). Data (units: arbitrary "units"): Points: A(1,1), B(1.5,2), C(3,4), D(5,7), E(3.5,5). Let K=2. Initial centroids: µ1=A(1,1), µ2=E(3.5,5). Step 1 — assign points by Euclidean distance:
- Dist(A,µ1)=0; Dist(A,µ2)=sqrt((1-3.5)^2+(1-5)^2)=4.72 ⇒ A→C1.
- Dist(B,µ1)=1.118; Dist(B,µ2)=3.606 ⇒ B→C1.
- Dist(C,µ1)=3.606; Dist(C,µ2)=1.118 ⇒ C→C2.
- Dist(D,µ1)=7.211; Dist(D,µ2)=2.5 ⇒ D→C2.
- Dist(E,µ1)=4.72; Dist(E,µ2)=0 ⇒ E→C2. Clusters: C1={A,B}, C2={C,D,E}. Step 2 — recompute centroids:
- µ1 = mean(A,B) = ((1+1.5)/2, (1+2)/2) = (1.25, 1.5).
- µ2 = mean(C,D,E) = ((3+5+3.5)/3, (4+7+5)/3) = (3.8333, 5.3333). Step 3 — reassign (compute one representative check): distances keep A,B to C1 and C,D,E to C2, so assignment unchanged → algorithm converged. Compute SSE (final):
- For C1: squared dist A→µ1 = 0.3125 (units^2), B→µ1 = 0.3125 → sum 0.625 units^2.
- For C2: squared dist C→µ2 ≈ 2.4722, D→µ2 ≈ 4.1389, E→µ2 ≈ 0.2222 → sum ≈ 6.8333 units^2.
- Total SSE ≈ 7.4583 units^2. Final clusters: C1={A,B}, C2={C,D,E}. Final centroids as above. Bold final answer: Clusters: {A,B} and {C,D,E}; SSE ≈ 7.4583 units^2.
Agglomerative hierarchical clustering (single-link) example (trace). Data (1D, units: units): P1=1, P2=2, P3=5, P4=8. Step 1 — pairwise distances: d(1,2)=1, d(1,5)=4, d(1,8)=7, d(2,5)=3, d(2,8)=6, d(5,8)=3. Step 2 — smallest distance 1: merge P1 and P2 into cluster A at height 1. Step 3 — compute distances from A to others using single-link (min distance): d(A,P3)=min(d(1,5),d(2,5))=min(4,3)=3; d(A,P4)=min(7,6)=6. Step 4 — next smallest distance is 3 (ties: A–P3 and P3–P4). Suppose we merge P3 and P4? Actually P3–P4 distance is 3 (d(5,8)=3). If we merge P3 and P4 into cluster B at height 3, final merge A and B at height min distance between clusters = min(d(A,P3)=3,d(A,P4)=6)=3. Dendrogram heights: first merge at 1, second merges at 3, final join at 3. Diagram to draw: vertical axis distance 0..8, leaves P1..P4; join P1–P2 at height 1, P3–P4 at height 3, then join those two clusters at height 3. Final answer: dendrogram with merges at heights 1 and 3 (single-link). This shows how hierarchical clustering groups by increasing linkage distance.
Common mistakes
- Using SSE alone to choose K without visualising elbow or checking silhouette — SSE always decreases with larger K.
- Applying K-means to categorical data without converting features (use k-modes or categorical embedding).
- Ignoring random initialisation in K-means — failing to run multiple restarts and compare SSE.
- Miscomputing centroid: forgetting to divide by cluster size or confusing sum of coordinates with mean.
- For hierarchical clustering, forgetting to update inter-cluster distances correctly per linkage type.
For your exam
Types of questions you may get:
- Definitions and short notes: define clustering, K-means, DBSCAN, centroid vs medoid.
- Derivations: show why centroid = mean minimizes SSE (give derivative step); derive update rules for K-means iteration.
- Numericals/algorithm traces: run K-means for small 2D points for 1–3 iterations or produce a small hierarchical clustering trace and draw dendrogram.
- Diagrams: draw K-means assignments and centroid movements or a dendrogram annotated with linkage heights.
- Programs/pseudocode: write K-means pseudocode or sketch DBSCAN steps and cluster labelling.
What a full-marks answer includes:
- Clear definitions with bolded keywords, assumptions (e.g., numeric features, distance type), step-by-step derivation where required, correct formulas with symbol explanations, a correctly labelled diagram if asked, and a final concise conclusion (e.g., final clusters or objective value). For numericals, show all distance calculations, intermediate centroids and final SSE or dendrogram heights.
Quick check
- What is the K-means objective function?
- Why should you scale features before K-means?
- In DBSCAN, what makes a point a core point?
Answers: 1) SSE = sum_{k=1..K} sum_{x in C_k} ||x - µ_k||^2 (minimize this). 2) Because distances combine features — features with larger numeric ranges dominate the distance and distort clusters (so standardize to comparable scale). 3) A point p is a core point if |N_eps(p)| >= minPts, i.e., it has at least minPts points within radius eps.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?