Implementing plagiarism detection with shingling and MinHash
I'm providing a Python implementation that breaks text into word shingles, computes MinHash signatures using multiple hash functions, and estimates Jaccard similarity from signatures to detect near-duplicates efficiently. The code includes an example comparing two documents for clarity.
Below is a minimal, self–contained implementation of shingling + MinHash in Python to detect near–duplicate documents. It breaks text into word n‑gram shingles, hashes them to integers, builds MinHash signatures with a family of random hash functions, and then estimates Jaccard similarity from the signatures.
import re
import random
from typing import List, Set, Tuple
def tokenize(text: str) -> List[str]:
"""Lowercase and split text into alphanumeric tokens."""
return re.findall(r"\w+", text.lower())
def get_shingles(text: str, n: int = 5) -> Set[int]:
"""
Convert text into a set of n‑word shingles.
Each shingle is hashed to an integer for compactness.
"""
tokens = tokenize(text)
shingles = set()
for i in range(len(tokens) - n + 1):
shingle = " ".join(tokens[i:i+n])
shingles.add(hash(shingle)) # or use a consistent hash function
return shingles
def jaccard_similarity(a: Set[int], b: Set[int]) -> float:
"""Exact Jaccard similarity between two sets."""
if not a and not b:
return 1.0
return len(a & b) / len(a | b)
def generate_hash_functions(num_funcs: int,
max_shingle_id: int,
seed: int = 42) -> List[Tuple[int, int]]:
"""
Generate 'num_funcs' random (a, b) coefficients for hash functions of the form:
h(x) = (a * x + b) % prime
"""
random.seed(seed)
prime = 4294967311 # a large prime > 2^32
hash_params = []
for _ in range(num_funcs):
a = random.randint(1, prime-1)
b = random.randint(0, prime-1)
hash_params.append((a, b))
return hash_params
def compute_minhash_signature(shingles: Set[int],
hash_params: List[Tuple[int, int]],
prime: int = 4294967311) -> List[int]:
"""
Compute MinHash signature: for each hash function, take min hash value over all shingles.
"""
signature = []
for a, b in hash_params:
min_hash = min(((a * s + b) % prime) for s in shingles) if shingles else prime
signature.append(min_hash)
return signature
def signature_similarity(sig1: List[int], sig2: List[int]) -> float:
"""
Approximate Jaccard similarity: fraction of matching components in the signatures.
"""
assert len(sig1) == len(sig2)
if not sig1:
return 1.0
matches = sum(1 for x, y in zip(sig1, sig2) if x == y)
return matches / len(sig1)
# Example usage
if __name__ == "__main__":
docs = [
"MinHash is a probabilistic technique for estimating Jaccard similarity.",
"MinHash is a probabilistic method for approximating the Jaccard index.",
"Completely different content with no overlap."
]
n = 3 # shingle size (number of words per shingle)
num_hashes = 128 # number of hash functions in the signature
shingle_sets = [get_shingles(doc, n) for doc in docs]
# Determine a maximum shingle id (for informational purposes)
max_shingle_id = max((max(s) for s in shingle_sets if s), default=0)
hash_funcs = generate_hash_functions(num_hashes, max_shingle_id)
signatures = [compute_minhash_signature(s, hash_funcs) for s in shingle_sets]
# Compare documents pairwise
for i in range(len(docs)):
for j in range(i+1, len(docs)):
exact = jaccard_similarity(shingle_sets[i], shingle_sets[j])
approx = signature_similarity(signatures[i], signatures[j])
print(f"Doc {i} vs Doc {j}: exact Jaccard={exact:.3f}, MinHash≈{approx:.3f}")
How it works:
get_shingles produces the set of all contiguous word n‑grams of length n from a document. Using sets turns the bag of shingles into a representation suitable for Jaccard similarity.
jaccard_similarity computes the exact Jaccard index |A∩B| / |A∪B| of two shingle sets.
generate_hash_functions creates a family of random linear hash functions (h_i(x) = (a_i x + b_i) \bmod p).
compute_minhash_signature applies each hash function to all shingles and records the minimum hash value. The resulting vector is the MinHash signature.
signature_similarity estimates the Jaccard similarity between two sets as the proportion of equal components in their signatures.
By comparing signatures instead of full shingle sets, you can efficiently detect near‑duplicates in large collections. You can adjust the shingle size n, the number of hash functions, and a similarity threshold to suit your application.