A very timely question! Deduplicating datasets, especially those used for training sentence transformers (or any NLP model), is crucial for several reasons:
Reduces overfitting: Duplicate examples can make your model biased towards those specific examples, rather than generalizing well to unseen data.
Saves computational resources: Training on a smaller, unique dataset is faster and more efficient.
Improves evaluation metrics: By removing duplicates, your evaluation metrics (e.g., accuracy, F1-score) become more reliable and representative of real-world performance.
When working with Hugging Face (HF) datasets, particularly those intended for sentence transformers (e.g., sentence similarity, text classification), here are the most common ways to deduplicate:
Method 1: Exact String Matching (Simple but Effective)
Remove rows with identical text in the columns of interest (e.g., text, sentence1, sentence2, depending on your dataset structure). You can do this using:
python
import pandas as pd
from datasets import Dataset, load_dataset
# Load your dataset (example: 'glue', 'stsb_multi_mt')
dataset = load_dataset('glue', 'stsb_multi_mt', split='train')
# Convert to pandas for easy manipulation
df = pd.DataFrame(dataset)
# Deduplicate based on exact string match (e.g., on 'sentence1' and 'sentence2')
df_dedup = df.drop_duplicates(subset=['sentence1', 'sentence2'])
# Convert back to HF Dataset
dedup_dataset = Dataset.from_pandas(df_dedup)
Method 2: Fuzzy Matching (for near-duplicates)
Sometimes, duplicates aren't exact but very similar (e.g., differing only in punctuation or minor typos). Use fuzzy matching techniques:
python
from fuzzywuzzy import fuzz, process
import pandas as pd
from datasets import Dataset
# Assuming 'df' is your DataFrame as before
# Define a function to check similarity (threshold: 90 means 90% similar)
def is_duplicate(text1, text2, threshold=90):
return fuzz.ratio(text1, text2) > threshold
# Apply fuzzy matching (slower than exact matching, be patient)
duplicates_mask = []
for i, row in df.iterrows():
is_dup = False
for j, prev_row in df.iloc[:i].iterrows():
if is_duplicate(row['sentence1'], prev_row['sentence1']) and \
is_duplicate(row['sentence2'], prev_row['sentence2']):
is_dup = True
break
duplicates_mask.append(not is_dup)
df_dedup_fuzzy = df[duplicates_mask]
# Convert back to HF Dataset
dedup_fuzzy_dataset = Dataset.from_pandas(df_dedup_fuzzy)
Note: Fuzzy matching is computationally expensive. For large datasets, consider sampling or parallelizing the process.
Leverage sentence embeddings (the very purpose of sentence transformers!) to identify semantically similar sentences, even if wording differs:
Encode sentences using a pre-trained sentence transformer (e.g., all-MiniLM-L6-v2).
Compute cosine similarity between embeddings.
Threshold similarity scores to decide what's a duplicate.
python
from sentence_transformers import SentenceTransformer, util
import torch
import numpy as np
# Load pre-trained sentence transformer model
model = SentenceTransformer('all-MiniLM-L6-v2')
# Extract sentences of interest (e.g., 'sentence1' and 'sentence2')
sentences1 = dataset['sentence1']
sentences2 = dataset['sentence2']
# Encode sentences (do this in batches if OOM)
embeddings1 = model.encode(sentences1, convert_to_tensor=True)
embeddings2 = model.encode(sentences2, convert_to_tensor=True)
# Stack embeddings for cosine similarity computation
all_embeddings = torch.cat([embeddings1, embeddings2], dim=0)
# Compute cosine similarity matrix
cosine_scores = util.cos_sim(all_embeddings, all_embeddings)
# Identify duplicates based on a threshold (e.g., 0.95)
threshold = 0.95
duplicate_mask = np.tril(cosine_scores.numpy(), k=-1) > threshold # Lower triangle, excluding self
# Get indices of duplicates
dup_indices = np.argwhere(duplicate_mask)
# Since we're comparing sentence1 & sentence2 together, adjust logic:
# For simplicity, let's deduplicate only based on sentence1 embeddings
sentence1_embeddings = embeddings1.numpy()
from sklearn.metrics.pairwise import cosine_similarity
sim_matrix = cosine_similarity(sentence1_embeddings)
np.fill_diagonal(sim_matrix, 0) # Ignore self-comparison
dup_rows = np.where(sim_matrix > threshold)[0]
# Deduplicate
df_dedup_semantic = df.drop(dup_rows, axis=0)
# Convert back to HF Dataset
dedup_semantic_dataset = Dataset.from_pandas(df_dedup_semantic)
Method 4: MinHashLSH (for very large datasets)
For extremely large datasets where the above methods are too slow, use Locality Sensitive Hashing (LSH) with MinHash:
Hash sentences into multiple "buckets" using MinHash.
Consider as duplicates sentences that fall into the same bucket multiple times.
Here's a simplified example using datasketch:
python
from datasketch import MinHash, MinHashLSH
# Example: Deduplicate on 'sentence1'
sentences = dataset['sentence1']
# Initialize LSH with 5 permutations (tune this param)
lsh = MinHashLSH(threshold=0.5, num_perm=5)
# Insert sentences into LSH
for i, sentence in enumerate(sentences):
minhash = MinHash(num_perm=5)
for word in sentence.split(): # Simple tokenizer
minhash.update(word.encode('utf8'))
lsh.insert(i, minhash)
# Query LSH to find duplicates
duplicates = set()
for i in range(len(sentences)):
result = lsh.query(MinHash(num_perm=5, hashvalues=lsh.keys[i]))
if len(result) > 1: # More than self
duplicates.update(result)
# Deduplicate
df_dedup_lsh = df.drop(list(duplicates), axis=0)
# Convert back to HF Dataset
dedup_lsh_dataset = Dataset.from_pandas(df_dedup_lsh)
Recap & Recommendations:
Start with Exact String Matching (Method 1). It's fast and often removes 20-50% of duplicates.
If you suspect near-duplicates (typos, rewordings), apply Fuzzy Matching (Method 2) on a sampled subset to gauge its effectiveness.
For semantically similar but not identical sentences, use Embeddings-based Similarity (Method 3). This is more computationally intensive but powerful.
MinHashLSH (Method 4) is your friend for huge datasets (>100K sentences) where other methods are infeasible.
Always:
Monitor dataset size reduction after deduplication.
Spot-check removed duplicates to ensure you're not throwing away valuable diversity.
Validate your model's performance post-deduplication; sometimes, a smaller, cleaner dataset yields better generalization!
Happy deduplicating, and may your sentence transformer models perform even better on cleaner data!