Duplicate Detection
Duplicates enter datasets in many ways: a form submitted twice, two systems merged, a retried API call, a log replayed after a crash, the same photo uploaded by two users, a web page scraped from two URLs. They do three kinds of damage. They over-weight some samples, so the model cares more about them. They leak between training and test sets, so the test score measures memory rather than generalisation. And when the copies disagree, they reveal conflicting labels. This lesson finds exact duplicates, duplicates by key, near-duplicates in text and images, and duplicates that cross a split.
Exact duplicates and duplicates by key
import pandas as pd
customers = pd.DataFrame({
"customer_id": [101, 102, 103, 103, 104, 105, 106],
"name": ["Ana Le", "Ben Ng", "Cai Tran", "Cai Tran", "Dev Rao", "ana le ", "Eve Ho"],
"email": ["ana@ex.com", "ben@ex.com", "cai@ex.com", "cai@ex.com", "dev@ex.com", "ANA@ex.com", "eve@ex.com"],
"city": ["Hanoi", "Hue", "Da Nang", "Da Nang", "Hanoi", "Hanoi", "Hue"],
"churned": [0, 1, 0, 0, 1, 1, 0],
})
print("exact duplicate rows:", int(customers.duplicated().sum()))
print("duplicate customer_id:", customers.loc[customers["customer_id"].duplicated(keep=False), "customer_id"].tolist())
key = customers["email"].str.strip().str.lower()
same_person = customers[key.duplicated(keep=False)]
print()
print("same email after normalising:")
print(same_person)exact duplicate rows: 1
duplicate customer_id: [103, 103]
same email after normalising:
customer_id name email city churned
0 101 Ana Le ana@ex.com Hanoi 0
2 103 Cai Tran cai@ex.com Da Nang 0
3 103 Cai Tran cai@ex.com Da Nang 0
5 105 ana le ANA@ex.com Hanoi 1
duplicated() finds the copy of customer 103, a classic double insert. But customers 101 and 105 are almost certainly the same person too ("Ana Le" and "ana le ", the same email in different case), registered twice with two ids. Plain duplicated() misses them, and worse: one copy says she churned and the other that she did not. That is a label conflict, and it must be resolved (which record is current?) before training.
The general recipe: decide which columns identify "the same thing" (here, the email), normalise them (trim spaces, lower-case, remove punctuation, standardise formats), and then look for duplicates on the normalised key.
Near-duplicate text
Text often repeats with small changes: a template with a different name, a review posted twice with a typo fixed, an article syndicated by several sites. Normalising and then measuring similarity finds them. The standard library's difflib gives a similarity ratio between 0 and 1:
import re
from difflib import SequenceMatcher
from itertools import combinations
reviews = [
"Great kettle, boils fast. Love it!",
"great kettle - boils fast, love it",
"Stopped working after two weeks.",
"The kettle is great and boils fast.",
"Stopped working after 2 weeks!!",
]
def norm(t):
t = t.lower().replace("2", "two")
return re.sub(r"[^a-z ]+", " ", t).split()
scores = []
for i, j in combinations(range(len(reviews)), 2):
r = SequenceMatcher(None, " ".join(norm(reviews[i])), " ".join(norm(reviews[j]))).ratio()
scores.append((r, i, j))
for r, i, j in sorted(scores, reverse=True)[:4]:
print(f"{i} ~ {j} similarity {r:.2f}")2 ~ 4 similarity 1.00
0 ~ 1 similarity 1.00
1 ~ 3 similarity 0.58
0 ~ 3 similarity 0.58
Pairs 0 ~ 1 and 2 ~ 4 become identical after normalising (similarity 1.00): the same review with different punctuation and spelling. Review 3 says something similar to review 0 in other words: a paraphrase, not a duplicate, and its clearly lower score reflects that. A threshold (say 0.9) separates the two cases here; on real data you set it by looking at pairs near the threshold. Comparing every pair is fine for hundreds of texts but grows with the square of the dataset size; large-scale deduplication uses hashing tricks (MinHash, locality-sensitive hashing) or embeddings to compare only likely pairs.
Near-duplicate images
A resized, recompressed or slightly brightened photo has completely different bytes, so a file hash (as in the media layouts lesson) misses it. A perceptual hash looks at the picture instead. The simplest, the average hash, shrinks the image to 8 × 8 grey pixels and records which pixels are brighter than the average: 64 bits that survive small changes. The number of differing bits (the Hamming distance) measures how different two images look:
import numpy as np
from skimage import data
from skimage.color import rgb2gray
from skimage.transform import resize
def average_hash(img):
gray = rgb2gray(img) if img.ndim == 3 else img / 255.0
small = resize(gray, (8, 8), anti_aliasing=True)
return (small > small.mean()).flatten()
camera = data.camera()
variants = {
"camera, brighter": np.clip(camera.astype(int) + 40, 0, 255).astype(np.uint8),
"camera, half size": (resize(camera, (256, 256), anti_aliasing=True) * 255).astype(np.uint8),
"camera, mirrored": camera[:, ::-1],
"coins (another photo)": data.coins(),
"astronaut (another photo)": data.astronaut(),
}
h0 = average_hash(camera)
for name, img in variants.items():
print(f"{name:26} differing bits: {int((average_hash(img) != h0).sum()):2} of 64")camera, brighter differing bits: 0 of 64
camera, half size differing bits: 0 of 64
camera, mirrored differing bits: 40 of 64
coins (another photo) differing bits: 32 of 64
astronaut (another photo) differing bits: 30 of 64
The brighter and the half-size copies get exactly the same hash (0 differing bits): near-duplicates. The unrelated photos differ in about half of the 64 bits, as two unrelated images would, and the mirrored copy differs in even more. Production systems use stronger perceptual hashes or embedding similarity, but the idea is the same: compare what the image looks like, not its bytes. Note that a mirrored copy, a common augmentation, is not caught by this hash; whether it counts as a duplicate depends on the task.
Duplicates across the split
The most damaging duplicates are those shared by the training and the test set, because they make the evaluation dishonest. This experiment copies part of the test set into the training set, as an accidental merge of two exports might, and compares a 1-nearest-neighbour classifier's test score:
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
model = KNeighborsClassifier(n_neighbors=1)
print("honest test accuracy:", round(model.fit(X_tr, y_tr).score(X_te, y_te), 3))
rng = np.random.default_rng(0)
for share in [0.25, 0.5]:
leak = rng.choice(len(X_te), int(share * len(X_te)), replace=False)
X_leaky, y_leaky = np.vstack([X_tr, X_te[leak]]), np.concatenate([y_tr, y_te[leak]])
acc = model.fit(X_leaky, y_leaky).score(X_te, y_te)
print(f"{share:.0%} of test copied into training: accuracy {acc:.3f}")
train_rows = {row.tobytes() for row in X_leaky}
print("test rows found in the (last) training set:", sum(row.tobytes() in train_rows for row in X_te))honest test accuracy: 0.722
25% of test copied into training: accuracy 0.778
50% of test copied into training: accuracy 0.815
test rows found in the (last) training set: 27
A 1-nearest-neighbour model on the unscaled wine data scores 0.722 on the 54 test wines. Copying a quarter of them into the training set raises the score to 0.778, half of them to 0.815: every copied wine now finds itself in the training set at distance 0 and is answered correctly. Nothing about the model improved; the test simply got easier. The check finds all 27 leaked rows. The check in the last line (hash every training row, look up every test row) is cheap and belongs in every evaluation pipeline. Beyond exact rows, split by group whenever the same entity can appear several times: the same patient, customer, speaker, product or source video must sit entirely in training or entirely in test. Data Preparation covers group splits.
Pitfalls
- Deduplicating on all columns only: real duplicates often differ in an id, a timestamp or a spelling. Choose an identifying key and normalise it.
- Deleting blindly: two identical rows can be two real events (two identical purchases on the same day). Know the grain before deleting.
- Ignoring label conflicts: copies with different labels need a decision rule (latest record, majority, expert review).
- Deduplicating after splitting: remove duplicates, or group them, before the train/test split, then check for cross-split overlap.
Practice
- A dataset of product listings has 100,000 rows. 3,000 titles appear more than once, and half of those repeated titles come with different prices. What do you check before deduplicating?
Answer
Whether a repeated title means the same product: different sellers can list the same product at different prices (not duplicates), or the same listing may have been scraped twice at different times (duplicates; keep the latest). Look at seller id, listing id and timestamp, and decide the grain (one row per listing, or per product).
- In the image example, which hash would you need to also catch mirrored copies?
Answer
Compute the hash of the image and of its mirror, and compare a new image against both (or use the smaller of the two distances). Embedding-based similarity from a model trained with flip augmentation is also largely mirror-invariant.
Test yourself
Why does df.duplicated() miss the customer stored as 'Ana Le' and as 'ana le '?
- It only checks the first column
- The rows differ in id, spelling and case, so they are not exact copies
- pandas ignores text columns
- The emails are different people
What does a duplicate shared by the training and test sets do to the test score?
- Lowers it
- Inflates it, because the model has seen those test items
- Nothing
- Makes it impossible to compute
Why is a perceptual hash used for images instead of a SHA-256 of the file?
- It is more secure
- It changes little when the image is resized or recompressed, so near-duplicates stay close
- It is longer
- It works only on greyscale images
Two copies of the same customer have different churn labels. This is…
- An outlier
- A label conflict that must be resolved before training
- A missing value
- Harmless