评估困惑度(perplexity)
动手生成文本并评估困惑度分数。
已为您提供一句话的开头 input_text:"Current trends show that by 2030 "。
使用一个 LLM 生成该句子的其余部分。
已为您加载 AutoModelForCausalLM 模型及其分词器,分别存放在变量 model 和 tokenizer 中。
本练习是课程的一部分
Python 中的 LLM 入门
练习说明
- 对
input_text进行编码,并将其传入提供的文本生成模型。 - 加载并计算生成文本的
mean_perplexity分数。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Encode the input text, generate and decode it
input_text_ids = ____(input_text, return_tensors="pt")
output = ____(input_text_ids, max_length=20)
generated_text = ____(output[0], skip_special_tokens=True)
print("Generated Text: ", generated_text)
# Load and compute the perplexity score
perplexity = ____("perplexity", module_type="metric")
results = ____(model_id="gpt2", predictions=____)
print("Perplexity: ", results['mean_perplexity'])