AI Logic

Data Augmentation

EDA

Updated:

EDA diagram. Left: the flow for building training data (training sentences, split into words, pick one of four operations, apply the chosen operation, create n_aug sentences from each sentence, text classification model, loss). Right: an example sentence from the paper with synonym replacement (SR), random insertion (RI), random swap (RS), and random deletion (RD) applied, along with the formula n = α·l for the number of words changed.

What is EDA?

EDA (Easy Data Augmentation) is a data augmentation technique for text classification that applies four simple operations to the words of a sentence to create new sentences with the same label. It was proposed by Wei and Zou in 2019.

For images, new training data can be created without changing meaning through horizontal flips or crops. For text, rules for "meaning-preserving transformations" are hard to write, and methods using back-translation or language models take effort to implement and compute. EDA restricts itself to simple operations that need neither language model training nor external data, working with just a synonym dictionary.

The four operations are as follows, shown with the paper's example sentence (right of the top figure).

OperationWhat it doesExample (original: A sad, superior human comedy played out on the back roads of life.)
Synonym replacement (SR)Pick nn non-stop-words and replace each with a randomly chosen synonymA lamentable, superior human comedy played out on the backward road of life.
Random insertion (RI)Pick a non-stop-word and insert one of its synonyms at a random position in the sentence. Repeat nn timesA sad, superior human comedy played out on funniness the back roads of life.
Random swap (RS)Randomly pick two words in the sentence and swap them. Repeat nn timesA sad, superior human comedy played out on roads back the of life.
Random deletion (RD)Delete each word in the sentence with probability ppA sad, superior human out on the roads of life.

Stop words are words with little meaning that appear in nearly every sentence, such as "the" and "of" in English.

As an analogy, it is like studying for an exam by solving the same problem rephrased slightly each time. Learning that the answer stays the same even when the wording changes makes it harder to memorize specific word sequences by rote.

Synonym replacement had been used before, but the authors state that this paper is the first to comprehensively study random insertion, swap, and deletion as data augmentation. Sentences with swapped or deleted words look unnatural to humans, but most of the original words and their order remain, so they act as moderate noise that suppresses overfitting.

Procedure

For each sentence in the training data, do the following (left of the top figure).

  1. Split the sentence into words and count the number of words ll.
  2. Randomly choose one of the four operations (SR, RI, RS, RD).
  3. Apply the chosen operation. The number of changes nn for SR, RI, and RS and the probability pp of deleting each word in RD are set according to sentence length by the formula below.
  4. Repeat steps 2–3 to create naugn_{\mathrm{aug}} sentences from one original sentence.
  5. Give the created sentences the same label as the original, add them to the training data together with the original sentences, and train the model as usual.
n=α l,p=αn = \alpha\, l, \qquad p = \alpha

α\alpha is a parameter representing "what fraction of the words in a sentence to change." Longer sentences can absorb more changed words while keeping their meaning, so the number of changes is proportional to sentence length.

The paper takes synonyms from WordNet, an English thesaurus. The official implementation (eda_nlp) creates an equal number of sentences with each of the four operations from one original sentence, mixes them, selects naugn_{\mathrm{aug}} of them, and finally adds the original sentence. A separate α\alpha can also be specified for each operation (alpha_sr, alpha_ri, alpha_rs, p_rd).

The paper's implementation is for English: it lowercases sentences and removes non-alphabetic characters before splitting into words. For Japanese, words must be segmented with morphological analysis, and a Japanese thesaurus (such as Japanese WordNet) must be prepared. A stop word list is also needed for each language.

Choosing the parameters

The parameters to tune are the fraction of words changed, α\alpha, and the number of sentences generated per sentence, naugn_{\mathrm{aug}}. The paper recommends the following values by training set size.

Training sentencesα\alphanaugn_{\mathrm{aug}}
5000.0516
2,0000.058
5,0000.14
More0.14
  • α\alpha: In experiments using one operation at a time with α\alpha varied from 0.05 to 0.5, all four operations improved accuracy, and α=0.1\alpha = 0.1 was a good overall value. SR and RD reduced accuracy substantially at large α\alpha (replacing or deleting many words changes the meaning or makes the sentence unreadable). RS did well at α≤0.2\alpha \le 0.2 but declined at 0.3 and above (too many swaps scramble the word order). RI was stable across α\alpha because the original words and their order remain.
  • naugn_{\mathrm{aug}}: With small training sets, overfitting is likely, so generating more sentences improved accuracy more. With large training sets, generating more than 4 per sentence brought no improvement.

Why it works

The paper gives two reasons why EDA works.

  • Moderate noise prevents overfitting: Adding sentences that are close to but slightly different from the originals makes it harder for the model to memorize the word sequences of the training data.
  • It introduces new words: Synonym replacement and random insertion bring in words not in the training data. Even if a test sentence contains a synonym absent from the training data, it becomes easier to classify correctly.

Both effects are larger when training data is smaller.

The paper also checks whether labels are preserved. It fed test sentences, along with 9 EDA-augmented versions of each, into an RNN trained on Pro-Con classification and plotted the outputs of the last fully connected layer in 2D with t-SNE. The points for augmented sentences clustered closely around those of the originals, and the paper concludes that in most cases, EDA preserves the labels.

Random insertion inserts a synonym of a word in the sentence rather than a random word so as not to change the label. Inserting words related to the context makes it easier to preserve the original sentence's label.

Results reported in the paper

On five text classification tasks (SST-2 sentiment analysis, CR product reviews, SUBJ subjectivity/objectivity, TREC question types, and PC pro/con), a CNN and an RNN using LSTM were compared with and without EDA. Accuracy (%) is the average over the five tasks and over five random seeds.

Model500 sentences2,000 sentences5,000 sentencesFull
RNN75.383.786.187.4
RNN + EDA79.184.487.388.3
CNN78.685.687.788.3
CNN + EDA80.786.488.388.8
Average76.984.686.987.8
Average + EDA79.985.487.888.6

The average improvement was 0.8 points with the full data and 3.0 points with 500 sentences. Also, in experiments varying the fraction of training data from 1% to 100%, the best average accuracy without EDA was 88.3% using all the data, whereas with EDA, 88.6% was reached with only 50% of the data.

The paper also compares the preparation required by other text data augmentation methods.

MethodRequires training a language model etc.?Requires external data?
Back-translationYesSometimes
Contextual augmentation (replaces words predicted by a bidirectional language model)YesNo
Generating sentences with a VAE and discriminatorYesYes
Synonym replacement with nearest words in word embeddingsNoNo
EDANoNo

EDA uses a thesaurus (WordNet), but the paper does not count it as external data.

Practical considerations

  • The effect shrinks when training data is plentiful. On the paper's five tasks, the improvement with the full data was less than 1 point on average.
  • It may barely help large pretrained models. The paper cites a report that EDA gave almost no improvement with ULMFiT and suggests the same is likely for models such as BERT.
  • Sentences with changed labels may slip in. Deleting a negation or replacing a word with a "synonym" of different meaning can produce sentences that do not match their labels. The paper finds that labels are preserved overall, but for tasks where negation or word order determines meaning, check on validation data which operations to use.
  • Use the created sentences only during training. For evaluation and inference, feed the original sentences as is.

Do not make α\alpha too large. In the paper's experiments, SR and RD with large α\alpha did worse than not using them at all. Start with α=0.05\alpha = 0.05 to 0.10.1.

Comparison with other methods and how to choose

The following table compares text data augmentation methods from the same perspectives.

MethodHow sentences are createdRequirementsNaturalness of sentencesComputational cost
EDAReplacing, inserting, swapping, and deleting wordsThesaurusMay produce unnatural sentencesVery low
Back-translationTranslate into another language and back into the originalTranslation models in both directionsTend to be natural paraphrasesHigh (translation model inference)
Contextual augmentationReplace words with those a language model predicts from contextA trained language modelRelatively naturalModerate

Guidelines for choosing are as follows.

  • Training data is scarce and a quick try is wanted: Use EDA. It runs with a few dozen lines of code and a thesaurus, and the less training data there is, the more it helps.
  • Diverse sentences through natural paraphrases are wanted, and translation models are available: Use back-translation. Semi-supervised UDA also uses back-translation for text data augmentation.
  • Fine-tuning a large pretrained model: EDA's effect may be small, so first compare against results without augmentation.

PyTorch example

Show code
python
import random
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader

"""
Augment sentences with EDA (same procedure as eda.py in the paper's official implementation jasonwei20/eda_nlp) and train a small text classification model
For English, synonyms come from WordNet (nltk.corpus.wordnet). Here a small dictionary stands in for it
"""

# Hyperparameters
alpha = 0.1       # fraction of words changed in a sentence (the paper recommends 0.05 for 500 sentences, 0.1 for 5,000 or more)
num_aug = 4       # number of sentences n_aug created per sentence (16 for 500 sentences, 4 for 5,000 or more)
epochs = 20       # number of epochs
learning_rate = 1e-2
embed_dim = 32

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

stop_words = {'the', 'a', 'an', 'of', 'on', 'in', 'is', 'it', 'this', 'and', 'was'}
synonym_dict = {  # in practice, use a thesaurus such as WordNet
  'sad': ['lamentable', 'pitiful'], 'back': ['backward'], 'comedy': ['funniness', 'drollery'],
  'great': ['outstanding', 'excellent'], 'boring': ['tedious', 'dull'], 'movie': ['film', 'picture'],
}


def get_synonyms(word):
  return [s for s in synonym_dict.get(word, []) if s != word]


def synonym_replacement(words, n):  # SR: replace n non-stop-words with synonyms
  new_words = words.copy()
  candidates = [w for w in set(words) if w not in stop_words and get_synonyms(w)]
  random.shuffle(candidates)
  for w in candidates[:n]:
    syn = random.choice(get_synonyms(w))
    new_words = [syn if x == w else x for x in new_words]
  return new_words


def random_insertion(words, n):  # RI: insert a synonym of a word in the sentence at a random position, n times
  new_words = words.copy()
  for _ in range(n):
    for _ in range(10):  # retry up to 10 times until a word with synonyms is found
      syns = get_synonyms(random.choice(new_words))
      if syns:
        new_words.insert(random.randint(0, len(new_words)), random.choice(syns))
        break
  return new_words


def random_swap(words, n):  # RS: pick two words and swap them, n times
  new_words = words.copy()
  for _ in range(n):
    if len(new_words) < 2:
      break
    i, j = random.sample(range(len(new_words)), 2)
    new_words[i], new_words[j] = new_words[j], new_words[i]
  return new_words


def random_deletion(words, p):  # RD: delete each word with probability p (keep one word if all are deleted)
  if len(words) == 1:
    return words
  new_words = [w for w in words if random.random() > p]
  return new_words if new_words else [random.choice(words)]


def eda(sentence, alpha=0.1, num_aug=4):
  words = sentence.lower().split()
  n = max(1, int(alpha * len(words)))  # n = α·l
  per_op = num_aug // 4 + 1
  augmented = []
  for _ in range(per_op):
    augmented.append(synonym_replacement(words, n))
    augmented.append(random_insertion(words, n))
    augmented.append(random_swap(words, n))
    augmented.append(random_deletion(words, alpha))  # p = α
  random.shuffle(augmented)
  return [' '.join(w) for w in augmented[:num_aug]] + [' '.join(words)]  # finally add the original sentence too


# Small training data (1: positive, 0: negative)
train_data = [
  ('a sad superior human comedy played out on the back roads of life', 1),
  ('a great movie with an outstanding cast', 1),
  ('this movie was boring and too long', 0),
  ('the plot is dull and the jokes are tedious', 0),
]
# Augment the training data with EDA (labels same as the originals). Not used for evaluation data
augmented_data = [(s, label) for text, label in train_data for s in eda(text, alpha, num_aug)]
print(len(train_data), '->', len(augmented_data))

vocab = {'<unk>': 0}
for text, _ in augmented_data:
  for w in text.split():
    vocab.setdefault(w, len(vocab))


def collate(batch):
  ids, offsets, labels = [], [], []
  for text, label in batch:
    offsets.append(len(ids))
    ids.extend(vocab.get(w, 0) for w in text.split())
    labels.append(label)
  return torch.tensor(ids), torch.tensor(offsets), torch.tensor(labels)


class BagOfWords(nn.Module):  # small model that classifies by averaging word embeddings
  def __init__(self, vocab_size, embed_dim, num_classes=2):
    super().__init__()
    self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, mode='mean')
    self.fc = nn.Linear(embed_dim, num_classes)

  def forward(self, ids, offsets):
    return self.fc(self.embedding(ids, offsets))


model = BagOfWords(len(vocab), embed_dim).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
loader = DataLoader(augmented_data, batch_size=8, shuffle=True, collate_fn=collate)

for epoch in range(epochs):
  model.train()
  for ids, offsets, labels in loader:
    ids, offsets, labels = ids.to(device), offsets.to(device), labels.to(device)
    loss = criterion(model(ids, offsets), labels)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# Evaluation / inference: feed the original sentence as is (no EDA)
model.eval()
with torch.no_grad():
  ids, offsets, _ = collate([('a dull and boring film', 0)])
  print(model(ids.to(device), offsets.to(device)).argmax(dim=1).item())

FAQ

Q. Can EDA be used on Japanese text?
A.

Yes, but it requires preparation. The paper's implementation is for English: it splits words on spaces and takes synonyms from English WordNet. For Japanese, segment words with morphological analysis and prepare a Japanese thesaurus and a stop word list, then apply the same four operations.

Q. Does it help pretrained models like BERT?
A.

The effect may be small. The paper cites a report that there was almost no improvement with ULMFiT and suggests the same is likely for large pretrained models such as BERT. EDA works best when training data is scarce and the model is trained from scratch.

Q. Which of the four operations helps the most?
A.

In the paper's experiments, all four operations improved accuracy; no single one was responsible for the gains. At small α\alpha, deletion (RD) gave the largest improvement, and insertion (RI) was stable across α\alpha. α=0.1\alpha = 0.1 was a good value for every operation.

References

  1. J. Wei and K. Zou, "EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks," EMNLP-IJCNLP, 2019.
  2. jasonwei20/eda_nlp (the paper's official implementation)