在BERT训练阶段,为了学习到上下文的信息,会对输入的句子进行屏蔽处理。屏蔽部分包括15%的词汇,其中80%被替换成屏蔽标记'[MASK]”,10%被替换成任意一个词,剩余10%保持不变。在预测过程中,需要预测被替换成屏蔽标记'[MASK]”的部分。
具体解决方法包括以下步骤:
1.准备输入:将输入句子转化成BERT预训练的输入格式。此外需要记录原句中哪些位置是需要替换成'[MASK]”标记的。
from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
def prepare_input(sentence): tokens = tokenizer.tokenize(sentence) tokens.insert(0, '[CLS]') tokens.append('[SEP]') masked_tokens = tokens[:] masked_indices = [] for i, token in enumerate(tokens): if token != '[CLS]' and token != '[SEP]': rand = random.random() if rand < 0.15: if rand < 0.1: masked_tokens[i] = '[MASK]' elif rand < 0.125: masked_indices.append(i) masked_tokens[i] = tokens[random.randint(1, len(tokens)-2)] else: masked_indices.append(i) masked_tokens[i] = '[MASK]' input_ids = tokenizer.convert_tokens_to_ids(masked_tokens) return input_ids, masked_indices
2.调用BERT:输入已经准备好的输入,并使用PyTorch运行BERT模型,得到对标记处的预测。
import torch from transformers import BertModel
model = BertModel.from_pretrained('bert-base-uncased')
def predict_masked_tokens(input_ids, masked_indices): input_ids = torch.tensor([input_ids]) with torch.no_grad(): output = model(input_ids) predictions = output[0].squeeze(0) masked_predictions = predictions[masked_indices] return masked_predictions
如果需要预测多个句子的被替换屏蔽标记的结果,可以将多个输入concatenate到一起并同时运行BERT模型。