Cut a Linkage Matrix into Flat Labels

Quick Overview

Implement a function that cuts a hierarchical clustering linkage matrix into flat cluster labels, either by a target cluster count or by a distance threshold. It tests how linkage rows encode merges, union-find bookkeeping, canonical relabeling and agreement with SciPy's fcluster.

Cut a Linkage Matrix into Flat Labels

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `cut_linkage(Z, n_clusters=None, distance_threshold=None)`. `Z` is a SciPy-style linkage matrix of shape `(n-1, 4)`: row `i` is `[a, b, dist, count]` and creates cluster id `n + i` (ids `< n` are observations). Return flat cluster labels as an `int64` array of length `n`. - With `n_clusters=k`, apply only the first `n - k` merges (rows in order). - With `distance_threshold=t`, apply every merge with `dist <= t` (inclusive). - Labels are 0-based, numbered by first appearance over observations `0..n-1`. - Raise `ValueError` if neither or both criteria are given, if `n_clusters` is outside `[1, n]`, or if `Z` is not 2-D with 4 columns. Example: ```python Z = [[0, 1, 1.0, 2], [2, 3, 2.0, 2], [5, 6, 4.0, 4], [4, 7, 13.0, 5]] # n = 5 cut_linkage(Z, n_clusters=3) # [0, 0, 1, 1, 2] cut_linkage(Z, distance_threshold=2.0) # [0, 0, 1, 1, 2] cut_linkage(Z, distance_threshold=1.999) # [0, 0, 1, 2, 3] ``` ```hint Replay the merges Walk the rows of `Z` in order and decide for each row whether the cut applies it. A structure that tracks which observations are already joined does the rest. ``` ```hint Merged cluster ids A row can name a merged cluster `n + i` as a child. Keep a way to get from any cluster id to one observation inside it. ``` ### Constraints & Assumptions - 2 ≤ `n` ≤ 1000. - `Z` is a valid linkage (for example from `scipy.cluster.hierarchy.linkage`) whose merge heights do not decrease down the rows, as with single, complete, average, weighted and Ward linkage. - Output must match `fcluster` up to relabeling: `criterion="distance"` for a threshold, `criterion="maxclust"` for `n_clusters`. For `n_clusters` this holds when the last applied merge and the next one have different heights. On such a tie `fcluster` applies both and returns fewer clusters, and the rules above define the expected answer. ### What a Strong Answer Covers - Validation of the shape of `Z` and of the arguments, covering each error case in the task. - The set of rows each criterion applies, with the threshold treated as inclusive. - A replay that resolves merged cluster ids `n + i` to the observations they contain and joins only the applied merges. - Relabeling by first appearance over the observations, returned as `int64`. - Time and space complexity, and the conditions under which the result agrees with `fcluster`. ### Follow-up Questions - How would you handle a linkage with inversions, such as one from centroid or median linkage, where merge heights can decrease? - How does `fcluster` with `criterion="maxclust"` behave when several merges share the height at the cut, and how would you reproduce its output? - How would you choose `k` or `t` when you have no ground-truth labels?

Overview: Implement a function that cuts a hierarchical clustering linkage matrix into flat cluster labels, either by a target cluster count or by a distance threshold. It tests how linkage rows encode merges, union-find bookkeeping, canonical relabeling and agreement with SciPy's fcluster.

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

Implement cut_linkage(Z, n_clusters=None, distance_threshold=None). Z is a SciPy-style linkage matrix of shape (n-1, 4): row i is [a, b, dist, count] and creates cluster id n + i (ids < n are observations). Return flat cluster labels as an int64 array of length n.

  • With n_clusters=k , apply only the first n - k merges (rows in order).
  • With distance_threshold=t , apply every merge with dist <= t (inclusive).
  • Labels are 0-based, numbered by first appearance over observations 0..n-1 .
  • Raise ValueError if neither or both criteria are given, if n_clusters is outside [1, n] , or if Z is not 2-D with 4 columns.

Example:

Z = [[0, 1, 1.0, 2],
     [2, 3, 2.0, 2],
     [5, 6, 4.0, 4],
     [4, 7, 13.0, 5]]   # n = 5

cut_linkage(Z, n_clusters=3)             # [0, 0, 1, 1, 2]
cut_linkage(Z, distance_threshold=2.0)   # [0, 0, 1, 1, 2]
cut_linkage(Z, distance_threshold=1.999) # [0, 0, 1, 2, 3]

Constraints & Assumptions

  • 2 ≤ n ≤ 1000.
  • Z is a valid linkage (for example from scipy.cluster.hierarchy.linkage ) whose merge heights do not decrease down the rows, as with single, complete, average, weighted and Ward linkage.
  • Output must match fcluster up to relabeling: criterion="distance" for a threshold, criterion="maxclust" for n_clusters . For n_clusters this holds when the last applied merge and the next one have different heights. On such a tie fcluster applies both and returns fewer clusters, and the rules above define the expected answer.

What a Strong Answer Covers Guidance

  • Validation of the shape of Z and of the arguments, covering each error case in the task.
  • The set of rows each criterion applies, with the threshold treated as inclusive.
  • A replay that resolves merged cluster ids n + i to the observations they contain and joins only the applied merges.
  • Relabeling by first appearance over the observations, returned as int64 .
  • Time and space complexity, and the conditions under which the result agrees with fcluster .

Follow-up Questions Guidance

  • How would you handle a linkage with inversions, such as one from centroid or median linkage, where merge heights can decrease?
  • How does fcluster with criterion="maxclust" behave when several merges share the height at the cut, and how would you reproduce its output?
  • How would you choose k or t when you have no ground-truth labels?