forked from vedantm314/text-analytics-for-reconnaissance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FineTunedBertModule.py
39 lines (23 loc) · 1.22 KB
/
FineTunedBertModule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from transformers import Trainer
from transformers import BertTokenizerFast
from transformers import BertForSequenceClassification
import numpy as np
import pandas as pd
class FineTunedBertModule:
category_array = ["buildings", "infrastructure ", "other", "resilience"]
def __init__(self):
self.model = BertForSequenceClassification.from_pretrained("fineTunedBert")
self.tokenizer = BertTokenizerFast.from_pretrained("bert-base-uncased")
def tokenize_sentence(self, sentence):
return self.tokenizer(sentence, padding="max_length", truncation=True, return_tensors="pt")
def get_predictions(self, sentences):
preds = []
for x in range(0, len(sentences)):
tokenized_sentence = self.tokenize_sentence(sentences[x])
logits = self.model(**tokenized_sentence).logits
numerical_prediction = np.argmax(logits.detach().numpy(), axis = -1)
preds.append(numerical_prediction[0])
preds = list(map(lambda x: self.category_array[x], preds))
sentences_with_preds = {"sentence": sentences, "label": preds}
df = pd.DataFrame.from_dict(sentences_with_preds)
return df