Text Augmentation
Flipping an image rarely changes what it shows; changing one word of a sentence easily does. "The food was not bad" and "The food was not good" differ by one token and mean opposite things. That is why text augmentation is used more carefully than its image and audio cousins: it helps most when labelled data is scarce (a few hundred examples of a rare intent, a low-resource language), and every method needs a guard that the label survives. This lesson covers the four methods of the curriculum: controlled synonym replacement, token masking, back-translation and paraphrasing with semantic validation, and the splitting rule that applies to all of them. Text basics are in Text Data and Preparing Text Data.
The methods
| Method | How | Risk to the label | Cost |
|---|---|---|---|
| controlled synonym replacement | swap a few words for synonyms from a curated list; never touch protected words | low with a curated list, high with an automatic thesaurus | tiny |
| token masking / deletion | replace random tokens with [MASK] (or drop them) |
low when the rate is small (10 to 15 %) | tiny |
| back-translation | translate to another language and back with a translation model | medium: meaning can drift | a model call per sentence |
| paraphrasing | generate rewrites with a language model, keep only those that pass a similarity check | medium: needs validation | a model call, plus the check |
Controlled synonym replacement
"Controlled" means three things: the synonyms come from a list someone checked for this domain ("cheap" is a fine synonym for "inexpensive" in shopping reviews, not in a review of furniture quality), protected tokens are never changed (negations, numbers, names, the words the label hinges on), and only a small share of the eligible words is changed per sentence.
import random
SYNONYMS = {
"quick": ["fast", "speedy"], "delivery": ["shipping"], "friendly": ["kind", "helpful"],
"staff": ["team", "employees"], "big": ["large"], "room": ["space"],
"slow": ["sluggish"], "food": ["meal", "dish"],
}
PROTECTED = {"not", "no", "never", "good", "bad", "great", "terrible"} # negations and sentiment words
def synonym_replace(sentence, rng, p=0.5):
out = []
for word in sentence.split():
w = word.lower()
if w in SYNONYMS and w not in PROTECTED and rng.random() < p:
out.append(rng.choice(SYNONYMS[w]))
else:
out.append(word)
return " ".join(out)
rng = random.Random(0)
reviews = [("quick delivery and friendly staff", "pos"),
("the food was not good and the room was big", "neg"),
("slow delivery , never again", "neg")]
for text, label in reviews:
variants = {synonym_replace(text, rng) for _ in range(4)} - {text}
print(f"[{label}] {text}")
for v in sorted(variants):
print(" ->", v)[pos] quick delivery and friendly staff
-> fast delivery and kind team
-> quick delivery and helpful staff
-> quick delivery and kind employees
-> speedy delivery and kind staff
[neg] the food was not good and the room was big
-> the dish was not good and the space was large
-> the food was not good and the room was large
[neg] slow delivery , never again
-> slow shipping , never again
-> sluggish delivery , never again
Each review yields a few variants, and none of them touches "not", "good" or "never", so the sentiment stays intact. An automatic thesaurus (WordNet, embedding neighbours) offers far more synonyms, but also antonyms and wrong senses: the nearest embedding neighbour of "good" is often "bad", because both appear in the same contexts. Use it only with a review step or a validation filter.
Token masking
Masking replaces a small random share of tokens with a placeholder, the same corruption a masked language model like BERT is trained with. It teaches the model not to rely on any single word, which helps against typos and rare words. Deleting tokens instead of masking them is a variant.
import random
def mask_tokens(sentence, rng, rate=0.15, mask="[MASK]", protected=()):
tokens = sentence.split()
return " ".join(mask if (t not in protected and rng.random() < rate) else t for t in tokens)
rng = random.Random(3)
text = "the battery lasts two full days and charging takes under an hour"
for _ in range(3):
print(mask_tokens(text, rng))
counts = [mask_tokens(text, rng).split().count("[MASK]") for _ in range(1000)]
print("average masked tokens:", sum(counts) / len(counts), "of", len(text.split()))the battery lasts two full [MASK] [MASK] charging takes under an hour
the battery lasts two full days and charging takes [MASK] an hour
the [MASK] lasts two full days and charging takes under an hour
average masked tokens: 1.735 of 12
At a 15 % rate, 1.735 of the 12 tokens are masked on average over 1,000 draws (the expected value is 12 × 0.15 = 1.8). Real pipelines mask subword tokens produced by the model's tokenizer, and the [MASK] string must be the tokenizer's own mask token.
Back-translation and paraphrasing
Back-translation sends a sentence through a translation model to a pivot language and back: "The delivery was quick but the box was damaged" may return as "Delivery was fast, but the box was damaged". The result is fluent and differently worded, which is exactly what simple word swaps cannot produce. Paraphrasing asks a language model directly for rewrites. Both need a model (a cloud API or a local translation model, see the NLP course), and both can drift: a pivot language without grammatical negation markers, or a creative paraphrase, can quietly change the meaning. So generated text is validated before use:
- semantic similarity: embed original and rewrite with a sentence encoder and keep pairs above a cosine threshold (for example 0.85);
- label agreement: a classifier trained on the original data must still predict the original label for the rewrite;
- rules: numbers, names and negations must survive unchanged.
The idea of a similarity filter can be shown without any model download, using TF-IDF vectors as a crude stand-in for sentence embeddings:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
original = "the delivery was quick but the box was damaged"
candidates = [
"delivery was quick but the box was damaged", # good rewrite
"the shipping was fast but the box was damaged", # good, different words
"the delivery was quick and the box was perfect", # meaning changed
"i ordered shoes last week", # unrelated
]
vec = TfidfVectorizer().fit([original] + candidates)
sims = cosine_similarity(vec.transform([original]), vec.transform(candidates))[0]
for c, s in zip(candidates, sims):
print(f"{s:.2f} {'keep' if s >= 0.5 else 'drop'} {c}")0.97 keep delivery was quick but the box was damaged
0.73 keep the shipping was fast but the box was damaged
0.73 keep the delivery was quick and the box was perfect
0.00 drop i ordered shoes last week
The word-overlap measure keeps the light rewrite and drops the unrelated sentence, but it also illustrates the limits of a crude filter: the meaning-changing rewrite ("perfect") still shares most words with the original and scores 0.73, exactly as high as the good synonym rewrite. No threshold on this score can keep one and drop the other. A real sentence encoder handles synonyms much better, yet negation and polarity flips fool embeddings too, which is why label agreement and rules are checked as well.
The splitting rule: copies stay with their source
Augmented sentences are near-copies of their source. If the original lands in the test fold and its copy in the training fold, the model is tested on sentences it has effectively seen. The most dramatic way to see this is with labels that are pure noise: nothing can be learned, so any honest accuracy must stay near 50 %.
import random
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import KFold, GroupKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
rng = random.Random(0)
vocab = ("price screen battery camera delivery sound case light quick slow nice cheap strong weak "
"small large clean loud soft heavy").split()
SYN = {"quick": "fast", "nice": "pleasant", "cheap": "inexpensive", "large": "big", "loud": "noisy"}
sources = [" ".join(rng.sample(vocab, 6)) for _ in range(80)]
labels = [rng.randint(0, 1) for _ in sources] # random: there is nothing to learn
texts, y, groups = [], [], []
for i, (s, lab) in enumerate(zip(sources, labels)):
for k in range(4): # the original + 3 augmented copies
words = s.split()
if k:
words = [SYN.get(w, w) if rng.random() < 0.5 else w for w in words]
words[rng.randrange(len(words))] = "[MASK]"
texts.append(" ".join(words)); y.append(lab); groups.append(i)
model = make_pipeline(TfidfVectorizer(), KNeighborsClassifier(n_neighbors=1))
random_folds = cross_val_score(model, texts, y, cv=KFold(5, shuffle=True, random_state=0)).mean()
group_folds = cross_val_score(model, texts, y, cv=GroupKFold(5), groups=groups).mean()
print(f"rows: {len(texts)} from {len(sources)} sources")
print(f"random K-fold: accuracy {random_folds:.2f}")
print(f"grouped by source: accuracy {group_folds:.2f} (chance 0.50)")rows: 320 from 80 sources
random K-fold: accuracy 0.90
grouped by source: accuracy 0.46 (chance 0.50)
With copies scattered across folds, the nearest neighbour of a test sentence is usually its own augmented sibling with the same (random) label, and the score climbs to 0.90. Grouping by source gives 0.46, chance level within the noise of 80 sources, which is the truth for random labels. The safe workflow is: split the original data first (by source, author or document when needed), then augment only the training part, inside the training loop or after the split.
Pitfalls
- Unchecked synonyms: automatic thesauri produce antonyms and wrong senses; curate or validate.
- Touching what the label depends on: negations, sentiment words, entity names in named-entity tasks (and their labels' positions!), numbers in questions about quantities.
- Augmenting before splitting or scoring on augmented test data: both inflate the estimate.
- Too much synthetic text: a training set that is 90 % paraphrases learns the paraphraser's style. Keep augmented examples a minority, or weight them lower.
Practice
- For an intent classifier ("cancel order", "track order", "change address"), which words would you protect from synonym replacement?
Answer
The verbs and nouns that define the intent: "cancel", "track", "change", "address", "order", plus negations ("don't cancel"). Replacing "cancel" with a synonym like "stop" may be fine if the curated list says so, but replacing it with "change" would change the label.
- A back-translated review "the room was not clean" comes back as "the room was clean". How would each validation check catch it?
Answer
The rule check: a negation present in the original is missing. Label agreement: a sentiment classifier predicts the opposite label for the rewrite. Embedding similarity may not catch it, because the sentences share almost every word, which is why rule and label checks are needed.
Test yourself
Why are negation words usually protected in synonym replacement for sentiment data?
- They are too short
- Changing or dropping them can reverse the label
- Tokenizers cannot handle them
- They are rare
What does back-translation do?
- Reverses the word order
- Translates a sentence to another language and back to get a rewording
- Removes stop words
- Masks random tokens
Augmented copies are mixed into the data before a random K-fold split. What happens to the score?
- It is unbiased
- It is inflated, because near-copies of test sentences are in the training folds
- It drops to zero
- Nothing, augmentation is always safe
Why is a word-overlap similarity a weak filter for paraphrases?
- It is too slow
- It scores synonym rewrites low and can score meaning-changing edits high
- It needs a GPU
- It ignores word order only