Tag: K-Means

  • ML0178 k-Median Facility Location

    Uber wants to cluster pickup points into k stops minimizing total walking distance. Why is this k-median not k-means, and what algorithm actually solves it?

    Three dashed panels. Panel 1, the demand: a small street-grid map with blue dots for pickup requests along the streets and white squares for legal curb points, labeled 1,200 pickup requests per hour, 300 legal curb points, and walking follows the street grid. Panel 2, the prototype: a teammate ran KMeans with 12 clusters on latitude and longitude, producing 12 centroids that minimize squared distance, 3 of which fall inside buildings or a park; the dashboard reports inertia in squared meters and riders report long walks. Panel 3, the open choices: three boxes ask whether the objective should be squared or total walking distance, whether stops can go anywhere or only at legal curb points, and which algorithm, Lloyd, swap search, or exact, has a guarantee.

    The Problem: A shared-ride team must place k = 12 pickup stops for 1,200 hourly pickup requests, choosing among 300 legal curb points so that riders’ total walking distance is as small as possible. A teammate’s KMeans prototype reports a good inertia, yet 3 of its 12 centroids sit inside buildings or a park and riders complain about long walks.

    Answer

    Total walking distance adds up plain distances, so the objective is k-median, while k-means minimizes the sum of squared distances. For a single stop on a street, the median minimizes total walking and the mean minimizes squared walking, and squaring lets a few distant riders drag the stop away from everyone else. Walking also follows sidewalks rather than straight lines, and a stop must sit at a legal curb point. That makes the real problem discrete metric k-median, also called the p-median or facility-location problem, solved over a precomputed walking-distance matrix. Like k-means it is NP-hard, so Lloyd-style alternation only reaches a local optimum with no quality bound. What actually solves it is distance-weighted seeding plus swap local search, provably within 3 + 2/t of optimal, backed by the exact p-median integer program or its LP bound at city-zone sizes.

    (1) Linear Cost, Not Squared: Walking cost grows linearly with distance, while k-means squares it. One rider 300 m away then weighs as much as nine riders 100 m away and pulls the stop toward the fringe.
    (2) Median, Not Mean: On a line, total distance is minimized by the median and squared distance by the mean. On a Manhattan grid the optimum is the coordinate-wise median, and with straight-line distance it is the geometric median, found iteratively by Weiszfeld’s algorithm.
    (3) Network Distance And Candidate Stops: Walking distance is a shortest path on the pedestrian graph, so d(i, j) is a precomputed matrix, not a formula on coordinates. A mean of graph nodes is undefined, so any update step must pick a medoid from the legal curb points.
    (4) NP-Hard, With A Floor: Discrete k-median is NP-hard even for points in the plane, and metric k-median cannot be approximated below a factor of 1 + 2/e \approx 1.736 unless P = NP. k-means is NP-hard too, so Lloyd converging is never the same as Lloyd solving.
    (5) Swap Search Carries The Guarantee: Local search that swaps up to t open stops for closed candidates ends within 3 + 2/t of optimal, which is 5 for single swaps. Seeding with probability proportional to distance (not squared distance) gives an expected O(\log k)-approximate starting point.

    Mathematical Formulation:
    \min_{S \subseteq F,\ |S| = k} \sum_{j \in D} w_j\, d(j, S)
    d(j, S) = \min_{i \in S} d(i, j)
    \min \sum_{i \in F} \sum_{j \in D} w_j d_{ij} x_{ij}
    \sum_{i \in F} x_{ij} = 1
    x_{ij} \leq y_i
    \sum_{i \in F} y_i = k
    \min_{|C| = k} \sum_{j \in D} \min_{c \in C} \|x_j - c\|_2^2
    \arg\min_{c} \sum_{j} |x_j - c| = \mathrm{median}(x)
    \arg\min_{c} \sum_{j} (x_j - c)^2 = \bar x
    \mathrm{cost}(S_{\mathrm{LS}}) \leq (3 + 2/t)\, \mathrm{OPT}

    Where:

    • S is the set of opened stops, chosen from the candidate set F of legal curb points, and k is the number of stops.
    • D is the set of demand points (pickups, or grid cells that aggregate them), indexed by j, and w_j is the number of requests at point j.
    • d(i, j) = d_{ij} is the walking distance from candidate i to demand point j along the pedestrian network, and d(j, S) is the distance to the nearest open stop.
    • x_{ij} \in \{0, 1\} assigns demand j to stop i and y_i \in \{0, 1\} opens stop i. The constraints assign every demand point once, only to an open stop, with exactly k stops open. Relaxing both to [0, 1] gives the LP lower bound.
    • C is the set of k-means centers, free to sit anywhere in the plane, x_j are pickup coordinates, and \|\cdot\|_2^2 is squared straight-line distance.
    • \mathrm{median}(x) and \bar x are the median and mean of rider positions on a single street.
    • S_{\mathrm{LS}} is any solution where no swap of up to t stops lowers the cost, and \mathrm{OPT} is the optimal k-median cost.

    Worked Example:
    Five riders wait along one street at 0, 10, 20, 30 and 400 m, and we place a single stop (k = 1). The mean is \bar x = 460/5 = 92 m and the median is 20 m. At the mean the walks are 92, 82, 72, 62 and 308 m, for a total of 616 m. At the median they are 20, 10, 0, 10 and 380 m, for a total of 420 m. The k-means stop therefore costs 47% more walking (616/420 \approx 1.47). It still wins its own objective, with a squared cost of 119,080 square meters at the mean against 145,000 at the median.

    Two-panel chart. Left: grouped bars of walking distance for riders A to E at 0, 10, 20, 30 and 400 meters; with the k-means stop at the mean of 92 meters the walks are 92, 82, 72, 62 and 308 meters, totaling 616, and with the k-median stop at the median of 20 meters they are 20, 10, 0, 10 and 380, totaling 420; a note says moving the stop 72 meters toward rider E saves E 72 meters but adds 268 meters for riders A to D. Right: total walking cost and squared-distance cost, each divided by its own minimum, plotted against stop position from minus 20 to 200 meters; total walking is minimized at 20 meters and squared cost at 92 meters, where total walking is 47 percent above its minimum, while at 20 meters the squared cost is 22 percent above its minimum.

    Figure 1: (a) Per-rider walks for the worked example. Moving the stop from the median (20 m) to the mean (92 m) saves rider E 72 m but adds 268 m for riders A to D, so total walking rises from 420 m to 616 m. (b) Each cost divided by its own minimum. Total walking bottoms out at the median and squared distance at the mean, so neither stop is optimal for the other objective.

    Which Algorithm Actually Solves It:
    Because the problem is NP-hard, “solves” means either an exact method fast enough for the instance at hand or an approximation with a proven ratio. The Lloyd analogue for k-median alternates nearest-stop assignment with a per-cluster median or medoid update. It is quick but stalls in local optima, because it never moves a stop from one neighborhood to another. Swap local search (the PAM family) tries replacing an open stop with a closed candidate and keeps any swap that lowers total walking, which is exactly the move Lloyd cannot make. Arya et al. proved every swap-local optimum is within 5 times the global optimum, and within 3 + 2/t when t stops are swapped at once. LP-rounding algorithms push the best proven ratio below 2.7, but in production the swap solution is usually certified against the LP relaxation rather than replaced by a rounding algorithm.

    PropertySwap local search (PAM, FasterPAM)Lloyd-style k-mediansk-means (Lloyd)p-median integer program
    ObjectiveTotal walking distance, any metricTotal walking distanceSum of squared straight-line distancesTotal walking distance, any distance matrix
    Where stops goOnly candidate curb pointsMedoids among candidates, or off-network geometric mediansAnywhere, often inside blocksOnly candidate curb points
    GuaranteeWithin 3 + 2/t of optimal (5 for single swaps)Local optimum, no boundLocal optimum of the wrong objectiveOptimal, or a certified gap from the LP bound
    CostAbout k times |F| swap checks per pass; FasterPAM removes a factor of kOne assignment plus one medoid update per iterationCheapest, O(nk) per iterationExponential worst case; p-median LPs are often nearly integral
    Best useDefault solver at production scaleFast warm startWhen the true cost really is varianceOffline planning and certifying heuristics

    Login to view more content
  • ML0177 LDA Topic Modeling

    Explain Latent Dirichlet Allocation as a generative model: what do the document-topic and topic-word distributions look like, and how do you choose the number of topics?

    Three-panel dashed scenario card. The first panel describes 40,000 support tickets of about 120 tokens each, turned into bags of words over an 8,000-term vocabulary and fit with LDA by collapsed Gibbs sampling at K equal to 10, 40 and 150. The second panel lists held-out perplexity of 1,420 at K equal to 10, 1,180 at K equal to 40 and 1,050 at K equal to 150, plus two K equal to 150 topics, 87 and 112, that both start with refund, charge, card. The third panel asks what each ticket's topic mix and each topic's word distribution should look like, and whether to ship K equal to 10, 40 or 150, under the constraint that support ops must be able to name every topic from its top 10 words.

    The Problem: A support team fit LDA to 40,000 tickets with an 8,000-term vocabulary at K = 10, 40 and 150, and held-out perplexity kept falling from 1,420 to 1,050 while the 150-topic run began splitting refunds into near-duplicate topics. They need to know what the per-ticket and per-topic distributions should look like and which K to ship.

    Answer

    Latent Dirichlet Allocation (LDA) treats every document as a bag of words generated by a mixture of K topics, where each topic is a probability distribution over the whole vocabulary. To write document d, the model draws topic proportions \theta_d \sim \mathrm{Dir}(\alpha), then for each word slot picks a topic z from \theta_d and a word from that topic’s distribution \phi_z. The document-topic vectors are points on the (K-1)-simplex, and with \alpha below 1 they are sparse, so a typical document uses 2 to 4 topics. The topic-word vectors \phi_k \sim \mathrm{Dir}(\beta) are long-tailed distributions over all V words, where a few dozen words carry most of the mass. The number of topics is a hyperparameter the model does not learn. You sweep it and pick the value where topic coherence peaks and topics stay distinct, because held-out perplexity usually keeps improving long after topics stop being interpretable.

    (1) Generative Story: Each topic draws a word distribution \phi_k \sim \mathrm{Dir}(\beta) once for the whole corpus. Each document draws \theta_d \sim \mathrm{Dir}(\alpha), and each word slot draws a topic z_{dn} from \theta_d and then the word from \phi_{z_{dn}}.
    (2) Plate Notation: A K plate repeats \phi_k, a D plate repeats \theta_d, and an N_d word plate nested inside it repeats z_{dn} and w_{dn}. The word is the only observed node, so inference means running this story backwards to recover \theta, \phi and z.
    (3) Document-Topic Distribution: \theta_d lives on the (K-1)-simplex with prior mean \alpha_k / \sum_j \alpha_j. With \alpha below 1 it is sparse, so a real document loads on a handful of topics rather than spreading across all K.
    (4) Topic-Word Distribution: \phi_k gives every vocabulary word nonzero probability but is heavily skewed, and a small \beta sharpens the head. Its top words name the topic, and one word can rank high in several topics, which is how LDA handles polysemy.
    (5) Admixture, Not Clustering: Topics are assigned per word, so documents mix topics. Shrinking \alpha toward 0 pushes LDA toward a one-topic-per-document mixture of unigrams, whose hard-assignment fit is k-means with KL divergence.
    (6) Choosing K: Sweep K over several seeds and pick the peak of coherence (UMass, NPMI, C_v), backed by topic diversity and a human read of the top words. Held-out perplexity usually keeps falling and is a poor guide to interpretability.

    Mathematical Formulation:
    \theta_d \sim \mathrm{Dir}(\alpha)
    \phi_k \sim \mathrm{Dir}(\beta)
    z_{dn} \sim \mathrm{Cat}(\theta_d)
    w_{dn} \sim \mathrm{Cat}(\phi_{z_{dn}})
    p(w_{dn} = v \mid \theta_d, \Phi) = \sum_{k=1}^{K} \theta_{dk}\,\phi_{kv}
    p(z_{dn} = k \mid \cdot) \propto (n_{dk}^{\neg} + \alpha)\,\frac{n_{kv}^{\neg} + \beta}{n_{k}^{\neg} + V\beta}
    \mathrm{PPL} = \exp\left(-\frac{\sum_d \log p(\mathbf{w}_d)}{\sum_d N_d}\right)
    C_{\mathrm{UMass}} = \sum_{m=2}^{M} \sum_{l=1}^{m-1} \log \frac{D(v_m, v_l) + 1}{D(v_l)}

    Where:

    • \theta_d \in \Delta^{K-1} is the topic mixture of document d \in \{1, \ldots, D\}, and \alpha is its concentration, either a symmetric scalar or a vector (\alpha_1, \ldots, \alpha_K).
    • \phi_k \in \Delta^{V-1} is the word distribution of topic k \in \{1, \ldots, K\}, V is the vocabulary size, \beta is the topic-word concentration, and \Phi stacks the \phi_k into a K \times V matrix.
    • z_{dn} is the latent topic of word slot n \in \{1, \ldots, N_d\}, w_{dn} is the observed word, and \mathrm{Cat} is a categorical draw.
    • The marginal word probability is a convex combination of topic rows, so the D \times V matrix of word probabilities factorizes as \Theta \Phi with rank at most K.
    • In the collapsed Gibbs update, \theta and \Phi are integrated out: n_{dk}^{\neg} counts tokens of document d assigned to topic k, n_{kv}^{\neg} counts corpus-wide assignments of word v to k, and n_k^{\neg} is all tokens in k, each excluding the token being resampled.
    • \mathrm{PPL} is held-out perplexity, where p(\mathbf{w}_d) is the marginal likelihood of an unseen document and N_d its length; lower is better, and the marginal must be estimated (importance sampling, left-to-right, or document completion).
    • C_{\mathrm{UMass}} scores one topic from its top-M words v_1, \ldots, v_M ranked by \phi_{kv}. D(v) counts documents containing v, D(v_m, v_l) counts documents containing both, the +1 avoids \log 0, and scores closer to 0 mean more co-occurring top words.

    What the two distributions look like is set by the concentration parameters and the data together. A symmetric Dirichlet with \alpha = 1 is uniform over the simplex, values below 1 push draws toward corners and edges, and values above 1 pull draws toward the even mixture 1/K. The posterior mean \hat{\theta}_{dk} = (n_{dk} + \alpha)/(N_d + K\alpha) shows the prior acting as K\alpha pseudo-tokens. At K = 40, \alpha = 0.1 adds 4 pseudo-tokens to a 120-token ticket, while the older heuristic \alpha = 50/K = 1.25 adds 50 and visibly flattens every ticket’s mixture. On the word side, \beta = 0.01 over V = 8{,}000 words makes each \phi_k Zipf-like, which is why a topic is read and named from its top 10 to 20 words. Learning an asymmetric \alpha helps in practice, because a few broad topics can then absorb greetings and sign-offs that would otherwise leak into every specific topic.

    Three-panel figure. Panel a: LDA plate notation with hyperparameter alpha pointing to theta_d, theta_d pointing to z_dn, z_dn pointing to the shaded observed word w_dn, and beta pointing to phi_k, which points up into w_dn; a word plate N_d surrounds z_dn and w_dn, a document plate D surrounds theta_d and the word plate, and a topic plate K surrounds phi_k. Panel b: bar chart of one ticket's topic proportions over 40 topics with alpha equal to 0.1, where billing holds 0.62, login 0.24, shipping 0.09 and the other 37 topics share the remaining 0.05. Panel c: horizontal bar chart of the billing topic's top 12 words from refund at 0.071 down to fee at 0.013, with the remaining 7,988 words sharing 0.605 of the probability.

    Figure 1: (a) Plate notation, with w_{dn} as the only observed node and \phi_k shared by every document. (b) One ticket’s \theta_d under \alpha = 0.1, where 3 of 40 topics hold 95% of the mass. (c) The billing topic’s \phi_k, whose top 12 words carry 0.395 while the other 7,988 words share a long tail of 0.605.

    Choosing K is a model-selection problem that the likelihood answers badly. Held-out perplexity almost always keeps improving as K grows, because extra topics give the model more parameters to soak up residual co-occurrence. Human word-intrusion studies found that better perplexity often comes with less interpretable topics. Practitioners therefore sweep K on a grid such as 10, 20, 40, 80 and 150 with several seeds and score each run with topic coherence. UMass uses document co-occurrence in the training corpus, while NPMI and C_v use sliding windows over a reference corpus and track human ratings more closely. Pair coherence with topic diversity (the share of unique words among all topics’ top 25) and seed stability, read the topics at the two or three best values, and let downstream accuracy break ties. The hierarchical Dirichlet process (HDP) infers the number of topics instead, though it moves the choice into its own concentration parameters.

    Worked Example:
    Score two candidate topics with UMass coherence on a 1,000-ticket reference sample, using each topic’s top three words in rank order and natural logs. Topic A is {refund, charge, card} with D(\mathrm{refund}) = 200, D(\mathrm{charge}) = 150, and co-document counts of 90 for charge with refund, 60 for card with refund, and 80 for card with charge. Its score is \log(91/200) + \log(61/200) + \log(81/150) = -0.787 - 1.187 - 0.616 = -2.590. Topic B is {refund, password, shipping} with D(\mathrm{password}) = 120 and co-document counts of 4, 10 and 2. Its score is \log(5/200) + \log(11/200) + \log(3/120) = -3.689 - 2.900 - 3.689 = -10.278. Topic A’s words genuinely appear together, Topic B is a mixed topic, and the average of this score over all K topics is what a K sweep compares.

    The cleanest way to see what LDA adds is to compare it with clustering. A mixture of unigrams draws one topic per document and generates every word from it. Fitting it with hard assignments is k-means on word-count vectors with KL divergence in place of squared Euclidean distance, the same way a Gaussian mixture collapses to k-means as its variances shrink. LDA relaxes the one-topic constraint to a per-word assignment, so a ticket about a double charge after a password reset can be 60% billing and 30% login. In matrix terms LDA is a Bayesian, non-negative factorization of document-word probabilities into \Theta times \Phi. pLSA is the same factorization without the Dirichlet priors, which is why it overfits and cannot score a new document without refitting.

    PropertyLDAMixture of unigramsk-means on word counts
    Topics per documentA mixture over all K topicsExactly oneExactly one cluster
    What gets assignedEvery word token gets its own topicThe whole documentThe whole count vector
    Document representationTopic proportions on the simplexPosterior over K topicsNearest centroid index
    PriorsDirichlet on document mixtures and topic-word rowsOptional Dirichlet on mixing weightsNone
    Fit byCollapsed Gibbs or variational BayesEMLloyd iterations
    New documentFold in its mixture with topics held fixedBayes rule over K topicsAssign the nearest centroid
    Limit relationApproaches the mixture of unigrams as alpha shrinks toward 0Hard-assignment EM becomes k-means with KL divergenceEuclidean special case of hard clustering

    Login to view more content
  • ML0172 Hierarchical Clustering

    Explain agglomerative clustering: linkage choices (single/complete/average/Ward), the dendrogram, and where to cut it. Why is it O(n^2) memory?

    Three-panel scenario card. Panel one, the data: 3,000 customer profiles with 8 standardized features, a goal of 3 to 6 segments for marketing campaigns, and no fixed k known up front. Panel two, pilot runs and constraints: a single-linkage cut at k equal to 4 gave cluster sizes 2,991, 6, 2 and 1; a Ward run has six highest merge heights 52.0, 38.5, 31.0, 12.4, 10.9 and 9.7; next quarter the job must run on 100,000 customers on one 32 GB machine. Panel three lists the open decisions: which linkage, where to cut the dendrogram, and whether 100,000 points fit in 32 GB of RAM.

    The Problem: A retail team wants 3 to 6 customer segments from 3,000 profiles with 8 standardized features, but a single-linkage pilot cut at k = 4 returned clusters of 2,991, 6, 2 and 1 customers, while a Ward run shows top merge heights of 52.0, 38.5, 31.0, 12.4, 10.9 and 9.7. Next quarter the same job must run on 100,000 customers on a 32 GB machine, and nobody has decided the linkage, the cut, or whether it will fit.

    Answer

    Agglomerative clustering starts with every point as its own cluster and repeatedly merges the two closest clusters until one remains. Each merge and its height are recorded in a dendrogram, a binary tree with n-1 joins. The linkage defines “closest”: single uses the nearest cross pair, complete the farthest, average the mean over all cross pairs, and Ward the increase in within-cluster sum of squares. A flat clustering comes from cutting the tree horizontally, ideally inside a large gap between consecutive merge heights. The standard algorithm stores all n(n-1)/2 pairwise cluster distances and refreshes them after every merge with the Lance-Williams update. That matrix is the source of the O(n^2) memory, and at n = 100{,}000 it holds about 5 billion float64 values, or 40 GB.

    (1) Single Linkage: Distance between the two nearest members, which makes the hierarchy equivalent to the minimum spanning tree. It recovers elongated, non-convex shapes but chains clusters together through a few bridging points.
    (2) Complete Linkage: Distance between the two farthest members, so every cluster formed below height h has diameter at most h. Clusters come out compact, but one outlier inflates a diameter and large groups tend to be split.
    (3) Average Linkage: Mean of all |A|\,|B| cross distances, also called UPGMA. It sits between the two extremes, dilutes single outliers, and works with any dissimilarity such as cosine or correlation.
    (4) Ward Linkage: Merges the pair whose union adds the least within-cluster sum of squares, the same objective k-means minimizes. It yields compact clusters of similar size and only makes sense with Euclidean distance.
    (5) Reading The Dendrogram: Only heights carry meaning, since the left-right order is one of 2^{n-1} equivalent flips. Cut at a fixed height, at the level that leaves k branches, or inside the largest gap between merge heights.
    (6) Why Quadratic Memory: After merging i and j, the Lance-Williams update needs the old distances from every other cluster to both, so the whole distance matrix must stay live. The nearest-neighbor chain algorithm brings time down to O(n^2) from the naive O(n^3), but memory stays quadratic for complete and average linkage.

    Mathematical Formulation:
    d_{\mathrm{single}}(A,B) = \min_{a \in A,\, b \in B} d(a,b)
    d_{\mathrm{complete}}(A,B) = \max_{a \in A,\, b \in B} d(a,b)
    d_{\mathrm{avg}}(A,B) = \frac{1}{|A|\,|B|} \sum_{a \in A} \sum_{b \in B} d(a,b)
    \Delta_{\mathrm{Ward}}(A,B) = \frac{|A|\,|B|}{|A| + |B|} \, \|\mu_A - \mu_B\|^2
    d_{k,(ij)} = \alpha_i d_{ki} + \alpha_j d_{kj} + \beta d_{ij} + \gamma \delta_k
    \delta_k = |d_{ki} - d_{kj}|
    M = 8 \cdot \frac{n(n-1)}{2}\ \text{bytes}

    Where:

    • A and B are two current clusters with members a and b, |A| is a cluster size, and d is the base dissimilarity. Single, complete and average linkage accept any dissimilarity.
    • \mu_A is the centroid of A, and \Delta_{\mathrm{Ward}} is the exact rise in total within-cluster SSE when A and B merge. It requires Euclidean geometry, and SciPy reports the merge height as \sqrt{2\Delta}.
    • d_{ki}, d_{kj} and d_{ij} are pre-merge distances between an untouched cluster k and the just-merged clusters i and j, and d_{k,(ij)} is the updated distance to their union.
    • \alpha_i, \alpha_j, \beta, \gamma select the linkage. Single uses \alpha = \frac{1}{2}, \beta = 0, \gamma = -\frac{1}{2} (a min), complete flips to \gamma = +\frac{1}{2} (a max), and average uses \alpha_i = \frac{n_i}{n_i + n_j} with \beta = \gamma = 0.
    • Ward uses \alpha_i = \frac{n_i + n_k}{n_i + n_j + n_k}, \beta = -\frac{n_k}{n_i + n_j + n_k} and \gamma = 0 on squared Euclidean distances, where n_i, n_j, n_k are cluster sizes.
    • M is the size of the condensed float64 distance matrix for n points: 36 MB at n = 3{,}000, 40 GB at n = 100{,}000, and double that for a full square matrix.

    Worked Example:
    On a line, take clusters A = \{0, 2\}, B = \{4, 9\} and C = \{12.5\}. The cross distances between A and B are 4, 9, 2 and 7, so single gives 2, complete gives 9 and average gives 5.5. Between B and C they are 8.5 and 3.5, so single gives 3.5, complete gives 8.5 and average gives 6.0. Single and average therefore merge A with B, while complete merges B with C because 8.5 beats 9. Ward compares SSE increases: \Delta(A,B) = 1 \times 5.5^2 = 30.25 and \Delta(B,C) = \frac{2}{3} \times 6^2 = 24, so Ward also picks B \cup C. Same three clusters, two different trees after one step.

    Four scatter panels of the same 315 two-dimensional points, made of a large blob, a smaller blob joined to it by a thin bridge of 12 points, a curved arc above them, and three isolated points. Each panel colors the k equals 3 clustering from one linkage: single, complete, average and Ward, with the resulting cluster sizes printed in each panel title.

    Figure 1: The same 315 points cut at k = 3 under each linkage, with cluster sizes in each panel title. Single linkage follows nearest-neighbor chains, so the 12-point bridge and the isolated points decide its partition. Ward prices every merge by added variance and favors compact groups of similar spread, and complete and average land between these extremes.

    In practice the choice follows from two questions: which dissimilarity do you trust, and what cluster shape do you expect? Ward is the default for standardized numeric features where k-means-like segments are wanted. Average linkage is the default for non-Euclidean similarities such as correlation between gene-expression profiles, and single linkage is reserved for clean data with genuinely elongated structure.

    PropertyWardAverageCompleteSingle
    Merge criterionSmallest rise in within-cluster SSEMean of all cross-pair distancesFarthest cross pairNearest cross pair
    Cluster shapeCompact, similar size and varianceModerately compact, tolerates size differencesCompact with bounded diameterArbitrary, elongated chains
    Outliers and noiseAbsorbed into the nearest compact groupDiluted by averagingInflate diameters and split large groupsBecome singletons, and bridges chain clusters
    DissimilarityEuclidean onlyAnyAnyAny
    Best exact algorithmO(n²) time; O(nd) memory from stored centroidsNN-chain, O(n²) time and O(n²) memoryNN-chain, O(n²) time and O(n²) memoryMST or SLINK, O(n²) time and O(n) memory
    Reach for it whenYou want k-means-like segments plus a hierarchyThe similarity is cosine or correlationEvery cluster must stay within a maximum spreadData are clean and shapes are non-convex

    Login to view more content
  • ML0171 Spectral Clustering

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0117 Clustering Internal Metrics

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0109 Expectation-Maximization

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0010 K-Means From Scratch

    Mode B · Build & Trace 30 Min NumPy 4 Array Blanks

    Clustering prototypes show up constantly on Google and Waymo ML teams, and this screen (reported by candidates from both companies' coding rounds) rewards the same habit: writing a few lines of vectorized NumPy that stay correct when the data misbehaves. You must implement KMeans.fit(X, k) from scratch. It takes a float array of shape (n_samples, n_features) and returns integer cluster labels of shape (n_samples,) and centroids of shape (k, n_features). Calling sklearn.cluster.KMeans, scipy.cluster.vq, or scipy.spatial.distance.cdist is forbidden.

    Initialization is fixed for this round: k distinct rows of X drawn at random, with k-means++ left as a follow-up. The interviewer cares less about the happy path than about three edge cases. A cluster can come out empty mid-run, the loop needs a defensible stopping rule, and a correct implementation must preserve specific invariants on every iteration.

    Complete the 4 missing operations in the skeleton below and narrate the array shape after each line. Then state the algorithm's time complexity, explain how you would choose k, and write a test that checks invariants rather than one hand-picked output.

    Skeleton Code (Fill Blanks 1-4):

    01  import numpy as np
    02
    03
    04  class KMeans:
    05      def __init__(self, max_iter: int = 100, tol: float = 1e-6, seed: int = 0):
    06          self.max_iter, self.tol = max_iter, tol
    07          self.rng = np.random.default_rng(seed)
    08
    09      def fit(self, X: np.ndarray, k: int):
    10          n_samples, n_features = X.shape                    # X: (n_samples, n_features) float64
    11          centroids = X[self.rng.choice(n_samples, size=k, replace=False)]   # (k, n_features)
    12          self.inertia_history = []
    13          for it in range(self.max_iter):
    14              # TODO (Blank 1): squared distances from every point to every
    15              #                 centroid, shape (n_samples, k), no Python loops
    16              sq_dists = ...
    17              # TODO (Blank 2): index of the nearest centroid per point, (n_samples,)
    18              labels = ...
    19              self.inertia_history.append(sq_dists[np.arange(n_samples), labels].sum())
    20              prev_centroids = centroids.copy()
    21              # TODO (Blank 3): recompute each centroid as the mean of its
    22              #                 points; an empty cluster must stay finite
    23              ...
    24              # TODO (Blank 4): stop when the centroids have converged
    25              if ...:
    26                  break
    27          self.centroids_, self.labels_, self.n_iter_ = centroids, labels, it + 1
    28          return labels, centroids
    Operator contract for KMeans.fit: input X of shape (n_samples, n_features) with k random rows as initial centroids flows through four question-marked steps (Blank 1 distances, Blank 2 assignment, Blank 3 centroid update, Blank 4 stop check) with a loop back for the next iteration, ending at labels (n_samples,) and centroids (k, n_features); below, three boxes list the edge cases the interviewer probes

    Figure 1: the input and output contract is fixed, the random-row initialization is given, and the four steps inside the Lloyd loop are yours to write, with the interviewer probing empty clusters, the stopping rule, and the loop's invariants.

    Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the invariant checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Broadcast Geometry: Align the point axis of X and the centroid axis of centroids so one subtraction covers every pair, then reduce over the feature axis only.
    (2) Reduction Axis: The assignment must produce one label per point, and line 19 indexes sq_dists with exactly that shape.
    (3) Empty-Cluster Contract: Decide what a centroid with zero members should be before writing the update, and keep every centroid finite.
    (4) Stopping Rule: Compare the updated centroids with the snapshot on line 20 using an explicit tolerance, and remember that line 13 is the second guard.

    2Visual Review Map (Figure 2)
    Shape trace for KMeans.fit: X (n_samples, n_features) and centroids (k, n_features) feed question-marked blanks whose target shapes are an intermediate (n_samples, k, n_features), sq_dists (n_samples, k), labels (n_samples,), new centroids (k, n_features), and a boolean stop flag; the line 19 inertia and the line 20 prev_centroids snapshot are shown as given, with a loop back to Blank 1 for the next iteration

    Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shape it must produce; writing the operations that reach them is the exercise.

    3Interviewer Nudge & Line Focus

    Pin the input shape, output shape, and failure mode of each blank before writing the NumPy call:

    Blank 1 (Distance Matrix): X is (n_samples, n_features) and centroids is (k, n_features). Which singleton axes must you insert so the subtraction broadcasts to a 3-axis tensor, and which axis do you reduce? If n_samples == k, what does a plain X - centroids silently compute instead of raising?
    Blank 2 (Assignment): sq_dists is (n_samples, k). Does the reduction collapse the point axis or the centroid axis, what shape would the other choice produce, and which index wins when two centroids sit at exactly the same distance?
    Blank 3 (Centroid Update): If X contains duplicate rows, two initial centroids can be identical. What does averaging a (0, n_features) array return, what happens to the next distance matrix once one centroid holds that value, and which two finite choices could you make instead?
    Blank 4 (Convergence): Lloyd's algorithm visits finitely many partitions, so why still compare against a tolerance in the data's units, and why does line 13 keep its bound even when your stop check is correct?
    Answer
    Login to view more content
  • ML0094 GMM vs K-Means

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0093 DBSCAN Clustering

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0061 KNN and K-means

    What are the key differences between KNN and K-means?

    A question card shows two notebook cells, one calling KNeighborsClassifier with n_neighbors=5 and the other calling KMeans with n_clusters=5, each followed by blank prompts asking what K counts, what input data it needs and what it outputs.

    The Problem: A teammate’s notebook has two cells that both set K = 5, one for KNN and one for K-means, and treats them as interchangeable. Fill in the blanks for each cell: what does K count, what data does the method need, and what does it return? Are these really the same kind of algorithm?

    Answer

    KNN (K-Nearest Neighbors) is a supervised algorithm that classifies data using the labels of its nearest neighbors: prediction from historical labeled data. K-means is an unsupervised clustering technique that groups data purely by similarity, using no labels at all. Despite the shared “K”, they solve different problems.

    (1) Learning Type: KNN is supervised (classification/regression); K-means is unsupervised (clustering).
    (2) Objective: KNN predicts a new sample’s label from the majority vote (or average) of its K nearest neighbors; K-means partitions the dataset into K clusters by minimizing intra-cluster distance.
    (3) Training: KNN has no explicit training: it stores the entire dataset; K-means iteratively learns cluster centroids.
    (4) Prediction Cost: KNN is expensive at prediction (distance to every training point, sort, take the top K, then vote/average); K-means is cheap: distances to K centroids, assign the nearest.
    (5) Distance Use And Output: KNN uses distance to find neighbors and outputs a label or value; K-means uses distance to assign points to centroids and outputs cluster assignments plus centroids.

    FeatureK-Nearest Neighbors (KNN)K-Means
    TypeSupervised LearningUnsupervised Learning
    TaskClassification, RegressionClustering
    Data RequiredLabeled dataUnlabeled data
    Training PhaseStores all training data (lazy learner)Iterative centroid calculation
    Prediction PhaseFinds K nearest neighbors and assigns label/valueAssigns new points to closest cluster centroid
    Compute CostHigh at prediction (distance calculations for each new point)High at training (iterative updates); low at prediction (centroid assignment)
    GoalPredict label/value for new dataGroup data into K clusters
    OutputClass label or predicted valueData points assigned to clusters

    Mathematical Formulation:
    \hat{y} = \arg\max_{c \in \mathcal{C}} \; \sum_{i=1}^{K} \mathbb{1}(y_i = c)
    \min_{C_1, \ldots, C_K} \; \sum_{k=1}^{K} \sum_{x \in C_k} \|x - \mu_k\|^2

    Where:

    • KNN (first line): \hat{y} is the predicted class, \mathcal{C} the class set, y_i the label of the i-th nearest neighbor, and \mathbb{1}(\cdot) the vote-counting indicator.
    • K-means (second line): C_k is cluster k and \mu_k its centroid; the algorithm minimizes total within-cluster squared distance: no labels appear anywhere.
    Two panels on crescent moon data showing KNN separating the moons correctly while K-means cuts through them

    Figure 1: Same data, different goals: with labels, KNN’s local votes trace the two crescents perfectly (left); without labels, K-means can only split by nearest-centroid geometry and slices through both moons (right). KNN performs well here thanks to local decision-making; K-means fails because it assumes spherical clusters with linear boundaries.


    Login to view more content