Compute all pairwise Jaccard similarities from a binary matrix

Why it matters Jaccard over shingles or tags is the base of near-duplicate removal for LLM training data and of set-based recommenders.

Near-duplicate detection and tag overlap compare sets. If each set is a row of 0s and 1s, a single matrix product gives every pairwise intersection, and Jaccard follows without loops.

Write jaccard_matrix(X) where X is an (N, V) array of 0s and 1s (row i is set i). Return the (N, N) float matrix J with J[i, j] = |A_i and A_j| / |A_i or A_j|. If both sets are empty, J[i, j] = 0.0.

Signaturedef jaccard_matrix(X)

Example

X = [[1, 1, 0], [0, 1, 1], [0, 0, 0]] gives [[1.0, 0.3333, 0.0], [0.3333, 1.0, 0.0], [0.0, 0.0, 0.0]] (rounded).

Understand the idea

Jaccard similarity of two sets is the size of their overlap divided by the size of their union. It is 1 for identical sets and 0 for sets with nothing in common.

Worked example: A = {0, 1} and B = {1, 2}, written as rows [1, 1, 0] and [0, 1, 1]. The dot product 1*0 + 1*1 + 0*1 = 1 is the overlap. Sizes are 2 and 2, so the union is 2 + 2 - 1 = 3, and J = 1 / 3 = 0.333.

Rule: J(A, B) = |A and B| / (|A| + |B| - |A and B|). For a 0/1 matrix X: inter = X X^T, union = s_i + s_j - inter, with s = row sums.

Training data dedup pipelines compare shingle sets with Jaccard (MinHash approximates exactly this value), and tag-based recommenders use it for item similarity.

Shapes and data flow

X (N, V) -> inter (N, N), s (N,), union (N, N) -> J (N, N)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplejaccard_matrix([[1, 1, 0], [0, 1, 1], [0, 0, 0]])
  • Sample 2: random setsjaccard_matrix(_X)
  • Test 3: identical setsjaccard_matrix([[1, 0, 1], [1, 0, 1]])