-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprediction.py
61 lines (43 loc) · 1.73 KB
/
prediction.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import torch
from Configuration import Configuration
from Parsing.parser_utils import parse_args
from Prediction.Predictor import Predictor
from Training.NERCRFClassifier import NERCRFClassifier
if __name__ == '__main__':
args, _ = parse_args()
conf = Configuration(args)
conf.show_parameters(["bert"])
if (args.models is None) or len(args.models) != 2:
raise Exception("Define models!")
models = args.models
id2lab_group_a = {0: 'B-ACTI', 1: 'B-DISO', 2: 'B-DRUG', 3: 'B-SIGN', 4: 'I-ACTI', 5: 'I-DISO', 6: 'I-DRUG',
7: 'I-SIGN', 8: 'O'}
id2lab_group_b = {0: 'B-BODY', 1: 'B-TREA', 2: 'I-BODY', 3: 'I-TREA', 4: 'O'}
modelA = NERCRFClassifier(conf.bert, id2lab_group_a)
modelA.load_state_dict(torch.load(models[0]))
modelB = NERCRFClassifier(conf.bert, id2lab_group_b)
modelB.load_state_dict(torch.load(models[1]))
if conf.cuda:
modelA = modelA.to(conf.gpu)
modelB = modelB.to(conf.gpu)
predictor = Predictor(conf)
predictor.add_model("a", modelA, id2lab_group_a)
predictor.add_model("b", modelB, id2lab_group_b)
while True:
sentence = input("Please enter a sentence:\n")
if sentence == "":
continue
if sentence == "exit":
break
else:
tag_pred, mask = predictor.predict(sentence)
result = [*zip(sentence.split(), tag_pred, mask)]
output = []
for (token, tag, mask) in result:
if tag:
output.extend(["[", token, "]"])
else:
output.append(token)
if tag and mask:
output.append(tag)
print("\n" + " ".join(output) + "\n\n")