【发布时间】:2021-11-15 08:10:02
【问题描述】:
我正在为已经训练好的 NER 模型编写推理脚本,但我无法将编码的标记(它们的 id)转换为原始单词。
# example input
df = pd.DataFrame({'_id': [1], 'body': ['Amazon and Tesla are currently the best picks out there!']})
# calling method that handles inference:
ner_model = NER()
ner_model.recognize_from_df(df, 'body')
# here is only part of larger NER class that handles the inference:
def recognize_from_df(self, df: pd.DataFrame, input_col: str):
predictions = []
df = df[['_id', input_col]].copy()
dataset = Dataset.from_pandas(df)
# tokenization, padding, truncation:
encoded_dataset = dataset.map(lambda examples: self.bert_tokenizer(examples[input_col],
padding='max_length', truncation=True, max_length=512), batched=True)
encoded_dataset.set_format(type='torch', columns=['input_ids', 'attention_mask'], device=device)
dataloader = torch.utils.data.DataLoader(encoded_dataset, batch_size=32)
encoded_dataset_ids = encoded_dataset['_id']
for batch in dataloader:
output = self.model(**batch)
# decoding predictions and tokens
for i in range(batch['input_ids'].shape[0]):
tags = [self.unique_labels[label_id] for label_id in output[i]]
tokens = [t for t in self.bert_tokenizer.convert_ids_to_tokens(batch['input_ids'][i]) if t != '[PAD]']
...
结果接近我需要的:
# tokens:
['[CLS]', 'am', '##az', '##on', 'and', 'te', '##sla', 'are', 'currently', 'the', 'best', 'picks', 'out', 'there', ...]
# tags:
['X', 'B-COMPANY', 'X', 'X', 'O', 'B-COMPANY', 'X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', ...]
如何将'am', '##az', '##on'和'B-COMPANY', 'X', 'X'组合成一个token/tag?我知道Tokenizer中有一个叫convert_tokens_to_string的方法,但是它只返回一个大字符串,即很难映射到标签。
问候
【问题讨论】:
标签: python pytorch huggingface-transformers huggingface-tokenizers huggingface-datasets