使用预训练的 LLM

Python 中的 LLM 入门

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

语言理解

一个人坐在桌前,周围是多项任务,展示文本分类、摘要、情感分析和问答

Python 中的 LLM 入门

语言生成

一个人坐在桌前,周围是多项任务,展示文本生成与翻译

Python 中的 LLM 入门

文本生成

generator = pipeline(task="text-generation", model="distilgpt2")

prompt = "The Gion neighborhood in Kyoto is famous for"

output = generator(prompt, max_length=100, pad_token_id=generator.tokenizer.eos_token_id)
  • 连贯
  • 有意义
  • 类似人类的文本
  • eos_token_id:序列结束标记 ID
Python 中的 LLM 入门

文本生成

两个序列示意图:we should go、i really like to travel。包含 token id,并显示填充与 EOS 位置

  • pad_token_id:把序列填充到 max_length
  • 加填充(padding):添加标记
  • 设为 generator.tokenizer.eos_token_id 表示有意义文本结束,模型在训练中学到
  • 模型生成至 max_length 或遇到 pad_token_id
  • truncation = True
Python 中的 LLM 入门

文本生成

generator = pipeline(task="text-generation", model="distilgpt2")

prompt = "The Gion neighborhood in Kyoto is famous for"

output = generator(prompt, max_length=100, pad_token_id=generator.tokenizer.eos_token_id)

print(output[0]["generated_text"])
The Gion neighborhood in Kyoto is famous for its many colorful green forests, such as the 
Red Hill, the Red River and the Red River. The Gion neighborhood is home to the world's 
tallest trees.
  • 如果提示含糊,输出可能不佳
Python 中的 LLM 入门

引导输出

generator = pipeline(task="text-generation", model="distilgpt2")


review = "This book was great. I enjoyed the plot twist in Chapter 10." response = "Dear reader, thank you for your review." prompt = f"Book review:\n{review}\n\nBook shop response to the review:\n{response}"
output = generator(prompt, max_length=100, pad_token_id=generator.tokenizer.eos_token_id) print(output[0]["generated_text"])
Dear reader, thank you for your review. We'd like to thank you for your reading!
Python 中的 LLM 入门

语言翻译

  • Hugging Face 提供完整的翻译任务与模型列表
translator = pipeline(task="translation_en_to_es", model="Helsinki-NLP/opus-mt-en-es")

text = "Walking amid Gion's Machiya wooden houses was a mesmerizing experience."
output = translator(text, clean_up_tokenization_spaces=True)
print(output[0]["translation_text"])
Caminar entre las casas de madera Machiya de Gion fue una experiencia fascinante.
Python 中的 LLM 入门

开始练习吧!

Python 中的 LLM 入门

Preparing Video For Download...