Papa Programmer
Lesson 09 of 36

Cleaning data and checking quality

9 min read

Optional

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.

python
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:

text
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.

python
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:

text
conflict: 'login page shows an error' has ['access', 'technical']
checked 2 distinct messages

The 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.

python
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:

text
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.

FindsMisses
Normalised comparisonExact copiesRewordings
Similarity scoreNear copiesSame meaning in different words
Label groupingDirect contradictionsA label that is wrong but consistent
Redaction patternsRegular personal dataNames and free-form details
Reading a sampleWrong labels and odd casesProblems too rare to appear in the sample
What each check finds
Remove repeatsKeep one copy of each message, and record what you removed.
Settle conflictsOne text with two labels needs a rule in the guide, not a coin toss.
Redact firstStrip personal data and secrets before training, because the model may keep them.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools