Cleaning data and checking quality
9 min read
Why cleaning pays off
Training on 2,000 examples is a vote. A duplicated example gets extra votes. A conflicting label splits the vote. A leaked email address might later come back out of the model. Cleaning is the cheapest way to improve a project, because it costs minutes and every later step benefits.
Do the checks below on the training set before each run, and on the validation and test sets too.
Duplicates and near duplicates
Exact duplicates are easy to find: compare the text after you normalise it, by lowercasing and collapsing spaces. Near duplicates differ by a few characters, such as a greeting or a trailing question mark. They matter for two reasons. They overweight one case in training, and when one copy lands in training and another in the test set, the test score is inflated.
The program below finds both kinds in a few messages.
import difflib
import re
messages = [
"I was charged twice this month",
"i was charged twice this month",
"I was charged twice this month!",
"Cannot reset my password",
"Cannot reset my password please",
"Export to CSV does nothing",
]
def normal(text):
return re.sub(r"[^a-z0-9 ]", "", re.sub(r"\s+", " ", text.lower())).strip()
seen = {}
for i, text in enumerate(messages):
key = normal(text)
if key in seen:
print(f"{i} duplicates {seen[key]}: {text!r}")
else:
seen[key] = i
keys = list(seen)
for a in range(len(keys)):
for b in range(a + 1, len(keys)):
ratio = difflib.SequenceMatcher(None, keys[a], keys[b]).ratio()
if ratio > 0.85:
print(f"near duplicates ({ratio:.2f}): {keys[a]!r} and {keys[b]!r}")It prints:
1 duplicates 0: 'i was charged twice this month'
2 duplicates 0: 'I was charged twice this month!'
near duplicates (0.87): 'cannot reset my password' and 'cannot reset my password please'Normalising catches the second and third messages as exact copies of the first. The pairwise comparison flags the password message and its copy with "please" added, at a similarity of 0.87. You choose the threshold, and a person should look at what it flags. It compares every pair, which is fine for thousands of examples and slow for millions. At that scale, people use hashing or embedding based methods, but the idea is the same. Keep one copy, and write the removals to a file so you can explain them later.
Conflicting labels
The same text with two different labels is a direct contradiction. Find them by grouping on the normalised text.
from collections import defaultdict
rows = [
("Login page shows an error", "access"),
("login page shows an error", "technical"),
("Why did my invoice go up?", "billing"),
("Why did my invoice go up?", "billing"),
]
labels = defaultdict(set)
for text, label in rows:
labels[text.lower()].add(label)
for text, found in labels.items():
if len(found) > 1:
print(f"conflict: {text!r} has {sorted(found)}")
print("checked", len(labels), "distinct messages")It prints:
conflict: 'login page shows an error' has ['access', 'technical']
checked 2 distinct messagesThe first message has two labels. A person has to settle it with a rule in the labelling guide, as Collecting and creating examples explained. The repeated invoice message is a plain duplicate and carries one label, so it raises no conflict.
Personal data and secrets
Remove what the task does not need: email addresses, phone numbers, account numbers, access tokens and passwords. Patterns catch the regular ones.
import re
patterns = {
"email": r"[\w.+-]+@[\w-]+\.[\w.]+",
"phone": r"\+?\d[\d ()-]{7,}\d",
"token": r"\b(?:sk|key|tok)_[A-Za-z0-9]{8,}\b",
}
def redact(text):
for name, pattern in patterns.items():
text = re.sub(pattern, f"[{name}]", text)
return text
print(redact("Write to ana@example.test or call +49 30 1234567, key tok_AbC12345xyz"))It prints:
Write to [email] or call [phone], key [token]Patterns miss names, addresses and anything written in an unusual way, so treat redaction as a first pass and sample the result. Replace each value with a marker such as [email] and not with nothing, so the sentence keeps its shape. Be careful with the claim that deleting a record fixes things. A trained model can memorise parts of its data, so removing a source record later does not guarantee the model has forgotten it. Clean before training, not after.
Balance and coverage
Count the labels and the kinds of message. If 90 percent of examples are billing, the model learns that guessing billing is a good habit, as Define the task and what success means showed. Add examples of the rare labels, or weigh them more in training. Check coverage too: short and long messages, other languages, typing errors and the hard cases you listed at the start.
Read a sample by eye
Scripts catch format and repeat problems. They cannot tell whether a label is correct. Read a sample of fifty or so examples, taking some from every label and from the shortest and longest. Note each problem and its cause. A few wrong labels are normal. A pattern, such as every message that mentions a refund labelled access, points to a flaw in the labelling guide that more data will not fix.
| Finds | Misses | |
|---|---|---|
| Normalised comparison | Exact copies | Rewordings |
| Similarity score | Near copies | Same meaning in different words |
| Label grouping | Direct contradictions | A label that is wrong but consistent |
| Redaction patterns | Regular personal data | Names and free-form details |
| Reading a sample | Wrong labels and odd cases | Problems too rare to appear in the sample |
Why remove duplicates?
The same ticket appears 40 times in the file.
Repeated examples are over-weighted and can sit in both training and test data.
What should you do with wrong labels?
A sample review shows 6% of labels are wrong.
Noisy labels cap the quality of the tuned model.
How do you check personal data?
Tickets contain emails and phone numbers.
A model can memorise rare strings, so the safest time to remove private data is before training.
Your reading position is saved
0 of 36 complete
Lesson complete
Cleaning data and checking quality
Up next