Sub topic 3
Turning documents into sets with shingling
MinHash works on sets, but documents are sequences of words. This chapter shows how to turn a document into a set so that Jaccard similarity measures how much two documents overlap. It assumes you know set union and intersection, the Jaccard formula from earlier chapters, and short Python programs.
Why a plain word set is not enough
The simplest conversion keeps every distinct word and drops the order. Two documents are then similar when they use the same vocabulary. That is a weak test. These two sentences use the same words in a different order, so they have identical word sets:
- "the dog bit the man"
- "the man bit the dog"
Their Jaccard similarity is 1.0, yet they mean different things. Word sets throw away local order, and local order carries much of what makes a document what it is.
Shingles keep local order
A shingle (also called a k-gram or n-gram) is a run of n consecutive items from the document. With word shingles of size n = 3, each shingle is three consecutive words. The document becomes the set of all its shingles, overlapping with one another.
def shingles(text, n=3):
words = text.lower().split()
return {" ".join(words[i:i + n]) for i in range(len(words) - n + 1)}
def jaccard(a, b):
return len(a & b) / len(a | b)
d1 = "the quick brown fox jumps over the lazy dog"
d2 = "the quick brown fox leaps over the lazy dog"
s1 = shingles(d1)
s2 = shingles(d2)
print(len(s1), len(s2), jaccard(s1, s2))
print(jaccard(shingles(d1, 1), shingles(d2, 1)))The first line prints 7 7 0.4. Each document has nine words, so each has 9 − 3 + 1 = 7 shingles. Four shingles are shared:
- "the quick brown"
- "quick brown fox"
- "over the lazy"
- "the lazy dog"
The union has 7 + 7 − 4 = 10 shingles, so the similarity is 4/10.
The second line prints about 0.778. With n = 1 the shingles are single words, so seven of the nine distinct words are shared. Changing one word cost little in the word-set view. It cost much more with n = 3, because one changed word appears in up to n different shingles.
Choosing the shingle size
The size n sets how strict "similar" is.
- Small n (1 or 2) gives sets that overlap a lot. Unrelated documents in the same language share many common words and short phrases, so similarity scores come out high for pairs that are not near-duplicates.
- Large n gives sets that overlap only when long passages match. A single edit destroys up to n shingles, so lightly edited copies score lower.
For word shingles in ordinary prose, n between 3 and 5 is a common range. Character shingles, taken over letters instead of words, are common for short texts such as titles. They typically use n around 5 to 9, which is large enough that most shingles are rare. As a rule of thumb, pick n so that a random pair of unrelated documents shares very few shingles, and check the choice on a few pairs whose similarity you already know.
Normalize before you shingle
Two documents that differ only in capitalization or spacing should not look different. The shingles function above lowercases the text and splits on whitespace. Real pipelines often go further:
- Strip punctuation.
- Collapse repeated whitespace.
- Remove markup such as HTML tags.
Apply the same normalization to every document. Different normalization on two documents makes their sets differ for reasons that have nothing to do with content.
Sets, not bags
A set holds each shingle once. If a phrase appears five times in a document, it still counts as one element. This is usually what you want for near-duplicate detection, but it means repetition is invisible. A document that repeats one sentence 100 times has the same shingle set as a document that says it once.
Edge cases
- Documents shorter than n words. The range
range(len(words) - n + 1)is empty, so the shingle set is empty. Computingjaccardon two empty sets divides by zero. Guard against this, or choose a smaller n for short inputs. - Memory. A document of L words produces about L shingles, each holding n words. Storing the shingle strings for millions of documents is expensive. Pipelines usually replace each shingle with a 32-bit integer from a hash function such as
zlib.crc32. Later chapters do this inside the MinHash code, so you only need the set of shingles here. - Hash collisions. Mapping shingles to 32-bit integers can make two different shingles collide. With a large collection this slightly raises the measured similarity. It is rarely a problem at the sizes where MinHash is used.
Exercise
A document has 100 words. You use word shingles with n = 4. How many shingles does it have, assuming no shingle repeats? If you change one word in the middle of the document, how many shingles change?
Show answer
There are 100 − 4 + 1 = 97 shingles. A word in the middle appears in 4 different windows, so 4 shingles are replaced by 4 new ones. The two sets share 93 shingles and have 97 + 4 = 101 in the union, so the Jaccard similarity is 93/101, about 0.92.