【发布时间】:2022-01-26 18:19:20
【问题描述】:
假设我们有一个这样的模板语句:
- “____ 家是我们的聚会场所。”
我们有一个形容词列表来填空,例如:
- “黄色”
- “大”
- ""
请注意,其中一个是空字符串。
目标是在给定句子上下文的情况下比较概率以选择最有可能描述“房子”的词。如果它更有可能什么都没有,也应该考虑到这一点。
我们可以预测每个单词填空的概率,但是我们如何预测没有形容词来描述“房子”的概率呢?
预测一个单词的概率:
from transformers import BertTokenizer, BertForMaskedLM
import torch
from torch.nn import functional as F
# Load BERT tokenizer and pre-trained model
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."
# Using BERT, compute probability over its entire vocabulary, returning 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)
# Run softmax over the logits to get the probabilities
softmax = F.softmax(output.logits[0], dim=-1)
# Find the words' probabilities in this probability distribution
target_probabilities = {t: softmax[mask_index, tokenizer.vocab[t]].numpy()[0] for t in targets}
target_probabilities
这会输出单词列表及其相关概率:
{'yellow': 0.0061520976, 'large': 0.00071377633}
如果我尝试向列表中添加一个空字符串,我会收到以下错误:
---------------------------------------------------------------------------
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]用在句尾,使一组句子的长度相同。)
【问题讨论】:
标签: python nlp huggingface-transformers bert-language-model