Preparing Text Data
Text looks ready to use: it is already a sequence of symbols. It is not. The same word can be stored as different bytes, a file can be decoded with the wrong encoding, a model expects exactly the tokens its own tokenizer produces, sequences in a batch must have one length, and a random split of reviews can put the same author's writing on both sides. This lesson prepares text for two kinds of models: classical ones (bag of words, TF-IDF; see Working with Text) and transformers, whose tokenizer does most of the work but not all of it. Text Data covers what text data is; Tokenization covers how subword tokenizers work.
Normalise carefully
Normalisation makes equal things equal. How far to go depends on the task and on the model:
| Step | Helps | Can hurt |
|---|---|---|
Unicode NFKC (fi to fi, full-width digits to ASCII) |
almost always | rarely |
fix mojibake (café back to café) |
always, at load time | never |
| collapse whitespace, strip control characters | almost always | code, poetry, tables |
| lowercasing | bag-of-words models, small data | named entities (Apple vs apple), cased transformer models |
| removing punctuation | topic classification | sentiment (great!!! vs great?), questions, code |
| removing stop words | TF-IDF topic models | negation (not good), transformers |
With a pretrained transformer, apply only the fixes in the first rows and leave casing and punctuation to its tokenizer: it was trained on raw text and expects it.
import re
import unicodedata
raw = [
"Café was GREAT!!! Would visit again", # UTF-8 bytes read as Latin-1
"The film was not good?", # full-width letters, ligature
"Delivery\ttook 3 days.\n", # tab, no-break space
]
def fix_mojibake(s):
try:
return s.encode("latin-1").decode("utf-8")
except (UnicodeEncodeError, UnicodeDecodeError):
return s # was not mojibake
def normalise(s):
s = fix_mojibake(s)
s = unicodedata.normalize("NFKC", s)
return re.sub(r"\s+", " ", s).strip()
for s in raw:
t = normalise(s)
print(repr(t))
print(" bag-of-words view:", re.findall(r"[a-z0-9]+", t.lower()))'Café was GREAT!!! Would visit again'
bag-of-words view: ['caf', 'was', 'great', 'would', 'visit', 'again']
'The film was not good?'
bag-of-words view: ['the', 'film', 'was', 'not', 'good']
'Delivery took 3 days.'
bag-of-words view: ['delivery', 'took', '3', 'days']
The mojibake is repaired (Café), the full-width letters and the fi ligature become plain The film, and the tab and no-break space collapse into single spaces. The bag-of-words view shows the price of aggressive cleaning: !!! and ? are gone, so GREAT!!! and the doubtful not good? lose their tone, and the simple [a-z0-9]+ pattern even cut café down to caf, because é is not in a-z. Normalisation code needs tests with non-English text too.
Note: encoding problems are best fixed where they start: read files with an explicit
encoding="utf-8"and record which sources used something else. Mixed languages are a similar issue: detect the language per document (a library such aslangdetect, or metadata), then route, filter or stratify by it; a model trained on one language scores badly on another without telling you.
Fixed lengths: truncation, padding and attention masks
A batch is a rectangular array, but sentences have different lengths. Truncation cuts long sequences to a maximum length; padding fills short ones with a special [PAD] id; the attention mask (1 = real token, 0 = padding) tells the model which positions to ignore. Here is the whole mechanism with a toy word-level vocabulary in NumPy:
import numpy as np
texts = ["the soup was cold", "great service", "the waiter forgot our order and the soup was cold"]
vocab = {"[PAD]": 0, "[UNK]": 1}
for t in texts[:2]: # vocabulary from training texts only
for w in t.split():
vocab.setdefault(w, len(vocab))
def encode(batch, max_len):
ids = [[vocab.get(w, 1) for w in t.split()][:max_len] for t in batch]
width = max(len(r) for r in ids)
input_ids = np.zeros((len(batch), width), dtype=int)
mask = np.zeros_like(input_ids)
for i, r in enumerate(ids):
input_ids[i, :len(r)] = r
mask[i, :len(r)] = 1
return input_ids, mask
ids, mask = encode(texts, max_len=6)
print("vocabulary size:", len(vocab))
print(ids)
print(mask)vocabulary size: 8
[[2 3 4 5 0 0]
[6 7 0 0 0 0]
[2 1 1 1 1 1]]
[[1 1 1 1 0 0]
[1 1 0 0 0 0]
[1 1 1 1 1 1]]
The vocabulary was built from the first two (training) texts only: 8 entries including [PAD] = 0 and [UNK] = 1. The third text is truncated to 6 tokens, and every word it has that was not in the training vocabulary becomes 1. The first two are padded with zeros, and the mask marks exactly the real positions: 4, 2 and 6 ones.
The model's own tokenizer (recorded)
A pretrained transformer only understands the ids of its own tokenizer: the same vocabulary, the same special tokens ([CLS], [SEP] for BERT), the same lowercasing rule. Always load the tokenizer that belongs to the model checkpoint. Transformers do not run in the browser, so this example is recorded in the course's Docker image with a tiny BERT:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
texts = ["The soup was COLD!", "Great service.", "The waiter forgot our order, and the soup was cold."]
batch = tok(texts, padding=True, truncation=True, max_length=10)
for t, ids in zip(texts, batch["input_ids"]):
print(tok.convert_ids_to_tokens(ids))
print("input_ids: ", batch["input_ids"][1])
print("attention_mask:", batch["attention_mask"][1])
print("vocabulary size:", tok.vocab_size, "| pad id:", tok.pad_token_id)
print("rarer words ->", tok.tokenize("unbelievably tasty"))['[CLS]', 'the', 'soup', 'was', 'cold', '!', '[SEP]', '[PAD]', '[PAD]', '[PAD]']
['[CLS]', 'great', 'service', '.', '[SEP]', '[PAD]', '[PAD]', '[PAD]', '[PAD]', '[PAD]']
['[CLS]', 'the', 'waiter', 'forgot', 'our', 'order', ',', 'and', 'the', '[SEP]']
input_ids: [101, 2307, 2326, 1012, 102, 0, 0, 0, 0, 0]
attention_mask: [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
vocabulary size: 30522 | pad id: 0
rarer words -> ['un', '##bel', '##ie', '##va', '##bly', 'ta', '##sty']
The tokenizer lowercases (this checkpoint is uncased), splits off !, . and , as tokens of their own, adds [CLS] (id 101) at the start and [SEP] (id 102) at the end, and pads to the longest sequence in the batch with id 0. The long sentence is truncated to 10 tokens, [SEP] included, so soup was cold is lost. In the mask of the second sentence, the five real tokens are 1 and the five pads 0. Words outside the 30,522-entry vocabulary are not unknown: WordPiece breaks them into known pieces marked ##.
Choose max_length from the data: look at the token-length distribution of the training texts and pick a length that covers most of them (say the 95th percentile), because truncation silently throws away the end of long documents. For long texts, alternatives are splitting into overlapping chunks or keeping the head and the tail.
Split by document, author or source
Texts by the same author share vocabulary, style, topics and often labels. A random split puts one author's reviews on both sides, and the model learns to recognise authors instead of sentiment. Paragraphs of the same document, messages of the same conversation and articles from the same site are the same situation. The example gives each of 40 authors a habit (a signature word) and a tendency to rate positively or negatively; the words that carry real sentiment are weak.
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import KFold, GroupKFold, cross_val_score
rng = np.random.default_rng(3)
pos, neg = ["tasty", "friendly", "fresh"], ["bland", "rude", "stale"]
filler = ["the", "food", "place", "table", "menu", "staff", "dinner", "visit"]
texts, labels, authors = [], [], []
for a in range(40):
lean = rng.random() # this author's positivity
for _ in range(12):
y = int(rng.random() < lean)
words = list(rng.choice(filler, 6)) + [f"habit{a}"] * 2
if rng.random() < 0.35: # weak true signal
words.append(rng.choice(pos if y else neg))
rng.shuffle(words)
texts.append(" ".join(words)); labels.append(y); authors.append(a)
labels, authors = np.array(labels), np.array(authors)
model = make_pipeline(TfidfVectorizer(), LogisticRegression(C=10, max_iter=1000))
random_cv = cross_val_score(model, texts, labels, cv=KFold(5, shuffle=True, random_state=0)).mean()
group_cv = cross_val_score(model, texts, labels, cv=GroupKFold(5), groups=authors).mean()
print(f"random split by review: {random_cv:.3f}")
print(f"split by author: {group_cv:.3f}")random split by review: 0.777
split by author: 0.671
Shuffled by review, cross-validation reports 0.777 accuracy; split by author it drops to 0.671. The difference is the author habit: with a random split, the model sees habit7 in training next to author 7's usual rating and uses it on the same author's held-out reviews. New authors have no such habit word in the vocabulary, so the honest estimate for them is the lower one.
Note also that the TfidfVectorizer sits inside the pipeline: its vocabulary and IDF weights are fitted on the training folds only, like any other fitted transformer.
Pitfalls
- Wrong decoding: read with an explicit encoding and repair mojibake at load time.
- Over-normalising for a pretrained model: lowercasing for a cased model, or stripping punctuation, removes what it was trained to read.
- A tokenizer from a different checkpoint: ids silently mean other words. Load tokenizer and model from the same name.
- Truncation without checking lengths: long documents lose their end, often where the conclusion is.
- Random splits of grouped text: split by author, document, conversation or source.
- Fitting the vocabulary on all texts: fit vectorizers inside the pipeline.
Practice
- For which tasks would you keep punctuation and case: (a) spam detection, (b) topic classification of news, (c) named-entity recognition, (d) sentiment of product reviews?
Answer
Keep them for (c), where capital letters mark names, and (d), where !!! and ? carry tone; usually also for (a), since spam often SHOUTS and uses runs of dollar signs. For (b), lowercasing and removing punctuation are generally harmless with bag-of-words models. With a pretrained transformer, keep the raw text in all four cases.
- 98% of your training texts are at most 180 tokens long, the longest is 2,300. What
max_lengthwould you choose, and what do you do with the long ones?
Answer
Around 192 or 256 covers almost everything with little padding. The few long texts are truncated, or, if their ends matter, split into chunks (with overlap) whose predictions are combined, or reduced to head plus tail.
Test yourself
What does the attention mask contain?
- The token ids
- 1 for real tokens and 0 for padding positions
- The attention weights of the model
- The label
You fine-tune a cased BERT model. Should you lowercase the text first?
- Yes, always
- No: use the raw text and the model's own tokenizer
- Only the first word
- Only for the test set
The string café appears in a dataset. What happened?
- A typo by the author
- UTF-8 bytes were decoded as Latin-1 (mojibake)
- The word is French slang
- The tokenizer failed
Why does a random split of reviews overestimate accuracy when authors have several reviews?
- Reviews are too short
- The model can recognise authors seen in training instead of learning the task
- TF-IDF needs more data
- Random splits are always pessimistic