#1286·bert

如何使用 BERT 预测空字符串的概率

作者: brienna创建于 2021年12月28日更新于 2024年5月20日

假设我们有一个这样的模板句子:

  • "The ____ house is our meeting place." 和一个用于填充空格的形容词列表,例如:
  • "yellow"
  • "large"
  • "" 请注意,其中一个是一个空字符串。 目标是比较概率,以选择在句子上下文中最有可能描述"房子"的单词。如果更有可能没有任何单词,这也应考虑到。 我们可以预测每个单词填充空格的概率,但我们如何预测一个空字符串填充空格的概率,即没有形容词来描述"房子"的概率呢? 要预测单词的概率:
python
from transformers import BertTokenizer, BertForMaskedLM 
import torch 
from torch.nn import functional as F 
# 加载 BERT 词汇表和预训练模型 
tokenizer = BertTokenizer.from_pretrained('bert-large-uncased') 
model = BertForMaskedLM.from_pretrained('bert-large-uncased', return_dict=True) 
targets = ["yellow", "large"] 
sentence = "The [MASK] house is our meeting place." 
# 使用 BERT,计算整个词汇中的概率,返回 logits 
input = tokenizer.encode_plus(sentence, return_tensors = "pt") 
mask_index = torch.where(input["input_ids"][0] == tokenizer.mask_token_id)[0] 
with torch.no_grad(): 
    output = model(**input) 
# 使用 softmax 运行 logits 以获取概率 
softmax = F.softmax(output.logits[0], dim=-1) 
# 在此概率分布中找到单词的概率 
target_probabilities = {t: softmax[mask_index, tokenizer.vocab[t]].numpy()[0] for t in targets} 
target_probabilities 
这输出了单词和它们相关的概率列表: 
```Python 
{'yellow': 0.0061520976, 'large': 0.00071377633} 
如果我尝试将一个空字符串添加到列表中,将出现以下错误: 
```Python 
--------------------------------------------------------------------------- 
KeyError                                  Traceback (most recent call last) 
<ipython-input-62-6f726220a108> in <module> 
     18 
     19 # Find the words' probabilities in this probability distribution 
---> 20 target_probabilities = {t: softmax[mask_index, tokenizer.vocab[t]].numpy()[0] for t in targets} 
     21 target_probabilities 
<ipython-input-62-6f726220a108> in <dictcomp>(.0) 
     18 
     19 # Find the words' probabilities in this probability distribution 
---> 20 target_probabilities = {t: softmax[mask_index, tokenizer.vocab[t]].numpy()[0] for t in targets} 
     21 target_probabilities 
KeyError: '' 
这是因为 BERT 的词汇中没有空字符串,因此我们无法查找模型中不存在的东西的概率。 
我们应该如何获得没有单词来填充空格的概率? 这是否可能使用模型? 使用空字符串 `[PAD]` 而不是空字符串是否有意义? (我只见过 `[PAD]` 在句子的末尾使用,以使一组句子具有相同的长度。) 
…

内容来源: google-research/bert