我正在尝试编写一个程序,给定一个句子列表,该程序返回最可能的句子。我想使用GPT-2,但是我对使用它很陌生(因为我真的不知道该怎么做)。我打算在给定前一个单词的情况下找到一个单词的概率,并将所有概率相乘以获得该句子出现的总体概率,但是我不知道如何在给定前一个单词的情况下找到一个单词出现的概率。这是我的(伪)代码:
sentences = # my list of sentences
max_prob = 0
best_sentence = sentences[0]
for sentence in sentences:
prob = 1 #probability of that sentence
for idx, word in enumerate(sentence.split()[1:]):
prob *= probability(word, " ".join(sentence[:idx])) # this is where I need help
if prob > max_prob:
max_prob = prob
best_sentence = sentence
print(best_sentence)
请给我一些帮助吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import numpy as np
model = GPT2LMHeadModel.from_pretrained('gpt2')
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
def score(tokens_tensor):
loss=model(tokens_tensor, labels=tokens_tensor)[0]
return np.exp(loss.cpu().detach().numpy())
texts = ['i would like to thank you mr chairman', 'i would liking to thanks you mr chair in', 'thnks chair' ]
for text in texts:
tokens_tensor = tokenizer.encode( text, add_special_tokens=False, return_tensors="pt")
print (text, score(tokens_tensor))
此代码段可能是您正在寻找的示例。您用一个句子列表为模型提供数据,并给每个句子评分,而得分越低越好。
上面的代码输出为:
i would like to thank you mr chairman 122.3066
i would liking to thanks you mr chair in 1183.7637
thnks chair 14135.129
答案 2 :(得分:0)
我写了一组 functions 可以准确地满足您的要求。回想一下 GPT-2 将其输入解析为标记(而不是单词):“Joe flicked the蚱蜢”中的最后一个单词实际上是三个标记:“grass”、“ho”和“pper”。 cloze_finalword
函数将这一点考虑在内,并计算所有标记的概率(以出现在它们之前的标记为条件)。您可以修改此函数的一部分,使其返回您要查找的内容。我希望你觉得代码有用!