igorithm commited on
Commit
9bddf5f
·
1 Parent(s): 92deaca

Add model for training

Browse files
Files changed (1) hide show
  1. bert_paper_classifier_model.py +41 -0
bert_paper_classifier_model.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing as tp
2
+
3
+ import torch
4
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
5
+
6
+
7
+ class SciBertPaperClassifier:
8
+ def __init__(self, model_path="trained_model"):
9
+ self.model = AutoModelForSequenceClassification.from_pretrained(model_path)
10
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path)
11
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
+ self.model.to(self.device)
13
+ self.model.eval()
14
+
15
+ def __call__(self, inputs):
16
+ if not isinstance(inputs, tp.Iterable):
17
+ inputs = [inputs]
18
+ texts = [
19
+ f"AUTHORS: {' '.join(paper.authors) if isinstance(paper.authors, list) else paper.authors} "
20
+ f"TITLE: {paper.title} ABSTRACT: {paper.abstract}"
21
+ for paper in inputs
22
+ ]
23
+
24
+ inputs = self.tokenizer(
25
+ texts, truncation=True, padding=True, max_length=256, return_tensors="pt"
26
+ ).to(self.device)
27
+
28
+ with torch.no_grad():
29
+ outputs = self.model(**inputs)
30
+
31
+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
32
+ results = []
33
+ for prob in probs:
34
+ result = [
35
+ {self.model.config.id2label[label_idx]: score.item()}
36
+ for label_idx, score in enumerate(prob)
37
+ ]
38
+ results.append(result)
39
+ if 1 == len(results):
40
+ return results[0]
41
+ return results