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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from transformers import BertModel,AutoTokenizer
|
| 8 |
+
import os
|
| 9 |
+
from torch.utils import data
|
| 10 |
+
import numpy as np
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
max_seq_length = 512
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class InputExample(object):
|
| 17 |
+
|
| 18 |
+
def __init__(self, guid, words, labels):
|
| 19 |
+
self.guid = guid
|
| 20 |
+
self.words = words
|
| 21 |
+
self.labels = labels
|
| 22 |
+
|
| 23 |
+
class InputFeatures(object):
|
| 24 |
+
|
| 25 |
+
def __init__(self, input_ids, input_mask, segment_ids, predict_mask, label_ids):
|
| 26 |
+
self.input_ids = input_ids
|
| 27 |
+
self.input_mask = input_mask
|
| 28 |
+
self.segment_ids = segment_ids
|
| 29 |
+
self.predict_mask = predict_mask
|
| 30 |
+
self.label_ids = label_ids
|
| 31 |
+
class DataProcessor(object):
|
| 32 |
+
|
| 33 |
+
def get_train_examples(self, data_dir):
|
| 34 |
+
raise NotImplementedError()
|
| 35 |
+
|
| 36 |
+
def get_dev_examples(self, data_dir):
|
| 37 |
+
raise NotImplementedError()
|
| 38 |
+
def get_predict_examples(self, data_dir,predict_string):
|
| 39 |
+
raise NotImplementedError()
|
| 40 |
+
def get_labels(self):
|
| 41 |
+
raise NotImplementedError()
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def _read_data(cls, input_file,isPredict = False,sentence = ''):
|
| 45 |
+
if isPredict == False:
|
| 46 |
+
with open(input_file) as f:
|
| 47 |
+
out_lists = []
|
| 48 |
+
entries = f.read().strip().split("\n\n")
|
| 49 |
+
for entry in entries:
|
| 50 |
+
words = []
|
| 51 |
+
ner_labels = []
|
| 52 |
+
pos_tags = []
|
| 53 |
+
bio_pos_tags = []
|
| 54 |
+
for line in entry.splitlines():
|
| 55 |
+
pieces = line.strip().split()
|
| 56 |
+
if len(pieces) < 1:
|
| 57 |
+
continue
|
| 58 |
+
word = pieces[0]
|
| 59 |
+
words.append(word)
|
| 60 |
+
ner_labels.append(pieces[-1])
|
| 61 |
+
|
| 62 |
+
out_lists.append([words,pos_tags,bio_pos_tags,ner_labels])
|
| 63 |
+
else:
|
| 64 |
+
out_lists = []
|
| 65 |
+
words = []
|
| 66 |
+
ner_labels = []
|
| 67 |
+
pos_tags = []
|
| 68 |
+
bio_pos_tags = []
|
| 69 |
+
entries = sentence.strip().split(" ")
|
| 70 |
+
for i in entries:
|
| 71 |
+
if len(i) < 1:
|
| 72 |
+
continue
|
| 73 |
+
word = i
|
| 74 |
+
words.append(word)
|
| 75 |
+
ner_labels.append('O')
|
| 76 |
+
out_lists.append([words,pos_tags,bio_pos_tags,ner_labels])
|
| 77 |
+
return out_lists
|
| 78 |
+
|
| 79 |
+
class DNRTIDataProcessor(DataProcessor):
|
| 80 |
+
|
| 81 |
+
def __init__(self):
|
| 82 |
+
self._label_types = [ 'X', '[CLS]', '[SEP]', 'O', 'B-Area', 'B-Exp', 'B-Features', 'B-HackOrg', 'B-Idus', 'B-OffAct','B-Org', 'B-Purp', 'B-SamFile','B-SecTeam','B-Time','B-Tool','B-Way','I-Area','I-Exp','I-Features','I-HackOrg','I-Idus','I-OffAct','I-Org','I-Purp','I-SamFile','I-SecTeam','I-Time','I-Tool','I-Way']
|
| 83 |
+
self._num_labels = len(self._label_types)
|
| 84 |
+
self._label_map = {label: i for i,
|
| 85 |
+
label in enumerate(self._label_types)}
|
| 86 |
+
|
| 87 |
+
def get_train_examples(self, data_dir):
|
| 88 |
+
return self._create_examples(
|
| 89 |
+
self._read_data(os.path.join(data_dir, "train.txt")))
|
| 90 |
+
|
| 91 |
+
def get_dev_examples(self, data_dir):
|
| 92 |
+
return self._create_examples(
|
| 93 |
+
self._read_data(os.path.join(data_dir, "valid.txt")))
|
| 94 |
+
def get_predict_examples(self,data_dir, predict_string):
|
| 95 |
+
return self._create_examples(
|
| 96 |
+
self._read_data(os.path.join(data_dir, "None.txt"),True,predict_string),True)
|
| 97 |
+
def get_test_examples(self, data_dir):
|
| 98 |
+
return self._create_examples(
|
| 99 |
+
self._read_data(os.path.join(data_dir, "test.txt")))
|
| 100 |
+
|
| 101 |
+
def get_labels(self):
|
| 102 |
+
return self._label_types
|
| 103 |
+
|
| 104 |
+
def get_num_labels(self):
|
| 105 |
+
return self.get_num_labels
|
| 106 |
+
|
| 107 |
+
def get_label_map(self):
|
| 108 |
+
return self._label_map
|
| 109 |
+
|
| 110 |
+
def get_start_label_id(self):
|
| 111 |
+
return self._label_map['[CLS]']
|
| 112 |
+
|
| 113 |
+
def get_stop_label_id(self):
|
| 114 |
+
return self._label_map['[SEP]']
|
| 115 |
+
|
| 116 |
+
def _create_examples(self, all_lists,isPredict = False):
|
| 117 |
+
examples = []
|
| 118 |
+
if isPredict == False:
|
| 119 |
+
for (i, one_lists) in enumerate(all_lists):
|
| 120 |
+
|
| 121 |
+
guid = i
|
| 122 |
+
words = one_lists[0]
|
| 123 |
+
labels = one_lists[-1]
|
| 124 |
+
|
| 125 |
+
examples.append(InputExample(
|
| 126 |
+
guid=guid, words=words, labels=labels))
|
| 127 |
+
|
| 128 |
+
else:
|
| 129 |
+
k = 1
|
| 130 |
+
for i in all_lists:
|
| 131 |
+
|
| 132 |
+
guid = k
|
| 133 |
+
k += 1
|
| 134 |
+
words = i[0]
|
| 135 |
+
labels = i[3]
|
| 136 |
+
examples.append(InputExample(
|
| 137 |
+
guid=guid, words=words, labels=labels))
|
| 138 |
+
|
| 139 |
+
return examples
|
| 140 |
+
|
| 141 |
+
def _create_examples2(self, lines):
|
| 142 |
+
examples = []
|
| 143 |
+
for (i, line) in enumerate(lines):
|
| 144 |
+
guid = i
|
| 145 |
+
text = line[0]
|
| 146 |
+
ner_label = line[-1]
|
| 147 |
+
examples.append(InputExample(
|
| 148 |
+
guid=guid, text_a=text, labels_a=ner_label))
|
| 149 |
+
return examples
|
| 150 |
+
def example2feature(example, tokenizer, label_map, max_seq_length):
|
| 151 |
+
add_label = 'X'
|
| 152 |
+
# tokenize_count = []
|
| 153 |
+
tokens = ['[CLS]']
|
| 154 |
+
predict_mask = [0]
|
| 155 |
+
label_ids = [label_map['[CLS]']]
|
| 156 |
+
for i, w in enumerate(example.words):
|
| 157 |
+
sub_words = tokenizer.tokenize(w)
|
| 158 |
+
if not sub_words:
|
| 159 |
+
sub_words = ['[UNK]']
|
| 160 |
+
tokens.extend(sub_words)
|
| 161 |
+
for j in range(len(sub_words)):
|
| 162 |
+
if j == 0:
|
| 163 |
+
predict_mask.append(1)
|
| 164 |
+
label_ids.append(label_map[example.labels[i]])
|
| 165 |
+
else:
|
| 166 |
+
predict_mask.append(0)
|
| 167 |
+
label_ids.append(label_map[add_label])
|
| 168 |
+
|
| 169 |
+
if len(tokens) > max_seq_length - 1:
|
| 170 |
+
print('Example No.{} is too long, length is {}, truncated to {}!'.format(example.guid, len(tokens), max_seq_length))
|
| 171 |
+
tokens = tokens[0:(max_seq_length - 1)]
|
| 172 |
+
predict_mask = predict_mask[0:(max_seq_length - 1)]
|
| 173 |
+
label_ids = label_ids[0:(max_seq_length - 1)]
|
| 174 |
+
tokens.append('[SEP]')
|
| 175 |
+
predict_mask.append(0)
|
| 176 |
+
label_ids.append(label_map['[SEP]'])
|
| 177 |
+
|
| 178 |
+
input_ids = tokenizer.convert_tokens_to_ids(tokens)
|
| 179 |
+
segment_ids = [0] * len(input_ids)
|
| 180 |
+
input_mask = [1] * len(input_ids)
|
| 181 |
+
feat=InputFeatures(
|
| 182 |
+
# guid=example.guid,
|
| 183 |
+
# tokens=tokens,
|
| 184 |
+
input_ids=input_ids,
|
| 185 |
+
input_mask=input_mask,
|
| 186 |
+
segment_ids=segment_ids,
|
| 187 |
+
predict_mask=predict_mask,
|
| 188 |
+
label_ids=label_ids)
|
| 189 |
+
|
| 190 |
+
return feat
|
| 191 |
+
class NerDataset(data.Dataset):
|
| 192 |
+
def __init__(self, examples, tokenizer, label_map, max_seq_length):
|
| 193 |
+
self.examples=examples
|
| 194 |
+
self.tokenizer=tokenizer
|
| 195 |
+
self.label_map=label_map
|
| 196 |
+
self.max_seq_length=max_seq_length
|
| 197 |
+
|
| 198 |
+
def __len__(self):
|
| 199 |
+
return len(self.examples)
|
| 200 |
+
|
| 201 |
+
def __getitem__(self, idx):
|
| 202 |
+
feat=example2feature(self.examples[idx], self.tokenizer, self.label_map, max_seq_length)
|
| 203 |
+
return feat.input_ids, feat.input_mask, feat.segment_ids, feat.predict_mask, feat.label_ids
|
| 204 |
+
|
| 205 |
+
@classmethod
|
| 206 |
+
def pad(cls, batch):
|
| 207 |
+
|
| 208 |
+
seqlen_list = [len(sample[0]) for sample in batch]
|
| 209 |
+
maxlen = np.array(seqlen_list).max()
|
| 210 |
+
|
| 211 |
+
f = lambda x, seqlen: [sample[x] + [0] * (seqlen - len(sample[x])) for sample in batch]
|
| 212 |
+
input_ids_list = torch.LongTensor(f(0, maxlen))
|
| 213 |
+
input_mask_list = torch.LongTensor(f(1, maxlen))
|
| 214 |
+
segment_ids_list = torch.LongTensor(f(2, maxlen))
|
| 215 |
+
predict_mask_list = torch.ByteTensor(f(3, maxlen))
|
| 216 |
+
label_ids_list = torch.LongTensor(f(4, maxlen))
|
| 217 |
+
|
| 218 |
+
return input_ids_list, input_mask_list, segment_ids_list, predict_mask_list, label_ids_list
|
| 219 |
+
|
| 220 |
+
def f1_score(y_true, y_pred):
|
| 221 |
+
ignore_id=3
|
| 222 |
+
|
| 223 |
+
num_proposed = len(y_pred[y_pred>ignore_id])
|
| 224 |
+
num_correct = (np.logical_and(y_true==y_pred, y_true>ignore_id)).sum()
|
| 225 |
+
num_gold = len(y_true[y_true>ignore_id])
|
| 226 |
+
|
| 227 |
+
try:
|
| 228 |
+
precision = num_correct / num_proposed
|
| 229 |
+
except ZeroDivisionError:
|
| 230 |
+
precision = 1.0
|
| 231 |
+
|
| 232 |
+
try:
|
| 233 |
+
recall = num_correct / num_gold
|
| 234 |
+
except ZeroDivisionError:
|
| 235 |
+
recall = 1.0
|
| 236 |
+
|
| 237 |
+
try:
|
| 238 |
+
f1 = 2*precision*recall / (precision + recall)
|
| 239 |
+
except ZeroDivisionError:
|
| 240 |
+
if precision*recall==0:
|
| 241 |
+
f1=1.0
|
| 242 |
+
else:
|
| 243 |
+
f1=0
|
| 244 |
+
|
| 245 |
+
return precision, recall, f1
|
| 246 |
+
|
| 247 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 248 |
+
BertLayerNorm = torch.nn.LayerNorm
|
| 249 |
+
def log_sum_exp_1vec(vec):
|
| 250 |
+
max_score = vec[0, np.argmax(vec)]
|
| 251 |
+
max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])
|
| 252 |
+
return max_score + torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))
|
| 253 |
+
|
| 254 |
+
def log_sum_exp_mat(log_M, axis=-1):
|
| 255 |
+
return torch.max(log_M, axis)[0]+torch.log(torch.exp(log_M-torch.max(log_M, axis)[0][:, None]).sum(axis))
|
| 256 |
+
|
| 257 |
+
def log_sum_exp_batch(log_Tensor, axis=-1):
|
| 258 |
+
return torch.max(log_Tensor, axis)[0]+torch.log(torch.exp(log_Tensor-torch.max(log_Tensor, axis)[0].view(log_Tensor.shape[0],-1,1)).sum(axis))
|
| 259 |
+
|
| 260 |
+
class BERT_CRF_NER(nn.Module):
|
| 261 |
+
|
| 262 |
+
def __init__(self, bert_model, start_label_id, stop_label_id, num_labels, max_seq_length, batch_size, device):
|
| 263 |
+
super(BERT_CRF_NER, self).__init__()
|
| 264 |
+
self.hidden_size = 768
|
| 265 |
+
self.start_label_id = start_label_id
|
| 266 |
+
self.stop_label_id = stop_label_id
|
| 267 |
+
self.num_labels = num_labels
|
| 268 |
+
# self.max_seq_length = max_seq_length
|
| 269 |
+
self.batch_size = batch_size
|
| 270 |
+
self.device=device
|
| 271 |
+
self.bert = bert_model
|
| 272 |
+
self.dropout = torch.nn.Dropout(0.2)
|
| 273 |
+
self.hidden2label = nn.Linear(self.hidden_size, self.num_labels)
|
| 274 |
+
self.transitions = nn.Parameter(torch.randn(self.num_labels, self.num_labels))
|
| 275 |
+
self.transitions.data[start_label_id, :] = -10000
|
| 276 |
+
self.transitions.data[:, stop_label_id] = -10000
|
| 277 |
+
|
| 278 |
+
nn.init.xavier_uniform_(self.hidden2label.weight)
|
| 279 |
+
nn.init.constant_(self.hidden2label.bias, 0.0)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def init_bert_weights(self, module):
|
| 283 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 284 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 285 |
+
elif isinstance(module, BertLayerNorm):
|
| 286 |
+
module.bias.data.zero_()
|
| 287 |
+
module.weight.data.fill_(1.0)
|
| 288 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 289 |
+
module.bias.data.zero_()
|
| 290 |
+
|
| 291 |
+
def _forward_alg(self, feats):
|
| 292 |
+
T = feats.shape[1]
|
| 293 |
+
batch_size = feats.shape[0]
|
| 294 |
+
log_alpha = torch.Tensor(batch_size, 1, self.num_labels).fill_(-10000.).to(self.device)
|
| 295 |
+
log_alpha[:, 0, self.start_label_id] = 0
|
| 296 |
+
for t in range(1, T):
|
| 297 |
+
log_alpha = (log_sum_exp_batch(self.transitions + log_alpha, axis=-1) + feats[:, t]).unsqueeze(1)
|
| 298 |
+
log_prob_all_barX = log_sum_exp_batch(log_alpha)
|
| 299 |
+
return log_prob_all_barX
|
| 300 |
+
|
| 301 |
+
def _get_bert_features(self, input_ids, segment_ids, input_mask):
|
| 302 |
+
bert_seq_out, _ = self.bert(input_ids, token_type_ids=segment_ids, attention_mask=input_mask,return_dict=False)
|
| 303 |
+
bert_seq_out = self.dropout(bert_seq_out)
|
| 304 |
+
bert_feats = self.hidden2label(bert_seq_out)
|
| 305 |
+
return bert_feats
|
| 306 |
+
|
| 307 |
+
def _score_sentence(self, feats, label_ids):
|
| 308 |
+
T = feats.shape[1]
|
| 309 |
+
batch_size = feats.shape[0]
|
| 310 |
+
|
| 311 |
+
batch_transitions = self.transitions.expand(batch_size,self.num_labels,self.num_labels)
|
| 312 |
+
batch_transitions = batch_transitions.flatten(1)
|
| 313 |
+
|
| 314 |
+
score = torch.zeros((feats.shape[0],1)).to(device)
|
| 315 |
+
for t in range(1, T):
|
| 316 |
+
score = score + \
|
| 317 |
+
batch_transitions.gather(-1, (label_ids[:, t]*self.num_labels+label_ids[:, t-1]).view(-1,1)) \
|
| 318 |
+
+ feats[:, t].gather(-1, label_ids[:, t].view(-1,1)).view(-1,1)
|
| 319 |
+
return score
|
| 320 |
+
|
| 321 |
+
def _viterbi_decode(self, feats):
|
| 322 |
+
T = feats.shape[1]
|
| 323 |
+
batch_size = feats.shape[0]
|
| 324 |
+
log_delta = torch.Tensor(batch_size, 1, self.num_labels).fill_(-10000.).to(self.device)
|
| 325 |
+
log_delta[:, 0, self.start_label_id] = 0
|
| 326 |
+
psi = torch.zeros((batch_size, T, self.num_labels), dtype=torch.long).to(self.device)
|
| 327 |
+
for t in range(1, T):
|
| 328 |
+
log_delta, psi[:, t] = torch.max(self.transitions + log_delta, -1)
|
| 329 |
+
log_delta = (log_delta + feats[:, t]).unsqueeze(1)
|
| 330 |
+
path = torch.zeros((batch_size, T), dtype=torch.long).to(self.device)
|
| 331 |
+
max_logLL_allz_allx, path[:, -1] = torch.max(log_delta.squeeze(), -1)
|
| 332 |
+
|
| 333 |
+
for t in range(T-2, -1, -1):
|
| 334 |
+
path[:, t] = psi[:, t+1].gather(-1,path[:, t+1].view(-1,1)).squeeze()
|
| 335 |
+
return max_logLL_allz_allx, path
|
| 336 |
+
|
| 337 |
+
def neg_log_likelihood(self, input_ids, segment_ids, input_mask, label_ids):
|
| 338 |
+
bert_feats = self._get_bert_features(input_ids, segment_ids, input_mask)
|
| 339 |
+
forward_score = self._forward_alg(bert_feats)
|
| 340 |
+
gold_score = self._score_sentence(bert_feats, label_ids)
|
| 341 |
+
return torch.mean(forward_score - gold_score)
|
| 342 |
+
|
| 343 |
+
def forward(self, input_ids, segment_ids, input_mask):
|
| 344 |
+
bert_feats = self._get_bert_features(input_ids, segment_ids, input_mask)
|
| 345 |
+
score, label_seq_ids = self._viterbi_decode(bert_feats)
|
| 346 |
+
return score, label_seq_ids
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
bert_model_scale = 'bert-base-cased'
|
| 351 |
+
tokenizer = AutoTokenizer.from_pretrained(bert_model_scale, do_lower_case=True)
|
| 352 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 353 |
+
DNRTIProcessor = DNRTIDataProcessor()
|
| 354 |
+
start_label_id = DNRTIProcessor.get_start_label_id()
|
| 355 |
+
stop_label_id = DNRTIProcessor.get_stop_label_id()
|
| 356 |
+
label_list = DNRTIProcessor.get_labels()
|
| 357 |
+
label_map = DNRTIProcessor.get_label_map()
|
| 358 |
+
batch_size = 512
|
| 359 |
+
bert_model = BertModel.from_pretrained(bert_model_scale)
|
| 360 |
+
model = BERT_CRF_NER(bert_model, start_label_id, stop_label_id, len(label_list), max_seq_length, batch_size, device)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
checkpoint = torch.load('./outputs/ner_bert_crf_checkpoint.pt', map_location='cpu', weights_only=False)
|
| 364 |
+
epoch = checkpoint['epoch']
|
| 365 |
+
valid_acc_prev = checkpoint['valid_acc']
|
| 366 |
+
valid_f1_prev = checkpoint['valid_f1']
|
| 367 |
+
pretrained_dict=checkpoint['model_state']
|
| 368 |
+
net_state_dict = model.state_dict()
|
| 369 |
+
pretrained_dict_selected = {k: v for k, v in pretrained_dict.items() if k in net_state_dict}
|
| 370 |
+
net_state_dict.update(pretrained_dict_selected)
|
| 371 |
+
model.load_state_dict(net_state_dict)
|
| 372 |
+
print('Loaded the pretrain NER_BERT_CRF model, epoch:',checkpoint['epoch'],'valid acc:',
|
| 373 |
+
checkpoint['valid_acc'], 'valid f1:', checkpoint['valid_f1'])
|
| 374 |
+
|
| 375 |
+
model.to(device)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
max_seq_length = 512
|
| 379 |
+
data_dir = 'none.txt'
|
| 380 |
+
|
| 381 |
+
def predict_sentence(sentence):
|
| 382 |
+
predict_string = sentence
|
| 383 |
+
predict_examples = DNRTIProcessor.get_predict_examples(data_dir,predict_string = predict_string)
|
| 384 |
+
predict_dataset = NerDataset(predict_examples,tokenizer,label_map,max_seq_length)
|
| 385 |
+
|
| 386 |
+
# model.eval()
|
| 387 |
+
with torch.no_grad():
|
| 388 |
+
demon_dataloader = data.DataLoader(dataset=predict_dataset,
|
| 389 |
+
batch_size=1,
|
| 390 |
+
shuffle=False,
|
| 391 |
+
num_workers=1,
|
| 392 |
+
collate_fn=NerDataset.pad)
|
| 393 |
+
for batch in demon_dataloader:
|
| 394 |
+
batch = tuple(t.to(device) for t in batch)
|
| 395 |
+
input_ids, input_mask, segment_ids, predict_mask, label_ids = batch
|
| 396 |
+
_, predicted_label_seq_ids = model(input_ids, segment_ids, input_mask)
|
| 397 |
+
# _, predicted = torch.max(out_scores, -1)
|
| 398 |
+
valid_predicted = torch.masked_select(predicted_label_seq_ids, predict_mask.bool())
|
| 399 |
+
# valid_label_ids = torch.masked_select(label_ids, predict_mask)
|
| 400 |
+
for i in range(1):
|
| 401 |
+
new_ids=predicted_label_seq_ids[i].cpu().numpy()[predict_mask[i].cpu().numpy()==1]
|
| 402 |
+
# print(list(map(lambda i: label_list[i], new_ids)))
|
| 403 |
+
xx = list(map(lambda i: label_list[i], new_ids))
|
| 404 |
+
result = " ".join(str(x) for x in list(map(lambda i: label_list[i], new_ids)))
|
| 405 |
+
for sss in xx:
|
| 406 |
+
if sss != "O":
|
| 407 |
+
pass
|
| 408 |
+
print("----------------")
|
| 409 |
+
print("source sentence: ", running_input)
|
| 410 |
+
print("result sentence: ", result)
|
| 411 |
+
|
| 412 |
+
if __name__ == '__main__':
|
| 413 |
+
|
| 414 |
+
parser = argparse.ArgumentParser()
|
| 415 |
+
parser.add_argument('-I', '--input', required=True, type=str, default="", help="Please enter the OSINT or CTI senetences.")
|
| 416 |
+
arguments = parser.parse_args(sys.argv[1:])
|
| 417 |
+
running_input = arguments.input
|
| 418 |
+
if running_input:
|
| 419 |
+
predict_sentence(running_input)
|
| 420 |
+
else:
|
| 421 |
+
print("Error!")
|