Contingency Matrix, Purity and Adjusted Rand Index

Quick Overview

Implement a contingency matrix, cluster purity and the adjusted Rand index from scratch in NumPy for two label arrays. It tests label-to-index mapping, pair counting, the chance correction behind ARI and the degenerate cases where the formula would divide by zero.

Contingency Matrix, Purity and Adjusted Rand Index

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given 1-D arrays `labels_true` and `labels_pred`, implement `contingency_matrix`, `purity` and `adjusted_rand_index` from scratch (no sklearn). - `contingency_matrix` returns an integer array of shape (n_classes, n_clusters). Rows follow the sorted unique true labels and columns follow the sorted unique predicted labels. - `purity` is the sum over clusters of the largest class count, divided by `n`. Return a `float`. - `adjusted_rand_index` is the standard (Hubert-Arabie) ARI as a `float`, which may be negative. Return `1.0` when the pair count or the denominator is zero. - Inputs that are not 1-D, or that have mismatched lengths, raise `ValueError`. Example: ```python labels_true = [0, 0, 0, 1, 1, 1, 2, 2] labels_pred = [1, 1, 0, 0, 0, 2, 2, 2] contingency_matrix(labels_true, labels_pred) # [[1, 2, 0], [2, 0, 1], [0, 0, 2]] purity(labels_true, labels_pred) # 0.75 adjusted_rand_index(labels_true, labels_pred) # 5/21 ≈ 0.238095 ``` ```hint Build one thing first Compute the contingency matrix, then write purity and ARI as reductions over its cells, its row sums and its column sums. ``` ```hint Labels are not indices Labels can be strings, negative or non-contiguous. Look for a NumPy call that returns the sorted unique values together with each element's position among them. ``` ```hint Pairs and degenerate cases ARI counts pairs of points. Work out what happens to the denominator when both labelings put everything in one cluster, or when both make every point a singleton. ``` ### Constraints & Assumptions - Labels are arbitrary sortable values (ints, possibly negative, or strings) and need not be contiguous. - Inputs may be lists or NumPy arrays. - ARI must be symmetric and invariant to label permutation, and must match sklearn's `adjusted_rand_score` to 1e-7. ### What a Strong Answer Covers - Input validation for dimensionality and length, and a label-to-index mapping that keeps rows and columns in sorted label order for any sortable label type. - A correct count of (true, predicted) pairs into the matrix, and purity computed per cluster from it. - The ARI formula in pair counts: the index, its expected value under chance and its maximum, with an explanation of why the correction makes random labelings score near 0. - Handling of the cases that return `1.0`, and why the result is symmetric and permutation-invariant. - Time and space complexity, plus numeric concerns such as integer overflow in the pair-count products. ### Follow-up Questions - Why is purity a poor metric on its own? - How would you scale the contingency matrix to millions of points and thousands of labels? - How does ARI differ from NMI, and when would you prefer one over the other?

Overview: Implement a contingency matrix, cluster purity and the adjusted Rand index from scratch in NumPy for two label arrays. It tests label-to-index mapping, pair counting, the chance correction behind ARI and the degenerate cases where the formula would divide by zero.

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

Given 1-D arrays labels_true and labels_pred, implement contingency_matrix, purity and adjusted_rand_index from scratch (no sklearn).

  • contingency_matrix returns an integer array of shape (n_classes, n_clusters). Rows follow the sorted unique true labels and columns follow the sorted unique predicted labels.
  • purity is the sum over clusters of the largest class count, divided by n . Return a float .
  • adjusted_rand_index is the standard (Hubert-Arabie) ARI as a float , which may be negative. Return 1.0 when the pair count or the denominator is zero.
  • Inputs that are not 1-D, or that have mismatched lengths, raise ValueError .

Example:

labels_true = [0, 0, 0, 1, 1, 1, 2, 2]
labels_pred = [1, 1, 0, 0, 0, 2, 2, 2]

contingency_matrix(labels_true, labels_pred)   # [[1, 2, 0], [2, 0, 1], [0, 0, 2]]
purity(labels_true, labels_pred)               # 0.75
adjusted_rand_index(labels_true, labels_pred)  # 5/21 ≈ 0.238095

Constraints & Assumptions

  • Labels are arbitrary sortable values (ints, possibly negative, or strings) and need not be contiguous.
  • Inputs may be lists or NumPy arrays.
  • ARI must be symmetric and invariant to label permutation, and must match sklearn's adjusted_rand_score to 1e-7.

What a Strong Answer Covers Guidance

  • Input validation for dimensionality and length, and a label-to-index mapping that keeps rows and columns in sorted label order for any sortable label type.
  • A correct count of (true, predicted) pairs into the matrix, and purity computed per cluster from it.
  • The ARI formula in pair counts: the index, its expected value under chance and its maximum, with an explanation of why the correction makes random labelings score near 0.
  • Handling of the cases that return 1.0 , and why the result is symmetric and permutation-invariant.
  • Time and space complexity, plus numeric concerns such as integer overflow in the pair-count products.

Follow-up Questions Guidance

  • Why is purity a poor metric on its own?
  • How would you scale the contingency matrix to millions of points and thousands of labels?
  • How does ARI differ from NMI, and when would you prefer one over the other?