Skip to main content
Big Data Analytics

Machine Learning Landscape & Unsupervised Clustering

Published: 2026-08-01
Level: postgraduate
Audience: Postgraduate students in Big Data Analytics

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • Machine learning fundamentals, taxonomy of ML paradigms, and the end-to-end ML pipeline — covered in Lecture 12
  • Model evaluation metrics (confusion matrix and regression metrics) — covered in Lecture 12
  • Apache Spark DataFrame API, Catalyst optimizer, and PySpark operations — covered in Lecture 10
  • Evolution to Apache Spark and the Spark component stack — covered in Lecture 3

13.1 Machine Learning Landscape & Project Workflow

Machine learning models operating on big data need a structured lifecycle and clear operational definitions. In industry projects, data scientists and engineers build end-to-end pipelines that turn raw business tasks into evaluated predictive models.

If a factory can sort tomatoes by size and color without writing every rule by hand, what must the computer have learned — and how do we prove the sorting got better over time?

13.1.1 Core Definitions & Learning Paradigms

A machine learning algorithm (a program that improves from data rather than from hand-written rules) follows Tom Mitchell's criterion: a computer program is said to learn from experience \(E\) with respect to some class of tasks \(T\) and performance measure \(P\), if its performance at tasks in \(T\), as measured by \(P\), improves with experience \(E\).

Tomato quality classification (Mitchell \(T\), \(E\), \(P\))

Consider classifying harvested tomatoes into high quality versus bad quality.

  • Task (\(T\)): Classify each tomato as high quality or bad quality.
  • Experience (\(E\)): Historical samples of tomatoes with recorded physical measurements (size, color intensity, mass, firmness) and known quality labels.
  • Performance Measure (\(P\)): Accuracy, precision, or the percentage of correct quality classifications on held-out tomatoes.

Sense-check: if \(P\) rises as more labeled tomatoes are seen, Mitchell's definition says the program is learning.

Machine learning differs from traditional software engineering in the direction of the pipeline:

Approach What you feed the computer What it produces
Traditional programming Rules + data Answers
Machine learning Data + answers (outcomes) Rules / predictive model

Think of traditional code as a recipe card: you write every step. Machine learning is closer to showing a cook many finished dishes and letting them infer the recipe. The analogy breaks when the “dishes” are noisy or mislabeled — the inferred recipe then encodes the noise.

The broader landscape spans three major paradigms:

  1. Supervised Learning: Algorithms learn from labeled datasets containing explicit input–output pairs.
  • Example: Predicting whether a person is labeled “fat” or “thin” from millions of past samples with weight \(x \in \mathbb{R}\) and height \(y \in \mathbb{R}\) (and a binary outcome label).
  • Supervised learning splits into two sub-problems:
  • Classification: Predict a target \(y\) from a small, finite set of discrete class labels (e.g., movie ratings as categories \(\{1,2,3,4,5\}\), or low / medium / high popularity).
  • Regression: Predict a continuous target \(y \in \mathbb{R}\) from an effectively infinite continuous set (e.g., exact scores such as \(3.23\), \(5.27\), or \(9.98\)).
  1. Unsupervised Learning: Algorithms operate on unlabeled datasets where ground-truth labels are absent. The goal is to discover structural patterns or groupings in the data space.
  • Example: Segmenting the population of India on demographic features. The algorithm forms clusters by feature similarity.
  • Key distinction: The algorithm may find that there are \(k\) groups, but it cannot name them. A domain expert must interpret clusters as super senior citizens, senior citizens, working population, teenagers, or toddlers.
  1. Reinforcement Learning: Algorithms learn without a static labeled batch. An agent interacts with an environment by trial and error and receives numeric rewards or penalties.
  • Analogy (professor): Learning to ride a bicycle. Falling is a heavy penalty; moving forward a few inches is a reward. Over time the agent finds an action sequence that maximizes cumulative reward.
  • Where the analogy breaks: bicycle balance is continuous and physical; digital RL often uses discrete actions and designer-chosen reward scales.

Scope: Mitchell's \(T\)/\(E\)/\(P\) framing assumes you can name the task and measure performance numerically. It does not by itself choose the algorithm family (supervised vs unsupervised vs RL). Mixing paradigms — e.g., treating cluster IDs as if they were ground-truth class names — breaks downstream evaluation.

13.1.2 Artificial Intelligence vs. Machine Learning vs. Deep Learning

Artificial Intelligence (AI) is the overarching domain: any system that shows intelligent behavior. Machine Learning (ML) is a subset of AI that uses statistical algorithms to learn patterns from data. Deep Learning (DL) is a further subset of ML that uses multi-layered artificial neural networks.

Visual intuition: picture three nested circles. The outer circle is AI. Inside it sits ML. Inside ML sits DL. Traditional algorithms such as Decision Trees, Support Vector Machines, and K-Means live in the ML ring but outside the DL ring.

  • Non-human-brain approach (traditional ML): Distinct mathematical algorithms tailored to engineered feature sets.
  • Human-brain approach (deep learning): Layers of artificial neurons that learn hierarchical feature representations automatically.
  • Explainability dilemma: Business stakeholders often demand why a prediction was made. Traditional ML models usually offer clearer mathematical interpretability. Deep learning models often behave as opaque black boxes: strong predictive performance, weaker pathway explanation.

Pitfalls

  • Calling every intelligent product “deep learning” when it may be classical ML.
  • Assuming higher accuracy always wins in enterprise settings where auditability matters more than a few points of accuracy.
  • Treating AI, ML, and DL as synonyms on an exam or in a client proposal.

AI ⊃ ML ⊃ DL. Prefer classical ML when stakeholders require transparent decision paths; consider DL when raw representation learning outweighs explainability cost.

13.1.3 End-to-End Machine Learning Project Phases

Every real-world machine learning initiative follows five core operational phases:

  1. Data Gathering: Collect raw feeds from distributed logs, databases, real-time streams, or third-party APIs.
  2. Data Cleaning: Handle missing values, filter noise, remove corrupt records, and normalize formats.
  3. Feature Engineering: Extract domain attributes, transform raw variables, and build feature vectors.
  4. Model Execution: Train candidate algorithms on the processed data.
  5. Model Evaluation: Quantify performance with objective metrics before deployment.

Exam note: Establishing model evaluation criteria before running algorithms is a critical project requirement. Models must never be judged on subjective developer impressions or mood swings. Clear numeric metrics up front let you verify whether an updated model is objectively better or worse.

Real-world & domain connection: In freelancing proposals and enterprise delivery, inexperienced teams often code models while omitting the evaluation framework. A proposal without predefined metrics is technically incomplete. The same discipline appears in industrial tomato sorting: accuracy and false-reject rate must be agreed before comparing sorter versions.

Assumption: The five phases assume access to representative data and a measurable business objective. If labels are unavailable, supervised evaluation metrics do not apply and the project must shift to unsupervised validation (e.g., clusterability tests) or RL reward design.

13.1.4 Student Questions and Answers

Q: How does reinforcement learning operate without labeled data, and can reward and penalty outcomes be customized for specific business applications?

A: Reinforcement learning does not rely on static historical labels. An agent takes trial-and-error actions in an environment; the environment returns dynamic rewards or penalties. The designer defines the reward and penalty structure. Penalties can lie in continuous ranges such as \([-1, 0]\); rewards can use scales such as \([0, 1]\), \([0, 5]\), or \([0, 100]\). Touching fire can map to a maximum negative penalty. In content systems, showing a trending World Cup article yields a reward if the user clicks and reads it; explicit deletion from a news feed yields a penalty, so the engine refines future recommendations.

Mitchell's \(T\)/\(E\)/\(P\), the three learning paradigms, and the five project phases form the map for the rest of this lecture — which next asks when unlabeled data is even worth clustering.

13.2 Clustering Fundamentals & Data Clusterability (Hopkins Statistic)

Any clustering algorithm will draw boundaries on pure noise if you ask it to. How do you know the data has real groups before you burn compute on K-Means?

Clustering (grouping similar points without labels) is an unsupervised technique that partitions observations by pairwise feature similarity so that intra-cluster similarity is high and inter-cluster similarity is low. Reference texts state the same objective: maximize inter-cluster distance and minimize intra-cluster distance.

13.2.1 Spatial Visualization & Feature Dimensions

Plotting weight against height is like placing people on a gym floor by two tape measures. Add age and you need a 3D room. With dozens of features you can no longer “see” the room — only distance formulas can.

Data with two features can be drawn on a 2D plane (e.g., weight on the horizontal axis, height on the vertical axis). A third feature such as age needs a 3D view. With four, five, or hundreds of dimensions, visual inspection fails. Distance geometry still works in any \(d\)-dimensional space \(\mathbb{R}^d\): each observation is a vector \(\mathbf{x} = (x_1, \dots, x_d)\).

Univariate data has a single scalar feature per observation (e.g., only heights across a region). Clustering still applies on the real line using absolute difference as distance.

Scope: Visual “eyeball clustering” is limited to \(d \le 3\). High-\(d\) projects must rely on numeric tendency tests and algorithm diagnostics, not scatter plots alone.

13.2.2 Partitioning vs. Hierarchical Clustering

Clustering methods fall into two structural paradigms (also reflected in textbook taxonomies of partitional vs hierarchical methods):

Paradigm Structure Membership Typical use
Partitioning Flat, disjoint subsets Each point in exactly one cluster Fixed \(k\) customer segments
Hierarchical Nested tree at many granularities Points belong to nested parent clusters Taxonomies, dendrogram cuts

Consider classifying living organisms on Earth:

  • Partitioning: Strict buckets — dogs in cluster 1, cats in 2, humans in 3, birds in 4, insects in 5, microbes in 6.
  • Hierarchical: Dogs and cats merge into an “Animals” super-cluster; birds and insects into “Flying Organisms”; an extraterrestrial viewer might treat all Earth life as one top-level cluster.

When to pick which: choose partitioning when you need a fixed number of non-overlapping segments; choose hierarchical when you need multi-resolution structure or do not want to commit to \(k\) up front.

13.2.3 Data Clusterability & The Hopkins Statistic

Garbage in, garbage out: If you feed uniform noise into a clustering model, the formulas still emit cluster boundaries. Without a pre-check, those boundaries become false business conclusions.

Before running any clustering algorithm, evaluate whether the dataset has true underlying clusters or is only uniformly distributed random noise.

The Hopkins Statistic \(H\) is a statistical test of clustering tendency (whether data is cluster-worthy).

Mathematical Formulation of Hopkins Statistic

Let the original dataset occupy a defined data space (e.g., feature values in \([0, 200]\)). Choose a sample size \(m\) with \(m \ll n\) (much smaller than the full dataset size \(n\)).

  1. Sample \(m\) real points uniformly at random from the dataset:

\[ U = \{u_1, u_2, \dots, u_m\} \] where \(u_i\) is the \(i\)-th sampled real point.

  1. Generate \(m\) synthetic points uniformly at random in the same data space:

\[ V = \{v_1, v_2, \dots, v_m\} \] where \(v_i\) is the \(i\)-th synthetic point.

  1. For each synthetic \(v_i \in V\), find its nearest neighbor among the real data and record

\[ V_{d,i} = \mathrm{dist}\bigl(v_i, \mathrm{nearest}(v_i)\bigr). \] Sum these distances: \[ \sum_{i=1}^{m} V_{d,i}. \]

  1. For each sampled real \(u_i \in U\), find its nearest other real neighbor (exclude itself) and record

\[ U_{d,i} = \mathrm{dist}\bigl(u_i, \mathrm{nearest}(u_i)\bigr). \] Sum these distances: \[ \sum_{i=1}^{m} U_{d,i}. \]

  1. Form the Hopkins ratio:

\[ H = \frac{\sum_{i=1}^{m} V_{d,i}}{\sum_{i=1}^{m} V_{d,i} + \sum_{i=1}^{m} U_{d,i}}. \]

In words: \(H\) is the total nearest-neighbor distance of synthetic points divided by that total plus the total nearest-neighbor distance of sampled real points. Because the numerator is part of the denominator, \(H \in [0, 1]\).

Interpretation Thresholds

  • \(H \approx 0.5\) (unclusterable / uniform): Real and synthetic nearest-neighbor distance sums are comparable (\(\sum V_d \approx \sum U_d\)). Example: \(\frac{100}{100+100} = 0.5\). Do not treat the data as cluster-worthy.
  • \(H > 0.5\) (cluster-worthy): Real points sit in tight groups, so \(\sum U_d\) is small while random synthetic points land far from real mass, making \(\sum V_d\) large. Example: \(\sum V_d = 100\), \(\sum U_d = 5\) gives

\[ H = \frac{100}{100+5} \approx 0.952. \] Values significantly above \(0.5\) support clustering.

  • \(H < 0.5\) (regular / grid): Points are more regularly spaced than uniform random noise (lattice-like structure).

Numeric Hopkins check

Suppose \(m = 4\), \(\sum_{i=1}^{4} V_{d,i} = 40\), and \(\sum_{i=1}^{4} U_{d,i} = 10\).

\[ H = \frac{40}{40+10} = \frac{40}{50} = 0.8. \]

Answer: \(H = 0.8 > 0.5\) — the sample is cluster-worthy. Sense-check: synthetic points are on average four times farther from real data than real points are from each other, which matches a clustered geometry.

Visual intuition: Imagine a scatter plot with two tight blobs. Sampled real points almost always find a neighbor inside their blob (short \(U_d\)). Uniform synthetic darts often land in empty space and must travel far to the nearest real point (long \(V_d\)). The ratio \(H\) then rises toward 1. On a uniform fog of points, both dart types travel similar distances and \(H\) hugs \(0.5\).

Assumption: Hopkins compares real structure against a uniform null in the same bounding box. It can mislead if the sampling region is wrong, features are unscaled, or \(m\) is too small. It tests tendency, not the “right” value of \(k\).

Pitfalls

  • Running K-Means first and declaring success because “clusters appeared” — algorithms always return partitions.
  • Memorizing only “high \(H\) is good” without the \(\le 0.5\) stop rule.
  • Confusing \(H < 0.5\) (regular grid) with \(H \approx 0.5\) (uniform noise); both are reasons to pause before naive partitioning.

Exam note: If \(H \le 0.5\), do not apply clustering algorithms. Memorize \[ H = \frac{\sum V_d}{\sum V_d + \sum U_d} \] and the threshold interpretation.

Real-world & domain connection: Marketing teams segmenting India’s demographics, or e-commerce teams clustering clickstreams, must confirm clusterability first. Otherwise “segments” are artifacts and campaign targeting wastes budget.

Clusterability is a gate: pass Hopkins, then choose partitioning (next: K-Means) or hierarchical methods.

13.3 Partitioning Clustering: K-Means Algorithm & Variants

Given twelve numbers on a line, how do you repeatedly “pull” three center marks until every point stops switching teams?

K-Means is a centroid-based partitioning algorithm: it divides a dataset into \(k\) predefined, non-overlapping clusters by alternating assignment to the nearest center and recomputing each center as a mean.

13.3.1 Distance Metrics: Euclidean vs. Manhattan

Evaluating proximity needs a distance between vectors \(\mathbf{x}_1 = (x_{11}, x_{12})\) and \(\mathbf{x}_2 = (x_{21}, x_{22})\).

  1. Euclidean distance (straight-line / “as the crow flies”):

\[ d_{\mathrm{Euclidean}}(\mathbf{x}_1, \mathbf{x}_2) = \sqrt{(x_{11}-x_{21})^2 + (x_{12}-x_{22})^2}. \] For scalar 1D points \(x_1, x_2 \in \mathbb{R}\) this reduces to \(|x_1 - x_2|\).

  1. Manhattan distance (city-block / rectilinear):

\[ d_{\mathrm{Manhattan}}(\mathbf{x}_1, \mathbf{x}_2) = |x_{11}-x_{21}| + |x_{12}-x_{22}|. \]

Euclidean is the hypotenuse of a right triangle; Manhattan is the sum of the two legs. On a city grid you cannot cut diagonally through buildings — Manhattan matches that path. The analogy breaks in feature spaces where diagonal movement is meaningful (then Euclidean is natural).

Distance spot-check

Take \(\mathbf{x}_1 = (1, 2)\) and \(\mathbf{x}_2 = (4, 6)\).

\[ \begin{aligned} d_{\mathrm{Euclidean}} &= \sqrt{(1-4)^2+(2-6)^2} = \sqrt{9+16} = 5, \\ d_{\mathrm{Manhattan}} &= |1-4| + |2-6| = 3 + 4 = 7. \end{aligned} \]

Sense-check: the straight path (\(5\)) is shorter than the axis-aligned path (\(7\)), as required by geometry.

13.3.2 Step-by-Step K-Means Algorithm Workflow

Use the procedural spine for this algorithm.

Purpose: Partition \(n\) points into \(k\) non-overlapping groups that minimize within-cluster squared distance to centroids (local optimum under random starts).

Inputs & outputs

  • Inputs: Dataset \(X = \{x_1, \dots, x_n\}\), cluster count \(k\), distance function \(d\) (often Euclidean), initial seeds.
  • Outputs: Cluster sets \(S_1, \dots, S_k\) and centroids \(c_1, \dots, c_k\).

Steps

  1. Initialization: Choose \(k\) seed centroids \(C = \{c_1, \dots, c_k\}\).
  2. Assignment: Put each point in the closest centroid’s set:

\[ S_j = \bigl\{ x_i : d(x_i, c_j) \le d(x_i, c_l)\ \forall\, l \in \{1,\dots,k\} \bigr\}. \]

  1. Update: Replace each centroid by the mean of its members:

\[ c_j = \frac{1}{|S_j|} \sum_{x \in S_j} x, \] where \(|S_j|\) is the number of points in cluster \(j\).

  1. Convergence check: Repeat assignment and update until no centroid moves and no point changes cluster.

Complexity & cost: with \(n\) points, \(k\) clusters, \(I\) iterations, and dimension \(d\), time is on the order of \(O(n \cdot k \cdot I \cdot d)\) — linear in \(n\) for fixed \(k, I, d\). Space is about \(O(n \cdot d)\). Cost blows up when \(k\) or \(I\) is large, or when poor seeds force many wasted iterations.

When to use / alternatives: Prefer K-Means for large \(n\), roughly spherical clusters, and a known \(k\). Prefer hierarchical methods when you need a dendrogram or non-flat structure; prefer K-Medoids when centers must be real observations or outliers dominate the mean.

13.3.3 Comprehensive Worked Computation: 1D Dataset Walkthrough

Dataset and configuration

\[ X = \{1, 2, 4, 5, 10, 11, 13, 14, 15, 19, 20, 22\}, \qquad k = 3. \]

Use 1D absolute distance \(d(x, c_j) = |x - c_j|\).

Trial 1: Seeds \(c_1 = 2\), \(c_2 = 4\), \(c_3 = 13\)

Iteration 1 — Assignment

Point \(x\) \(\|x-2\|\) \(\|x-4\|\) \(\|x-13\|\) Assigned
1 1 3 12 \(C_1\)
2 0 2 11 \(C_1\)
4 2 0 9 \(C_2\)
5 3 1 8 \(C_2\)
10 8 6 3 \(C_3\)
11 9 7 2 \(C_3\)
13 11 9 0 \(C_3\)
14 12 10 1 \(C_3\)
15 13 11 2 \(C_3\)
19 17 15 6 \(C_3\)
20 18 16 7 \(C_3\)
22 20 18 9 \(C_3\)

Clusters: \[ S_1 = \{1,2\},\quad S_2 = \{4,5\},\quad S_3 = \{10,11,13,14,15,19,20,22\}. \]

Iteration 1 — Centroid update

\[ \begin{aligned} c_1 &= \frac{1+2}{2} = 1.5, \\ c_2 &= \frac{4+5}{2} = 4.5, \\ c_3 &= \frac{10+11+13+14+15+19+20+22}{8} = \frac{104}{8} = 13.0. \end{aligned} \]

Notation note: A verbal walkthrough sometimes cited a later mid-run center near \(16.3\). That value is not the mean of this Trial-1 \(S_3\). Algebraically, \(\frac{104}{8} = 13\). The figure \(16.2 \approx 16.3\) appears correctly as a Trial-2 centroid below.

Iteration 2 — Reassignment with \(c = (1.5, 4.5, 13.0)\)

Boundary checks:

  • Point \(10\): \(|10-4.5|=5.5\), \(|10-13|=3\) → stays in \(C_3\).
  • Point \(11\): \(|11-4.5|=6.5\), \(|11-13|=2\) → stays in \(C_3\).
  • Points \(1,2\) stay in \(C_1\); \(4,5\) stay in \(C_2\).

No point moves. Trial 1 has already converged to the local solution \[ S_1=\{1,2\},\; S_2=\{4,5\},\; S_3=\{10,11,13,14,15,19,20,22\} \] with centroids \(1.5\), \(4.5\), \(13.0\).

Sense-check: two left seeds placed close together produced two tiny left clusters and one oversized right cluster — a classic poor-seed local minimum.

Trial 2: Seeds \(c_1 = 6\), \(c_2 = 19\), \(c_3 = 22\)

Spreading seeds across the domain reaches a balanced partition in four iterations.

Iteration 1 assignment (summary): \[ S_1=\{1,2,4,5,10,11\},\; S_2=\{13,14,15,19,20\},\; S_3=\{22\}. \]

Iteration 1 update: \[ \begin{aligned} c_1 &= \frac{33}{6} = 5.5, \\ c_2 &= \frac{13+14+15+19+20}{5} = \frac{81}{5} = 16.2 \approx 16.3, \\ c_3 &= 22. \end{aligned} \]

Iteration 2: With centers \(5.5\), \(16.2\), \(22\), \[ S_1=\{1,2,4,5,10\},\; S_2=\{11,13,14,15,19\},\; S_3=\{20,22\} \] and updated means \(c_1=4.4\), \(c_2=14.4\), \(c_3=21\).

Iteration 3:

  • \(10\) moves to \(C_2\) because \(|10-14.4|=4.4 < |10-4.4|=5.6\).
  • \(19\) moves to \(C_3\) because \(|19-21|=2 < |19-14.4|=4.6\).

\[ S_1=\{1,2,4,5\},\; S_2=\{10,11,13,14,15\},\; S_3=\{19,20,22\} \] with \[ c_1=3,\quad c_2=12.6,\quad c_3=\frac{61}{3}\approx 20.33. \]

Iteration 4: Reassignment leaves every point unchanged → convergence.

Final clusters (Trial 2): \[ S_1=\{1,2,4,5\},\; S_2=\{10,11,13,14,15\},\; S_3=\{19,20,22\}. \]

These three sets are a fixed point of K-Means: each point’s nearest mean is its own cluster mean. Trial 1’s different fixed point shows why initialization matters.

Trial 3 & Sensitivity to Random Initialization

Seed sensitivity: Seeds such as \((19, 20, 21)\) dump all centers into one high-value corner. The run burns extra iterations and can stick in a weak local minimum — wasted CPU and weaker segments.

  • Trial 2 seeds \((6, 19, 22)\): Spread seeds → clean convergence in 4 iterations to the balanced partition above.
  • Trial 3 seeds \((19, 20, 21)\): Corner seeds → redundant iterations and local-minimum risk.

Real-world production pattern: commercial K-Means runs multiple random restarts (\(n_{\mathrm{init}} = 100\)). For each restart compute Sum of Squared Errors (SSE / inertia): \[ \mathrm{SSE} = \sum_{j=1}^{k} \sum_{x \in S_j} (x - c_j)^2. \] Keep the restart with the lowest SSE.

SSE comparison (1D)

Trial 1 final (\(c=(1.5,4.5,13)\)): \[ \begin{aligned} \mathrm{SSE}_1 &= (1-1.5)^2+(2-1.5)^2 \\ &\quad + (4-4.5)^2+(5-4.5)^2 \\ &\quad + \sum_{x\in S_3}(x-13)^2 \\ &= 0.25+0.25+0.25+0.25 \\ &\quad + (9+4+0+1+4+36+49+81) \\ &= 1 + 184 = 185. \end{aligned} \]

Trial 2 final (\(c=(3, 12.6, 20.333)\)): \[ \begin{aligned} \mathrm{SSE}_2 &= (1-3)^2+(2-3)^2+(4-3)^2+(5-3)^2 \\ &\quad + (10-12.6)^2+(11-12.6)^2+(13-12.6)^2+(14-12.6)^2+(15-12.6)^2 \\ &\quad + (19-20.333)^2+(20-20.333)^2+(22-20.333)^2 \\ &\approx 4+1+1+4 + 6.76+2.56+0.16+1.96+5.76 + 1.78+0.11+2.78 \\ &\approx 32.87. \end{aligned} \]

Lowest SSE wins: Trial 2 (\(\approx 32.9\) vs \(185\)). Sense-check: the balanced partition packs points much closer to their means.

Visual intuition: On a number line, centroids are movable pins. Assignment snaps each tick mark to the nearest pin; update slides each pin to the average of its ticks. Pins stop when the snap-and-slide loop no longer changes membership.

Assumption: K-Means assumes roughly convex / spherical clusters in the chosen metric, a meaningful \(k\), and comparable feature scales. Elongated, nested, or heavily skewed clusters violate the geometry; unscaled features let one axis dominate distance.

Pitfalls

  • Trusting a single random seed (Trial 1 vs Trial 2).
  • Forgetting that “converged” only means a local minimum, not the global best SSE.
  • Using the mean when a single outlier can drag the centroid far from the dense mass.

13.3.4 K-Medoids / K-Median Variant

Standard K-Means centroids (e.g., \(2.3\) or \(17.17\)) need not be actual observations. Means are also sensitive to extreme outliers.

K-Medoids / K-Median: Cluster centers (medoids) are restricted to actual dataset points. Instead of minimizing squared Euclidean distance, K-Medoids typically minimizes absolute (Manhattan / L1) dissimilarities. Seed medoids and updated centers remain true instances.

Textbook framing: a medoid is like a mean but must be a member of the data; the algorithm iteratively swaps exemplars to reduce total dissimilarity. Use medoids for graphs/non-metric spaces and when interpretability requires “this customer is the prototype.”

K-Means = assign → mean-update → repeat; always compare multiple \(n_{\mathrm{init}}\) runs by SSE. Next: hierarchical clustering builds a merge tree without committing to \(k\) first.

13.4 Hierarchical Clustering & Linkage Criteria

If you refuse to pick \(k\) up front, can you still grow a family tree of clusters and cut it later at the height you need?

Hierarchical clustering builds a tree of nested clusters without requiring \(k\) before the run. Results are typically more consistent across runs than random-seed K-Means because there is no random centroid initialization for a fixed linkage rule.

13.4.1 Agglomerative vs. Divisive Approaches

  1. Agglomerative (bottom-up): Start with every point as its own cluster (\(n\) singleton clusters). At each step merge the two closest clusters under a linkage metric. Continue until one root cluster remains.
  1. Divisive (top-down): Start with one giant root cluster containing all points. Recursively split into smaller sub-clusters until every point is isolated.

Agglomerative merging is like sorting loose photos into albums: first pair near-duplicates, then merge related albums, until one shelf holds everything. Divisive splitting is the reverse — start with the whole shelf and keep dividing. The analogy breaks when “closeness” depends on which linkage definition you use; two albums can look near under single linkage and far under complete linkage.

Approach Start state Operation End state
Agglomerative \(n\) singletons Merge closest pair 1 root
Divisive 1 root Split clusters \(n\) singletons

When to pick which: agglomerative is the common default for teaching and many libraries; divisive is conceptually useful when you start from one population and need successive splits.

13.4.2 Linkage Criteria Metrics

The distance between clusters \(A\) and \(B\) depends on the linkage criterion:

  1. Single linkage (minimum distance):

\[ d_{\mathrm{single}}(A,B) = \min \{ d(x,y) : x \in A,\ y \in B \}. \]

  1. Complete linkage (maximum distance):

\[ d_{\mathrm{complete}}(A,B) = \max \{ d(x,y) : x \in A,\ y \in B \}. \]

  1. Average linkage:

\[ d_{\mathrm{average}}(A,B) = \frac{1}{|A||B|} \sum_{x \in A} \sum_{y \in B} d(x,y). \]

  1. Centroid linkage:

\[ d_{\mathrm{centroid}}(A,B) = d(\mu_A, \mu_B), \] where \[ \mu_A = \frac{1}{|A|}\sum_{x \in A} x, \qquad \mu_B = \frac{1}{|B|}\sum_{y \in B} y. \]

Comparison:

Linkage Uses Geometry tendency Risk
Single Closest pair Can follow chains / arbitrary shapes Chaining (bridges merge early)
Complete Farthest pair Compact, similar-diameter clusters May split elongated groups
Average Mean of all cross-pairs Compromise Costlier pairwise sums
Centroid Distance of means Interpretable centers Can behave oddly with unequal sizes

When to pick which: single linkage for elongated / chained structure; complete linkage when you want tight balls; average or centroid when you want a middle ground tied to mean geometry.

13.4.3 Dendrogram Construction & Cluster Extraction

A dendrogram is the tree diagram of agglomerative merge history: the horizontal axis lists points (or leaf labels); the vertical axis is the linkage distance at which merges occurred. Drawing a horizontal cut at height \(h\) yields as many clusters as vertical branches the cut intersects.

Agglomerative single-linkage walkthrough

Points: \(X = \{1, 2, 4, 5, 10, 11, 13\}\). Distance is absolute difference.

Step 1. Pairwise minima of \(1\) appear for pairs \((1,2)\), \((4,5)\), and \((10,11)\). Merge them: \[ C_1=\{1,2\},\; C_2=\{4,5\},\; C_3=\{10,11\},\; C_4=\{13\}. \] Merge height: \(1\).

Step 2. Single-linkage distances: \[ \begin{aligned} d_{\mathrm{single}}(C_1,C_2) &= \min\{|2-4|,|2-5|,|1-4|,|1-5|\} = |2-4| = 2, \\ d_{\mathrm{single}}(C_3,C_4) &= |11-13| = 2. \end{aligned} \] Merge both pairs at height \(2\): \[ C_{12}=\{1,2,4,5\},\; C_{34}=\{10,11,13\}. \]

Step 3. Final merge: \[ d_{\mathrm{single}}(C_{12},C_{34}) = |5-10| = 5. \] One root cluster at height \(5\).

Extracting \(k\): A cut just above height \(2\) (e.g., at \(h=3\)) intersects two branches → clusters \(\{1,2,4,5\}\) and \(\{10,11,13\}\). A cut between \(1\) and \(2\) yields four clusters. Final teaching cut for two groups: \(\{1,2,4,5\}\) and \(\{10,11,13\}\).

Sense-check: nearest neighbors merged first; the gap of \(5\) between \(5\) and \(10\) is the last bridge — matching the visible gap on the number line.

Visual intuition: The dendrogram looks like a sports tournament bracket turned upward. Low horizontal bars are early “easy” merges; the tall final bar is the hardest join. Your cut height is the similarity threshold you are willing to accept.

Assumption: Linkage assumes a meaningful pairwise distance and comparable scales. Single linkage assumes chaining is acceptable; complete linkage assumes compact clusters. Hierarchical methods store richer structure but cost \(O(n^2)\) to \(O(n^3)\) time — poor for huge \(n\).

Pitfalls

  • Reading leaf order on the \(x\)-axis as a distance ranking (order is only a drawing convenience).
  • Forgetting that different linkages produce different trees on the same data.
  • Cutting the dendrogram without stating the height rule used to get \(k\).

Exam note: Be ready to define and compute single (min), complete (max), average, and centroid linkage, and to read \(k\) from a dendrogram cut.

Real-world & domain connection: News aggregators nest stories into topics and subtopics (sports → basketball → a single game). Hierarchical clustering matches that multi-resolution taxonomy better than a single flat \(k\).

Hierarchical methods trade flat speed for a full merge tree. The next section contrasts that cost with K-Means and shows how Spark MLlib scales partitioning on big data.

13.5 Comparative Analysis & Big Data Execution in Apache Spark (MLlib)

When the dataset no longer fits on one laptop, which clustering family still finishes — and which framework spreads the work across machines?

13.5.1 K-Means vs. Hierarchical Clustering Comparison

Feature / Dimension K-Means Clustering Hierarchical Clustering
Cluster count (\(k\)) Must be specified before execution Inferred visually by cutting a dendrogram
Computational complexity \(O(n \cdot k \cdot I)\) — linear growth in dataset size \(n\) (for fixed \(k, I\)) \(O(n^3)\) or \(O(n^2 \log n)\) — heavy polynomial growth
Big data suitability High; scales across distributed clusters Low; usually unviable for large enterprise \(n\)
Determinism Non-deterministic; depends on initial seeds (unless restarts + SSE selection are fixed) Fully deterministic for a given linkage criterion
Cluster geometry Assumes convex, roughly spherical clusters Single linkage can uncover arbitrary non-spherical / chained shapes

When to pick which: Use K-Means for large \(n\), known \(k\), and roughly spherical segments. Use hierarchical clustering for smaller \(n\), unknown \(k\), multi-resolution taxonomies, or when you need a dendrogram audit trail.

Textbook alignment: hierarchical methods generally produce consistent trees; K-Means is simple and efficient with linear growth in \(n\), but needs \(k\) and can depend on random starts. Neither replaces a Hopkins-style clusterability check.

Pitfalls

  • Choosing hierarchical clustering on web-scale logs because “it does not need \(k\)” — cubic cost dominates.
  • Declaring K-Means “random” without noting that lowest-SSE multi-start makes production runs reproducible in practice.

13.5.2 Horizontal Scalability: Scikit-Learn vs. Apache Spark MLlib

In architectures that meet the 3 V’s (Volume, Velocity, Variety), framework choice sets the scalability ceiling.

  • Python Scikit-Learn: Single-node processing. It can use multi-core parallelism on one server (e.g., 20–64 CPU cores) but cannot scale horizontally across distributed worker nodes. It fails when memory need exceeds one machine’s RAM.
  • Apache Spark MLlib: Distributed machine learning library. MLlib runs clustering across worker nodes using resilient distributed datasets (RDDs) and DataFrames for horizontal scale-out. Spark documentation and big-data texts place clustering beside classification, regression, and collaborative filtering inside the MLlib toolbox.

Spark MLlib unifies batch processing, Spark Streaming, and ML pipelines under a standard API pattern:

  1. Load a distributed dataset into a Spark DataFrame.
  2. Transform raw columns with VectorAssembler into feature vectors.
  3. Instantiate and fit an estimator such as KMeans().
  4. Evaluate cluster quality with distributed metrics (e.g., SilhouetteEvaluator).

Conceptual pipeline (API shape)

DataFrame  →  VectorAssembler  →  features
features   →  KMeans(k=...).fit(...)  →  model
model      →  SilhouetteEvaluator  →  score

Sense-check: every heavy step runs as distributed Spark jobs; the driver orchestrates, workers hold partitions.

Visual intuition: Scikit-Learn is one kitchen with many burners. Spark MLlib is a chain of kitchens sharing the same recipe card (KMeans) while each cooks a partition of the ingredients (data shards). Horizontal scale adds kitchens; vertical scale only upgrades one kitchen’s burners.

Scope: Distributed K-Means still needs a sensible \(k\), scaled features, and clusterability. Spark removes the RAM ceiling; it does not remove local-minima or spherical-cluster assumptions.

Assumption: Horizontal scale helps when data or compute exceeds one node. For tiny matrices that already fit in memory, Scikit-Learn is often simpler and faster to iterate.

Real-world & domain connection: Telemetry and web-scale click logs that outgrow laptop RAM use Spark MLlib K-Means for customer or session segmentation. Hierarchical clustering remains a lab / mid-size tool for taxonomy discovery.

Exam note: Contrast K-Means vs hierarchical on complexity, need for \(k\), and big-data fitness; name Spark MLlib (not single-node Scikit-Learn) as the horizontal path for clustering at volume.

Exam Guidance Summary

  • Model Evaluation Strategy: Always finalize evaluation criteria before executing algorithms. Workflow questions expect you to state why metrics must precede model training — never judge models by developer mood.
  • Hopkins Statistic Formula: Memorize

\[ H = \frac{\sum V_d}{\sum V_d + \sum U_d}. \] Exams may give \(\sum V_d\) and \(\sum U_d\) and ask whether data is cluster-worthy. Rule: \(H > 0.5\) → clusterable; \(H \le 0.5\) → do not cluster (uniform/random or non-worthy under the lecture rule).

  • K-Means Numerical Walkthrough: Expect multi-mark 1D or 2D calculations. Show every distance, assignment, and mean update. State convergence when zero points move. Watch seed sensitivity and report SSE when comparing restarts.
  • Linkage Metrics: Define and compute Single (min), Complete (max), Average, and Centroid linkage. Be ready to cut a dendrogram for a stated \(k\).
  • K-Means vs. Hierarchical Trade-offs: Contrast complexity (\(O(n\cdot k\cdot I)\) vs \(O(n^2\log n)\)/\(O(n^3)\)), whether \(k\) is required up front, determinism, geometry assumptions, and big-data fitness (Spark MLlib K-Means vs hierarchical on one node).

Exam note: Highest-yield items are Hopkins thresholds, a full K-Means iteration table, linkage definitions, and the K-Means vs hierarchical comparison row on complexity / big data.

Key Industry Applications

  • Tomato Quality Classification: Industrial agricultural sorting systems use supervised feature vectors (size, color intensity, mass) to automate high-quality vs. bad-quality tomato classification — the lecture’s running Mitchell \(T\)/\(E\)/\(P\) example.
  • Demographic Population Segmentation: Enterprise marketing platforms use unsupervised clustering to segment large populations into demographic tiers for targeted communication; domain experts name the anonymous clusters afterward.
  • Content Recommendation Engines: Digital news platforms and media apps (e.g., Android minus-one news screens) use reinforcement learning to recommend trending articles (World Cup, politics), learning from positive clicks and explicit deletion penalties.
  • E-Commerce Customer Segmentation: Sites such as Amazon cluster user clickstreams (electronics, apparel, home decor) to target promotional offers — a classic partitioning use case once Hopkins confirms structure.
  • Multiple Random Restarts (\(n_{\mathrm{init}}\)): Production ML systems set \(n_{\mathrm{init}} = 100\) for K-Means, keep the model with lowest total SSE / inertia, and avoid shipping a poor local minimum from one unlucky seed.
  • Distributed Clustering with Apache Spark MLlib: Large-scale telemetry and web-scale log pipelines deploy Spark MLlib K-Means to scale horizontally when datasets exceed single-node RAM; Scikit-Learn remains the single-node prototyping tool.

Industry pattern: define metrics → test clusterability → run multi-start K-Means (or hierarchical on smaller data) → scale out with Spark MLlib when volume demands it.

BDA Lecture 13 notes

Big Data Analytics· postgraduate· 2026-08-01

Sections Breakdown

113.1 Machine Learning Landscape & Project Workflow

Mitchell T/E/P definition, supervised/unsupervised/RL paradigms, AI⊃ML⊃DL nesting, five project phases, and RL reward customization Q&A.

213.2 Clustering Fundamentals & Data Clusterability (Hopkins Statistic)

Defines clustering goals, partitioning vs hierarchical structure, and the Hopkins Statistic H with thresholds and a numeric worked check.

313.3 Partitioning Clustering: K-Means Algorithm & Variants

Euclidean/Manhattan distances, the K-Means assign-update loop, a full 1D walkthrough with Trial 1 vs Trial 2 (resolved 16.3 centroid), SSE restarts, and K-Medoids.

413.4 Hierarchical Clustering & Linkage Criteria

Agglomerative vs divisive methods, four linkage criteria, dendrogram cuts, and a full single-linkage 1D worked example.

513.5 Comparative Analysis & Big Data Execution in Apache Spark (MLlib)

Side-by-side K-Means vs hierarchical trade-offs and Scikit-Learn vs Spark MLlib horizontal scaling with the VectorAssembler–KMeans–Silhouette pipeline.

6Exam Guidance Summary

Exam-focused checklist: evaluation-before-training, Hopkins formula/thresholds, K-Means walkthrough, linkages, and K-Means vs hierarchical trade-offs.

7Key Industry Applications

Industry links: tomato sorting, demographic and e-commerce segmentation, RL news recommendations, n_init restarts, and Spark MLlib at scale.

Postgraduate students in Big Data Analytics

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

13.1 Machine Learning Landscape & Project Workflow

Must-know: Define ML via Mitchell T/E/P; distinguish supervised (classification vs regression), unsupervised, and RL; finalize evaluation metrics before training.

⚠️ Top pitfall: Judging models by developer mood instead of predefined numeric metrics; treating AI/ML/DL as synonyms.

Self-check: For tomato sorting, name T, E, and P.

Connects to: 13.2

13.2 Clustering Fundamentals & Data Clusterability (Hopkins Statistic)

Must-know: H = sum(Vd)/(sum(Vd)+sum(Ud)); apply clustering only if H > 0.5.

\[ H = \frac{\sum_{i=1}^{m} V_{d,i}}{\sum_{i=1}^{m} V_{d,i} + \sum_{i=1}^{m} U_{d,i}} \]

⚠️ Top pitfall: Trusting algorithm output on uniform noise without a Hopkins pre-check (GIGO).

Self-check: If sum Vd=100 and sum Ud=100, is the data cluster-worthy?

Connects to: 13.1, 13.3, 13.4

13.3 Partitioning Clustering: K-Means Algorithm & Variants

Must-know: K-Means assign/update until no moves; poor seeds cause local minima; pick lowest SSE across n_init restarts.

\[ c_j = \frac{1}{|S_j|} \sum_{x \in S_j} x, \quad \mathrm{SSE} = \sum_{j=1}^{k} \sum_{x \in S_j} (x - c_j)^2 \]

⚠️ Top pitfall: Mixing Trial-1 means with a 16.3 center from another seed run; trusting one random initialization.

Self-check: With seeds 2,4,13 on the 12-point set, what is c3 after iteration 1?

Connects to: 13.2, 13.4, 13.5

13.4 Hierarchical Clustering & Linkage Criteria

Must-know: Define single/complete/average/centroid linkage; cut a dendrogram to obtain k clusters.

\[ d_{\mathrm{single}}(A,B)=\min\{d(x,y)\},\quad d_{\mathrm{complete}}(A,B)=\max\{d(x,y)\} \]

⚠️ Top pitfall: Treating leaf order on the x-axis as ranked distance; ignoring that linkage choice changes the tree.

Self-check: For clusters {1,2} and {4,5}, what is single-linkage distance?

Connects to: 13.2, 13.3, 13.5

13.5 Comparative Analysis & Big Data Execution in Apache Spark (MLlib)

Must-know: K-Means is O(n k I) and big-data friendly; hierarchical is polynomial and usually not; Spark MLlib scales clustering horizontally.

⚠️ Top pitfall: Choosing hierarchical clustering for web-scale n because it does not need k.

Self-check: Name one reason Spark MLlib beats Scikit-Learn on a multi-terabyte log.

Connects to: 13.3, 13.4

Exam Guidance Summary

Must-know: H formula and 0.5 threshold; show full K-Means iterations; name four linkages; contrast complexity for big data.

\[ H = \frac{\sum V_d}{\sum V_d + \sum U_d} \]

⚠️ Top pitfall: Skipping evaluation criteria; clustering when H ≤ 0.5.

Self-check: List the five highest-yield exam themes from this lecture.

Connects to: 13.1, 13.2, 13.3, 13.4, 13.5

Key Industry Applications

Must-know: Map each paradigm to a named industry use case; production K-Means uses many n_init restarts; Spark MLlib for horizontal scale.

⚠️ Top pitfall: Shipping a single-seed K-Means model without SSE comparison.

Self-check: Name one supervised, one unsupervised, and one RL industry example from this lecture.

Connects to: 13.1, 13.3, 13.5

Was this lecture useful?

Loading comments…