|
|
import os |
|
|
os.environ["CUDA_VISIBLE_DEVICES"] = "1" |
|
|
|
|
|
import math |
|
|
import torch |
|
|
from sklearn.utils import shuffle |
|
|
from sklearn.metrics import f1_score, classification_report |
|
|
from transformers import CamembertModel, CamembertTokenizer, CamembertForSequenceClassification |
|
|
|
|
|
import pandas as pd |
|
|
import numpy as np |
|
|
|
|
|
from loadDataSet import loadData, labels_to_numeric, flatten_labels |
|
|
from helpers import get_device |
|
|
|
|
|
|
|
|
def get_prediction(text, tokenizer, model, max_len, device): |
|
|
|
|
|
inputs = tokenizer(text, padding=True, truncation=True, max_length=max_len, return_tensors="pt").to(device) |
|
|
|
|
|
outputs = model(**inputs) |
|
|
|
|
|
probs = outputs[0].softmax(1) |
|
|
|
|
|
|
|
|
return probs |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
device = get_device() |
|
|
|
|
|
|
|
|
base_path = "../code/" |
|
|
test_path = base_path + "test_slices.txt" |
|
|
|
|
|
|
|
|
testSamples, testLabels = loadData("test", test_path) |
|
|
|
|
|
print("Test size: %d" % len(testSamples)) |
|
|
|
|
|
|
|
|
bert_dir = './bert_models_saved/best_model/' |
|
|
|
|
|
print('Loading BERT tokenizer...') |
|
|
tokenizer = CamembertTokenizer.from_pretrained(bert_dir, do_lowercase=True) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model_path = os.path.join(bert_dir, "pytorch_model.bin") |
|
|
|
|
|
|
|
|
model = CamembertForSequenceClassification.from_pretrained("camembert-base", num_labels=4, output_hidden_states=True) |
|
|
model = model.float() |
|
|
model.load_state_dict(torch.load(model_path)) |
|
|
model.to(device) |
|
|
|
|
|
|
|
|
max_len = 128 |
|
|
|
|
|
|
|
|
|
|
|
testLabels = labels_to_numeric(testLabels) |
|
|
|
|
|
|
|
|
preds_all_labels = [] |
|
|
preds_proba = [] |
|
|
preds = [] |
|
|
|
|
|
for i in range(len(testSamples)): |
|
|
|
|
|
pred = get_prediction(testSamples[1], tokenizer, model, max_len, device) |
|
|
|
|
|
pred_list = pred.cpu().detach().numpy().tolist()[0] |
|
|
preds_all_labels.append(pred_list) |
|
|
|
|
|
pred_proba = pred.max().item() |
|
|
preds_proba.append(pred_proba) |
|
|
|
|
|
pred_index = pred.argmax().item() |
|
|
preds.append(pred_index) |
|
|
|
|
|
print(classification_report(testLabels, preds, digits=6, target_names=["BE", "CA", "CH", "FR"])) |
|
|
|
|
|
|
|
|
batch_size = 32 |
|
|
|
|
|
|
|
|
model_path = os.path.join(bert_dir, "bert.model") |
|
|
|
|
|
best_model = CustomBERTModel() |
|
|
|
|
|
|
|
|
|
|
|
test_gt, test_preds = predict(best_model, input_ids_test, test_dataloader, device) |
|
|
|
|
|
|
|
|
compute_accuracy(test_gt, test_preds) |
|
|
|
|
|
|
|
|
test_gt_flat, test_preds_flat = flatten_labels(test_gt, test_preds) |
|
|
|
|
|
|
|
|
f1_macro = f1_score(test_gt_flat, test_preds_flat, average='macro') |
|
|
print("F1 macro: ", f1_macro) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|