import random
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
"""
EDA(論文の公式実装 jasonwei20/eda_nlp の eda.py と同じ手順)で文を増やし、小さなテキスト分類モデルを学習する
英語なら同義語は WordNet(nltk.corpus.wordnet)から取る。ここでは小さな辞書で代わりにする
"""
# ハイパーパラメータ
alpha = 0.1 # 文の中で変える単語の割合(論文の推奨は 500 文なら 0.05、5,000 文以上なら 0.1)
num_aug = 4 # 1 文から作る文の数 n_aug(500 文なら 16、5,000 文以上なら 4)
epochs = 20 # エポック数
learning_rate = 1e-2
embed_dim = 32
# cudaを使えるなら'cuda', Apple Siliconなら'mps', それ以外なら'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 = { # 本来は 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:ストップワード以外の単語を n 個、同義語に置き換える
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:文中の単語の同義語を、無作為な位置に入れる。n 回
new_words = words.copy()
for _ in range(n):
for _ in range(10): # 同義語のある単語が見つかるまで、10 回まで選び直す
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:2 語を選んで入れ替える。n 回
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:各単語を確率 p で消す(全部消えたら 1 語だけ残す)
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)] # 最後に元の文も加える
# 小さな学習データ(1:肯定的、0:否定的)
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),
]
# EDA で学習データを増やす(ラベルは元の文と同じ)。評価のデータには使わない
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): # 単語の埋め込みを平均して分類する小さなモデル
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()
# 評価・推論:元の文をそのまま入れる(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())