-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_conll2003.py
53 lines (42 loc) · 2.06 KB
/
test_conll2003.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
import torch
from transformers import BertTokenizerFast
import utils.utils_conll2003 as E
import utils.utils_Generic as G
from nets.Bert_Only import BertNER
if __name__ == "__main__":
# ----------------------------------------------------#
# prompt: The sentence you want to test
# ----------------------------------------------------#
prompt = ''
# ----------------------------------------------------#
# save_path: Path to save you json file
# download_path: Path to conll2003 dataset
# if_downloaded: Have downloaded the conll2003 dataset
# pretrained_model_name: The Bert model
# model_path: Your trained model
# ----------------------------------------------------#
download_path = 'dataset/conll2003_NER'
if_downloaded = True
pretrained_model_name = 'All_Bert_Pretrained_Models/bert-base-uncased'
model_path = 'logs/Bert_only_f1_90.pth'
# ----------------------------------------------------#
# Get the label list and entities categories
# ----------------------------------------------------#
label_list, categories = E.labellist_and_categories(if_downloaded=if_downloaded, download_path=download_path)
# ----------------------------------------------------#
# Load the model/tokenizer and put it on GPU
# ----------------------------------------------------#
tokenizer = BertTokenizerFast.from_pretrained(pretrained_model_name)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = BertNER(len(label_list), bert_model_type=pretrained_model_name)
model.load_state_dict(torch.load(model_path))
model.to(device)
model.eval()
# ----------------------------------------------------#
# Start prediction
# ----------------------------------------------------#
entities = G.predict(prompt, model, tokenizer, device, categories, use_crf=False, english=True)
print('\nStart recognize: \n')
for entity, name in entities:
print(f'Entity: {entity}, Type: {name}')
print('\nFinished recognize \n')