Sub topic 1
Sets and Jaccard Similarity
Prerequisites
This chapter assumes you know the following:
- Basic set operations: union and intersection.
- Basic probability, including the probability of an event and expected value.
- What a hash function is.
- How to read short Python programs.
Later chapters build MinHash on top of the measure defined here, so the definitions below matter.
Why compare sets
Many similarity problems reduce to comparing collections of items where order and repeats do not matter. Examples:
- The words that appear in two web pages.
- The products two customers have bought.
- The users who follow two accounts.
A set is an unordered collection of distinct elements. Two sets are similar when they share many elements. To make "many" precise, we need a number that does not depend on how large the sets are.
Jaccard similarity
The Jaccard similarity of sets A and B is the size of their intersection divided by the size of their union:
J(A, B) = |A ∩ B| / |A ∪ B|
Here |X| means the number of elements in X. The result has these properties:
- It is always between 0 and 1.
- It is 0 when the sets share nothing.
- It is 1 when the sets are identical.
- It is symmetric: J(A, B) = J(B, A).
Dividing by the union keeps the measure fair. Two huge sets that overlap by a few elements score low. Two tiny sets that overlap completely score high.
By convention, J(∅, ∅) is undefined, because the union is empty. Code should handle this case explicitly.
A worked example
Let A contain the numbers 0 to 149 and B contain the numbers 50 to 199.
- The intersection is the numbers 50 to 149, which is 100 elements.
- The union is the numbers 0 to 199, which is 200 elements.
- So J(A, B) = 100 / 200 = 0.5.
def jaccard(a, b):
return len(a & b) / len(a | b)
A = {str(i) for i in range(0, 150)}
B = {str(i) for i in range(50, 200)}
print(jaccard(A, B)) # 100 shared elements out of 200 distinct: 0.5The & operator computes the intersection and | computes the union. Python sets store each element once, so duplicates vanish automatically.
The next diagram shows the same example as a picture of the three regions.
Distance and common pitfalls
The Jaccard distance is 1 − J(A, B). It is 0 for identical sets and 1 for disjoint sets. It satisfies the triangle inequality, so it is a true metric. That property is useful when you want to use it with algorithms that expect a distance.
Watch for these errors:
- Using a list instead of a set. Lists keep duplicates, so
len(list_a)does not count distinct elements. Convert withset(...)first. - Dividing by the size of one set instead of the union. That measures containment, which is a different quantity: |A ∩ B| / |A|. It is not symmetric.
- Forgetting the empty case.
jaccard(set(), set())raisesZeroDivisionError. - Treating the score as a percentage of "words in common". A score of 0.5 means half of all distinct elements are shared, not half of each set.
A guarded version handles the empty case:
def jaccard_safe(a, b):
union = a | b
if not union:
return 1.0 # choose a convention: two empty sets are identical
return len(a & b) / len(union)
print(jaccard_safe(set(), set()))
print(jaccard_safe({"x", "y"}, {"y", "z"})) # 1 shared of 3 distinct: 0.333...Where this is heading
Computing Jaccard similarity exactly requires looking at every element of both sets. For two small sets that is cheap. For millions of large sets it is not. The following chapters show how MinHash replaces each set with a short signature, so the Jaccard similarity can be estimated from the signatures alone. The value you computed here, 0.5 for the example sets, is the target the estimator will approach.
Exercise
Let A = {"a", "b", "c", "d"} and B = {"c", "d", "e"}. Compute J(A, B) and the Jaccard distance. Then say what containment of B in A (|A ∩ B| / |B|) would be, and why it differs from J.
Show answer
The intersection is {"c", "d"}, so 2 elements. The union is {"a", "b", "c", "d", "e"}, so 5 elements. J = 2/5 = 0.4 and the Jaccard distance is 1 − 0.4 = 0.6. Containment of B in A is 2/3, about 0.667. It is larger because it divides by |B| alone, ignoring the elements only in A, while J divides by the whole union.
Exercise
Two sets each have 1,000 elements and share 10 of them. Another pair of sets each have 20 elements and share 10 of them. Compute both Jaccard similarities and explain what the difference shows.
Show answer
The first pair has a union of 1,000 + 1,000 − 10 = 1,990, so J = 10/1990, about 0.005. The second pair has a union of 20 + 20 − 10 = 30, so J = 10/30, about 0.333. The same overlap count gives very different scores because Jaccard similarity is relative to the union size, so it measures the proportion shared rather than the raw overlap.