Sub topic 11
When Not to Clean: Trade-offs by Task
Prerequisites
This chapter assumes you have read the earlier chapters of this tutorial. You should know the difference between lower() and casefold(). You should know what NFC, NFD, NFKC, and NFKD do. You should be able to strip combining accents with unicodedata. You should also be comfortable with a simple tokenise-then-filter pipeline in Python.
Cleaning removes information
Every cleaning step maps many different inputs to one output. That is the point: "Café" and "cafe" become one token, so counts and matches line up. The cost is that you can no longer tell the inputs apart. The mapping is not reversible, and once you have thrown a distinction away, no later step can bring it back.
So the question for each step is not "is this correct?" but "does my task ever need the distinction this step removes?" If it does, skip the step or apply it only to a copy of the text.
The table lists what each step discards and a text where that loss does damage.
| Step | What it discards | Where that hurts |
|---|---|---|
| Case folding | Capitalisation | "US" and "us", "Apple" and "apple", shouted emphasis |
| NFKC | Compatibility distinctions (superscripts, ligatures, width, trademark signs) | "H₂O" becomes "H2O", "m²" becomes "m2", "™" becomes "TM" |
| Accent stripping | Diacritics | Spanish "año" (year) and "ano" (anus), German "schön" and "schon" |
| Punctuation removal | Emphasis, emoticons, sentence boundaries | "great!!!", ":(", "Dr. Smith." |
| Stop word removal | Function words, including negations | "not good" becomes "good" |
| Whitespace collapse | Line and paragraph breaks | Poems, tables, code, chat turns |
Sentiment analysis: keep the small words and the shouting
Sentiment models depend on exactly the features that classic cleaning removes.
- Negation. Many stop word lists contain "not", "no", "nor", and "never". Removing them turns "not good" into "good" and flips the label.
- Punctuation. "Great!!!" is more intense than "Great." Emoticons such as
:(are made entirely of punctuation. - Capitalisation. "This is TERRIBLE" carries emphasis that "this is terrible" does not.
- Intensifiers. Words such as "very", "so", and "too" appear in some lists and change the strength of the opinion.
A reasonable sentiment pipeline normalises Unicode (so that one emoji or one accented letter always has one representation) and collapses whitespace. It keeps case, punctuation, and stop words. If you need a smaller vocabulary for a bag-of-words model, case folding is the first step to try, and you can test whether it hurts validation accuracy.
Named entity recognition: case and form are the signal
Named entity recognition (NER) finds names of people, places, and organisations. Its main clues are capitalisation and the surrounding words.
- Capitalisation separates "Apple" (a company) from "apple" (a fruit), and "May" (a name or month) from "may" (a verb).
- Stop words often sit inside entity names: "Bank of England", "The Hague", "Lord of the Rings". Removing them breaks the span.
- Accents are part of the correct spelling. "Zoë" and "Zoe" may be the same person to a human, but a gazetteer lookup or an evaluation against gold annotations expects the original form.
- Character offsets matter. NER output is usually evaluated by start and end positions in the original text. Any step that changes the length of the string (NFKC expanding "…" into "...", whitespace collapsing, deleting characters) moves those offsets. If you must clean, keep a map from cleaned positions back to original positions, or run NER on the original text and clean only afterwards.
For NER, apply at most NFC normalisation and leave everything else alone.
Search and retrieval: clean the index and the query the same way
Search is the task where aggressive cleaning pays off most. Users do not type accents consistently, do not capitalise, and expect "cafe" to find "Café". Typical choices are NFKC, case folding, and sometimes accent stripping.
Two rules matter more than any individual step.
- Apply the same pipeline to documents and queries. If the index was built with accents stripped and the query still has them, "café" never matches "cafe". This is the stop word list lesson from earlier chapters, applied to the whole pipeline.
- Be careful with stop words in phrase queries. Dropping "the" is harmless for most keyword searches. It destroys a query for the band "The Who", the phrase "to be or not to be" (every word is a stop word, so the query becomes empty), or the abbreviation "IT". Many search engines keep stop words in the index for this reason, or index two versions.
Accent stripping should depend on language. In French, stripping accents mostly merges spelling variants that users also confuse. In Spanish or German, it can merge distinct words. A common compromise is to index both the original and the stripped form, and to rank exact matches higher.
Modern pretrained models: let the model's tokeniser decide
Contextual models such as BERT-style transformers were trained on text that went through a specific tokeniser. Their vocabulary and their learned behaviour assume that preprocessing.
- Stop words carry the syntax the model reads. Removing them turns a grammatical sentence into a list of keywords the model never saw in training.
- Cased and uncased checkpoints exist as separate models. If you pick a cased model, do not lowercase the input. You would be feeding it text unlike its training data, and its capitalisation knowledge would go unused.
- Some tokenisers already apply Unicode normalisation and, for uncased models, case folding and accent stripping internally. Doing it yourself first is redundant, and doing it differently can cause mismatches.
The safe default is to clean only what is actually broken in your data (stray control characters, mixed Unicode forms, broken whitespace) and pass the rest through.
Deciding which steps to keep
The diagram turns the discussion above into a set of questions you can ask for each step.
A pipeline with switches
Instead of one fixed pipeline, define a configuration for each task. The code below builds on the pipeline from earlier chapters. It keeps punctuation as separate tokens, because the sentiment case needs it.
import re
import unicodedata
from dataclasses import dataclass
from typing import Optional
STOP_WORDS = {"the", "a", "an", "is", "of", "and", "to", "in"}
@dataclass(frozen=True)
class CleanConfig:
unicode_form: Optional[str] = "NFC"
fold_case: bool = False
strip_accents: bool = False
drop_stop_words: bool = False
def clean(text, cfg):
if cfg.unicode_form:
text = unicodedata.normalize(cfg.unicode_form, text)
if cfg.fold_case:
text = text.casefold()
if cfg.strip_accents:
decomposed = unicodedata.normalize("NFD", text)
kept = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
text = unicodedata.normalize("NFC", kept)
text = re.sub(r"\s+", " ", text).strip()
tokens = re.findall(r"\w+|[^\w\s]", text)
if cfg.drop_stop_words:
tokens = [t for t in tokens if t.casefold() not in STOP_WORDS]
return tokens
SENTIMENT = CleanConfig()
NER = CleanConfig()
SEARCH = CleanConfig(
unicode_form="NFKC",
fold_case=True,
strip_accents=True,
drop_stop_words=True,
)
print(clean("This is NOT good!!!", SENTIMENT))
# ['This', 'is', 'NOT', 'good', '!', '!', '!']
print(clean("Apple hired Zo\u00eb in Paris.", NER))
# ['Apple', 'hired', 'Zoë', 'in', 'Paris', '.']
print(clean("The Caf\u00e9 in the \ufb01eld", SEARCH))
# ['cafe', 'field']Some details of the code are worth noting.
- Unicode normalisation runs first in every configuration, because even the "do nothing" tasks should not see two different encodings of the same letter.
- The stop word check uses
t.casefold(), so the list works whether or not case folding ran earlier. If you remove that call and keep case, "The" at the start of a sentence slips through a lowercase list. - The tokeniser pattern
\w+|[^\w\s]keeps punctuation as tokens. In Python'sremodule, combining marks are not word characters. Text left in NFD form, with no recomposition step, would be split at its accents. This is another reason to normalise to NFC before tokenising. - The sentiment example keeps "NOT", the exclamation marks, and "is". Applying the
SEARCHconfiguration to the same sentence would leave only['not', 'good', '!', '!', '!']. Here "not" survives only because it is not in this small stop word list. With a typical library list, it would be gone.
Common errors
- Using one pipeline for every task. A cleaning function copied from a search project and reused for sentiment is the most frequent cause of silent accuracy loss.
- Cleaning before measuring. Treat each step as a hyperparameter. Run the task with and without the step on a validation set, and keep the step only if the metric improves or stays level while the vocabulary shrinks.
- Cleaning the training data but not the inputs at prediction time, or the reverse. Mismatched preprocessing between training and serving makes a model appear to work in testing and fail in production.
- Throwing away the original text. Store the raw text next to the cleaned version. You will want it for debugging, for display to users, and for trying a different pipeline later.
- Trusting a library's stop word list. Print the list and read it. Check for negations, question words, and domain terms (for example "IT", "US", "can" in a legal context).
- Applying language-specific rules to all languages. Accent stripping, stop word lists, and case folding assume a language. For multilingual data, either detect the language per document or use the least destructive pipeline.
Exercises
Exercise
A team builds a review sentiment classifier. Their pipeline applies NFKC, case folding, accent stripping, punctuation removal, and a standard English stop word list. Accuracy is lower than a baseline that only normalises to NFC. Name three specific pieces of information the pipeline removes that could explain the drop.
Show answer
Any three of: negations such as "not" and "no" are in standard stop word lists, so "not good" becomes "good" and the polarity flips; punctuation removal drops emphasis ("!!!") and emoticons such as ":("; case folding removes capitalised emphasis ("TERRIBLE"); stop word removal can drop intensifiers such as "very" and "too". The fix is to keep case, punctuation, and stop words and normalise only to NFC.
Exercise
A search index was built with the SEARCH configuration from this chapter (NFKC, case folding, accent stripping, stop words dropped). A user queries "Café" using only NFC normalisation. Will the query match a document containing "Café"? Explain, and say what to change.
Show answer
No reliable match. The indexed token is "cafe" (folded and stripped), but the query token is "Café" (case and accent kept), so the strings differ. The query must go through the same pipeline as the documents. Applying the SEARCH configuration to the query turns it into "cafe" and the lookup succeeds.
Exercise
You run NER on text cleaned with NFKC, and the predicted entity spans are shifted a few characters from the gold annotations. Give one cause and two ways to avoid it.
Show answer
NFKC can change the string length (for example "…" becomes "...", and the ligature "fi" becomes "fi"), and whitespace collapsing also shifts positions, so offsets computed on the cleaned text no longer line up with the original. Avoid it by running NER on the original text and cleaning only afterwards, or by keeping a mapping from cleaned positions back to original positions. Skipping length-changing steps for NER also works.