繁体   English   中英

需要微调 BERT 模型以预测丢失的单词

[英]Need to Fine Tune a BERT Model to Predict Missing Words

我知道 BERT 有能力预测句子中的缺失词,这在句法上是正确的,在语义上是连贯的。 下面是一个示例代码:

import torch
from pytorch_pretrained_bert import BertTokenizer, BertForMaskedLM

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForMaskedLM.from_pretrained('bert-base-uncased')
model.eval(); # turning off the dropout

def fill_the_gaps(text):
   text = '[CLS] ' + text + ' [SEP]'
   tokenized_text = tokenizer.tokenize(text)
   indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)
   segments_ids = [0] * len(tokenized_text)
   tokens_tensor = torch.tensor([indexed_tokens])
   segments_tensors = torch.tensor([segments_ids])
   with torch.no_grad():
      predictions = model(tokens_tensor, segments_tensors)
   results = []
   for i, t in enumerate(tokenized_text):
       if t == '[MASK]':
           predicted_index = torch.argmax(predictions[0, i]).item()
           predicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]
           results.append(predicted_token)
   return results

 print(fill_the_gaps(text = 'I bought an [MASK] because its rainy .'))
 print(fill_the_gaps(text = 'Im sad because you are [MASK] .'))
 print(fill_the_gaps(text = 'Im worried because you are [MASK] .'))
 print(fill_the_gaps(text = 'Im [MASK] because you are [MASK] .'))

有人可以向我解释一下,我是否需要微调 BERT 模型来预测丢失的单词,还是只使用预先训练好的 BERT 模型? 谢谢。

BERT 是一种掩码语言模型,这意味着它正是针对此任务进行训练的。 这就是为什么它可以做到。 所以从这个意义上说,不需要微调。

但是,如果您将在运行时看到的文本与 BERT 训练的文本不同,那么如果您对期望看到的文本类型进行微调,您的表现可能会好得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM