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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
|
| 4 |
def test():
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
import logging
|
| 3 |
+
from transformers import BertModel, BertTokenizerFast
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from datasets import load_dataset
|
| 8 |
+
from torch.utils.data import DataLoader
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
CURRENT_PATH = Path(__file__).parent
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def tokenize(dataset):
|
| 15 |
+
BERT_MAX_LEN = 512
|
| 16 |
+
|
| 17 |
+
tokenizer = BertTokenizerFast.from_pretrained(
|
| 18 |
+
"neuralmind/bert-base-portuguese-cased", max_length=BERT_MAX_LEN)
|
| 19 |
+
|
| 20 |
+
dataset = dataset.map(lambda example: tokenizer(
|
| 21 |
+
example["text"], truncation=True, padding="max_length", max_length=BERT_MAX_LEN))
|
| 22 |
+
|
| 23 |
+
return dataset
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def create_dataloader(dataset, shuffle=True):
|
| 27 |
+
return DataLoader(dataset, batch_size=8, shuffle=shuffle, num_workers=8, drop_last=True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class AutoEncoder(torch.nn.Module):
|
| 31 |
+
def __init__(self):
|
| 32 |
+
super().__init__()
|
| 33 |
+
|
| 34 |
+
self.device = torch.device(
|
| 35 |
+
'cuda' if torch.cuda.is_available() else 'cpu')
|
| 36 |
+
|
| 37 |
+
self.bert = BertModel.from_pretrained(
|
| 38 |
+
'neuralmind/bert-base-portuguese-cased').to(self.device)
|
| 39 |
+
|
| 40 |
+
# Freeze BERT
|
| 41 |
+
for param in self.bert.parameters():
|
| 42 |
+
param.requires_grad = False
|
| 43 |
+
|
| 44 |
+
self.encoder = torch.nn.Sequential(
|
| 45 |
+
torch.nn.Linear(self.bert.config.hidden_size,
|
| 46 |
+
self.bert.config.hidden_size // 5),
|
| 47 |
+
torch.nn.ReLU(),
|
| 48 |
+
torch.nn.Linear(self.bert.config.hidden_size // 5,
|
| 49 |
+
self.bert.config.hidden_size // 10),
|
| 50 |
+
torch.nn.ReLU(),
|
| 51 |
+
torch.nn.Linear(self.bert.config.hidden_size // 10,
|
| 52 |
+
self.bert.config.hidden_size // 30),
|
| 53 |
+
torch.nn.ReLU(),
|
| 54 |
+
).to(self.device)
|
| 55 |
+
|
| 56 |
+
self.decoder = torch.nn.Sequential(
|
| 57 |
+
torch.nn.Linear(self.bert.config.hidden_size // 30,
|
| 58 |
+
self.bert.config.hidden_size // 10),
|
| 59 |
+
torch.nn.ReLU(),
|
| 60 |
+
torch.nn.Linear(self.bert.config.hidden_size // 10,
|
| 61 |
+
self.bert.config.hidden_size // 5),
|
| 62 |
+
torch.nn.ReLU(),
|
| 63 |
+
torch.nn.Linear(self.bert.config.hidden_size //
|
| 64 |
+
5, self.bert.config.hidden_size),
|
| 65 |
+
torch.nn.Sigmoid()
|
| 66 |
+
).to(self.device)
|
| 67 |
+
|
| 68 |
+
def forward(self, input_ids, attention_mask):
|
| 69 |
+
bert_output = self.bert(input_ids=input_ids,
|
| 70 |
+
attention_mask=attention_mask).last_hidden_state[:, 0, :]
|
| 71 |
+
|
| 72 |
+
encoded = self.encoder(bert_output)
|
| 73 |
+
|
| 74 |
+
decoded = self.decoder(encoded)
|
| 75 |
+
|
| 76 |
+
return bert_output, decoded
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def load_models():
|
| 80 |
+
models = []
|
| 81 |
+
|
| 82 |
+
for domain in ['politics', 'news', 'law', 'social_media', 'literature', 'web']:
|
| 83 |
+
logging.info(f"Loading {domain} model...")
|
| 84 |
+
|
| 85 |
+
accumulator = []
|
| 86 |
+
|
| 87 |
+
for lang in ['brazilian', 'european']:
|
| 88 |
+
model = AutoEncoder()
|
| 89 |
+
model.load_state_dict(torch.load(os.path.join(
|
| 90 |
+
CURRENT_PATH, 'models', 'autoencoder', f'{domain}_{lang}_model.pt')))
|
| 91 |
+
accumulator.append(model)
|
| 92 |
+
|
| 93 |
+
models.append({
|
| 94 |
+
'models': accumulator,
|
| 95 |
+
'train_domain': domain,
|
| 96 |
+
})
|
| 97 |
+
|
| 98 |
+
return models
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def benchmark(model, debug=False):
|
| 102 |
+
|
| 103 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 104 |
+
|
| 105 |
+
df_results = pd.DataFrame(
|
| 106 |
+
columns=['train_domain', 'test_domain', 'accuracy', 'f1', 'precision', 'recall'])
|
| 107 |
+
|
| 108 |
+
train_domain = model['train_domain']
|
| 109 |
+
|
| 110 |
+
brazilian_model = model['models'][0]
|
| 111 |
+
|
| 112 |
+
european_model = model['models'][1]
|
| 113 |
+
|
| 114 |
+
brazilian_model.eval()
|
| 115 |
+
european_model.eval()
|
| 116 |
+
|
| 117 |
+
brazilian_model.to(device)
|
| 118 |
+
european_model.to(device)
|
| 119 |
+
|
| 120 |
+
for test_domain in ['politics', 'news', 'law', 'social_media', 'literature', 'web']:
|
| 121 |
+
dataset = load_dataset(
|
| 122 |
+
'arubenruben/Portuguese_Language_Identification', test_domain, split='test')
|
| 123 |
+
|
| 124 |
+
if debug:
|
| 125 |
+
logging.info(f"Debugging {test_domain} dataset...")
|
| 126 |
+
dataset = dataset.select(range(100))
|
| 127 |
+
else:
|
| 128 |
+
dataset = dataset.shuffle().select(range(min(50_000, len(dataset))))
|
| 129 |
+
|
| 130 |
+
dataset = tokenize(dataset)
|
| 131 |
+
|
| 132 |
+
dataset.set_format(type='torch', columns=[
|
| 133 |
+
'input_ids', 'attention_mask', 'label'])
|
| 134 |
+
|
| 135 |
+
dataset = create_dataloader(dataset)
|
| 136 |
+
|
| 137 |
+
predictions = []
|
| 138 |
+
labels = []
|
| 139 |
+
|
| 140 |
+
reconstruction_loss = torch.nn.MSELoss(reduction='none')
|
| 141 |
+
|
| 142 |
+
with torch.no_grad():
|
| 143 |
+
for batch in tqdm(dataset):
|
| 144 |
+
input_ids = batch['input_ids'].to(device)
|
| 145 |
+
|
| 146 |
+
attention_mask = batch['attention_mask'].to(device)
|
| 147 |
+
|
| 148 |
+
label = batch['label'].to(device)
|
| 149 |
+
|
| 150 |
+
bert_european, reconstruction_european = european_model(
|
| 151 |
+
input_ids=input_ids, attention_mask=attention_mask)
|
| 152 |
+
|
| 153 |
+
bert_brazilian, reconstruction_brazilian = brazilian_model(
|
| 154 |
+
input_ids=input_ids, attention_mask=attention_mask)
|
| 155 |
+
|
| 156 |
+
test_loss_european = reconstruction_loss(
|
| 157 |
+
reconstruction_european, bert_european)
|
| 158 |
+
|
| 159 |
+
test_loss_brazilian = reconstruction_loss(
|
| 160 |
+
reconstruction_brazilian, bert_brazilian)
|
| 161 |
+
|
| 162 |
+
for loss_european, loss_brazilian in zip(test_loss_european, test_loss_brazilian):
|
| 163 |
+
|
| 164 |
+
if loss_european.mean().item() < loss_brazilian.mean().item():
|
| 165 |
+
predictions.append(0)
|
| 166 |
+
total_loss += loss_european.mean().item() / len(test_loss_european)
|
| 167 |
+
|
| 168 |
+
else:
|
| 169 |
+
predictions.append(1)
|
| 170 |
+
total_loss += loss_brazilian.mean().item() / len(test_loss_brazilian)
|
| 171 |
+
|
| 172 |
+
labels.extend(label.tolist())
|
| 173 |
+
|
| 174 |
+
accuracy = accuracy.compute(
|
| 175 |
+
predictions=predictions, references=labels)['accuracy']
|
| 176 |
+
f1 = f1.compute(predictions=predictions, references=labels)['f1']
|
| 177 |
+
precision = precision.compute(
|
| 178 |
+
predictions=predictions, references=labels)['precision']
|
| 179 |
+
recall = recall.compute(predictions=predictions,
|
| 180 |
+
references=labels)['recall']
|
| 181 |
+
|
| 182 |
+
df_results = pd.concat([df_results, pd.DataFrame(
|
| 183 |
+
[[train_domain, test_domain, accuracy, f1, precision, recall]], columns=df_results.columns)], ignore_index=True)
|
| 184 |
+
|
| 185 |
+
return df_results
|
| 186 |
|
| 187 |
|
| 188 |
def test():
|
| 189 |
+
DEBUG = True
|
| 190 |
+
|
| 191 |
+
models = load_models()
|
| 192 |
+
|
| 193 |
+
df_results = pd.DataFrame(
|
| 194 |
+
columns=['train_domain', 'test_domain', 'accuracy', 'f1', 'precision', 'recall'])
|
| 195 |
+
|
| 196 |
+
for model in models:
|
| 197 |
+
logging.info(f"Train Domain {model['train_domain']}...")
|
| 198 |
+
|
| 199 |
+
df_results = pd.concat([df_results, benchmark(
|
| 200 |
+
model, debug=DEBUG)], ignore_index=True)
|
| 201 |
+
|
| 202 |
+
logging.info(f"Saving results...")
|
| 203 |
+
|
| 204 |
+
df_results.to_json(os.path.join(CURRENT_PATH, 'results',
|
| 205 |
+
'autoencoder.json'), orient='records', indent=4, force_ascii=False)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
if __name__ == '__main__':
|
| 209 |
+
test()
|
n_grams.py
CHANGED
|
@@ -40,11 +40,6 @@ def load_pipelines():
|
|
| 40 |
|
| 41 |
def benchmark(pipeline, debug=False):
|
| 42 |
|
| 43 |
-
accuracy_evaluator = evaluate.load('accuracy')
|
| 44 |
-
f1_evaluator = evaluate.load('f1')
|
| 45 |
-
precision_evaluator = evaluate.load('precision')
|
| 46 |
-
recall_evaluator = evaluate.load('recall')
|
| 47 |
-
|
| 48 |
df_results = pd.DataFrame(
|
| 49 |
columns=['train_domain', 'test_domain', 'accuracy', 'f1', 'precision', 'recall'])
|
| 50 |
|
|
@@ -67,13 +62,16 @@ def benchmark(pipeline, debug=False):
|
|
| 67 |
|
| 68 |
y = pipeline.predict(dataset['text'])
|
| 69 |
|
| 70 |
-
accuracy =
|
| 71 |
predictions=y, references=dataset['label'])['accuracy']
|
| 72 |
-
|
|
|
|
| 73 |
predictions=y, references=dataset['label'])['f1']
|
| 74 |
-
|
|
|
|
| 75 |
predictions=y, references=dataset['label'])['precision']
|
| 76 |
-
|
|
|
|
| 77 |
predictions=y, references=dataset['label'])['recall']
|
| 78 |
|
| 79 |
logging.info(
|
|
|
|
| 40 |
|
| 41 |
def benchmark(pipeline, debug=False):
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
df_results = pd.DataFrame(
|
| 44 |
columns=['train_domain', 'test_domain', 'accuracy', 'f1', 'precision', 'recall'])
|
| 45 |
|
|
|
|
| 62 |
|
| 63 |
y = pipeline.predict(dataset['text'])
|
| 64 |
|
| 65 |
+
accuracy = evaluate.load('accuracy').compute(
|
| 66 |
predictions=y, references=dataset['label'])['accuracy']
|
| 67 |
+
|
| 68 |
+
f1 = evaluate.load('f1').compute(
|
| 69 |
predictions=y, references=dataset['label'])['f1']
|
| 70 |
+
|
| 71 |
+
precision = evaluate.load('precision').compute(
|
| 72 |
predictions=y, references=dataset['label'])['precision']
|
| 73 |
+
|
| 74 |
+
recall = evaluate.load('recall').compute(
|
| 75 |
predictions=y, references=dataset['label'])['recall']
|
| 76 |
|
| 77 |
logging.info(
|
script.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pip install -U -r requirements.txt
|
| 2 |
+
|
| 3 |
+
python n_grams.py
|
| 4 |
+
|
| 5 |
+
python embeddings.py
|
| 6 |
+
|
| 7 |
+
python autoencoder.py
|