Elbow Detection via Chord Distance

Quick Overview

Implement Lloyd's k-means, build a WCSS curve across several cluster counts, and locate the elbow by perpendicular distance to the chord between the curve's endpoints. Tests deterministic k-means details, agreement with scikit-learn's inertia, and point-to-line geometry with tie handling.

Elbow Detection via Chord Distance

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement Lloyd's k-means, a WCSS curve over several `k`, and elbow detection. The elbow is the interior point with maximum perpendicular distance to the chord joining the first and last curve points. - `lloyd_kmeans(X, init_centroids, max_iter=300, tol=1e-8)` returns `(labels, centroids, inertia)`. Ties go to the lowest-index centroid. An empty cluster keeps its previous centroid. Stop when the max centroid shift (Euclidean) is `<= tol`. Final labels and inertia (sum of squared distances) are recomputed against the final centroids. - `wcss_curve(X, k_values, init_order)` seeds each run with `X[init_order[:k]]` and returns a float array. - `perpendicular_distances(k_values, wcss)` returns each curve point's perpendicular distance to the chord, and raises `ValueError` if there are fewer than 3 points or the lengths differ. - `find_elbow(k_values, wcss)` excludes endpoints, breaks ties by smallest `k`, and returns an `int`. Example: ```python k = [1, 2, 3, 4, 5]; w = [100, 40, 20, 15, 12] perpendicular_distances(k, w) # [0, 152, 144, 76, 0] / sqrt(4**2 + 88**2) # about [0, 1.7255, 1.6347, 0.8627, 0] find_elbow(k, w) # 2 ``` The chord runs from $(1, 100)$ to $(5, 12)$, so its direction is $(4, -88)$. Among the interior points, the one at $k = 2$ is farthest from it. ```hint Distance to a line The perpendicular distance from a point to the line through two other points can be written as a 2-D cross product divided by the chord length. That form vectorizes over all curve points at once. ``` ```hint Which centroids the labels belong to Your loop ends right after the centroids move. Check which centroids the labels and inertia you return were computed against. ``` ### Constraints & Assumptions - `X` has shape `(n, d)`. `k_values` is increasing. - Inertia must match scikit-learn's Lloyd `KMeans` for the same init (`rtol=1e-6`). ### What a Strong Answer Covers - Lloyd iterations with lowest-index tie breaking, the empty-cluster rule and the max-shift stopping test. - Recomputing labels and inertia against the final centroids so the result agrees with sklearn. - A WCSS curve seeded deterministically from `init_order`. - The perpendicular distance formula, its input validation, and an elbow search limited to interior points with ties going to the smallest `k`. - The cost of building the curve compared with the cost of the elbow step. ### Follow-up Questions - Why is the chord-distance elbow invariant to scaling WCSS, and when does it break? - How would you make the WCSS curve less sensitive to poor initialisation? - What alternatives would you use when the elbow is ambiguous?

Overview: Implement Lloyd's k-means, build a WCSS curve across several cluster counts, and locate the elbow by perpendicular distance to the chord between the curve's endpoints. Tests deterministic k-means details, agreement with scikit-learn's inertia, and point-to-line geometry with tie handling.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement Lloyd's k-means, a WCSS curve over several k, and elbow detection. The elbow is the interior point with maximum perpendicular distance to the chord joining the first and last curve points.

  • lloyd_kmeans(X, init_centroids, max_iter=300, tol=1e-8) returns (labels, centroids, inertia) . Ties go to the lowest-index centroid. An empty cluster keeps its previous centroid. Stop when the max centroid shift (Euclidean) is <= tol . Final labels and inertia (sum of squared distances) are recomputed against the final centroids.
  • wcss_curve(X, k_values, init_order) seeds each run with X[init_order[:k]] and returns a float array.
  • perpendicular_distances(k_values, wcss) returns each curve point's perpendicular distance to the chord, and raises ValueError if there are fewer than 3 points or the lengths differ.
  • find_elbow(k_values, wcss) excludes endpoints, breaks ties by smallest k , and returns an int .

Example:

k = [1, 2, 3, 4, 5]; w = [100, 40, 20, 15, 12]
perpendicular_distances(k, w)  # [0, 152, 144, 76, 0] / sqrt(4**2 + 88**2)
                               # about [0, 1.7255, 1.6347, 0.8627, 0]
find_elbow(k, w)               # 2

The chord runs from (1,100)(1, 100) to (5,12)(5, 12), so its direction is (4,−88)(4, -88). Among the interior points, the one at k=2k = 2 is farthest from it.

Constraints & Assumptions

  • X has shape (n, d) . k_values is increasing.
  • Inertia must match scikit-learn's Lloyd KMeans for the same init ( rtol=1e-6 ).

What a Strong Answer Covers Guidance

  • Lloyd iterations with lowest-index tie breaking, the empty-cluster rule and the max-shift stopping test.
  • Recomputing labels and inertia against the final centroids so the result agrees with sklearn.
  • A WCSS curve seeded deterministically from init_order .
  • The perpendicular distance formula, its input validation, and an elbow search limited to interior points with ties going to the smallest k .
  • The cost of building the curve compared with the cost of the elbow step.

Follow-up Questions Guidance

  • Why is the chord-distance elbow invariant to scaling WCSS, and when does it break?
  • How would you make the WCSS curve less sensitive to poor initialisation?
  • What alternatives would you use when the elbow is ambiguous?