-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassify.py
More file actions
38 lines (33 loc) · 1.17 KB
/
classify.py
File metadata and controls
38 lines (33 loc) · 1.17 KB
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
import src.preparemodel
import torch
class RumourDetectClass:
def __init__(self):
self.model, self.tokenizer = src.preparemodel.getmodel(True)
self.max_length = 128
def classify(self, text: str) -> int:
self.model.to('cpu')
self.model.eval()
encoding = self.tokenizer(
text,
truncation=True,
padding="max_length",
max_length=self.max_length,
return_tensors="pt"
)
input_ids = encoding["input_ids"].flatten().unsqueeze(0)
attention_mask = encoding["attention_mask"].flatten().unsqueeze(0)
outputs = self.model(input_ids, attention_mask=attention_mask)
pred_class = torch.argmax(outputs, dim=-1).item()
return pred_class
def __call__(self, text: str) -> int:
return self.classify(text=text)
if __name__ == "__main__":
import pandas as pd
csv_file = 'data/val.csv'
data = pd.read_csv(csv_file)
texts = data['text'].tolist()
labels = data['label'].tolist()
test_idx = 0
classifier = RumourDetectClass()
pred = classifier(texts[test_idx])
print(f"predict\t{pred}\nlabel\t{labels[test_idx]}")