【NLP】32. Transformers (HuggingFace Pipelines 实战)

🤖 Transformers (HuggingFace Pipelines 实战)

本教程基于 Hugging Face 的 transformers 库,展示如何使用预训练模型完成以下任务:

  • 情感分析(Sentiment Analysis)
  • 文本生成(Text Generation)
  • 翻译(Translation)
  • 掩码填空(Masked Language Modeling)
  • 零样本分类(Zero-shot Classification)
  • 特定任务模型推理(Text2Text Generation, e.g., T5)
  • 文本摘要(Summarization)
  • 自定义分类模型载入与推理(如 BERT)

📦 安装依赖

python 复制代码
!pip install datasets evaluate transformers sentencepiece -q

✅ 情感分析

python 复制代码
from transformers import pipeline

classifier = pipeline("sentiment-analysis")

# 单个句子
classifier("I really enjoy learning new things every day.")

# 多个句子
classifier([
    "I really enjoy learning new things every day.",
    "I dislike rainy weather on weekends."
])

✍️ 文本生成(默认模型)

python 复制代码
from transformers import pipeline

generator = pipeline("text-generation")
generator("Today we are going to explore something exciting")

🎯 文本生成(指定参数)

python 复制代码
# 两句话,每句最多15词
generator("Today we are going to explore something exciting", num_return_sequences=2, max_length=15)

⚙️ 使用 distilgpt2 模型生成文本

python 复制代码
from transformers import pipeline

generator = pipeline("text-generation", model="distilgpt2")
generator(
    "Today we are going to explore something exciting",
    max_length=30,
    num_return_sequences=2,
)

🌍 翻译(英语→德语)

python 复制代码
from transformers import pipeline

translator = pipeline("translation_en_to_de")
translator("This is a great day to learn something new!")

🧩 掩码填空任务(填词)

python 复制代码
from transformers import pipeline

unmasker = pipeline("fill-mask")
unmasker("Life is like a <mask> of chocolates.")

🧠 零样本分类(Zero-shot Classification)

python 复制代码
from transformers import pipeline

classifier = pipeline("zero-shot-classification")
classifier(
    "This tutorial is about machine learning and natural language processing.",
    candidate_labels=["education", "sports", "politics"]
)

🔁 T5 模型(Text2Text)

python 复制代码
from transformers import pipeline

text2text = pipeline("text2text-generation")
text2text("Translate English to French: How are you today?")

✂️ 文本摘要(Summarization)

python 复制代码
from transformers import pipeline

summarizer = pipeline("summarization")
summarizer(
    "Machine learning is a field of artificial intelligence that focuses on enabling machines to learn from data..."
)

🧪 使用自己的模型(以 BERT 为例)

python 复制代码
from transformers import BertTokenizer, BertForSequenceClassification
from transformers import pipeline

model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForSequenceClassification.from_pretrained(model_name)

pipe = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
pipe("I had an amazing experience with this product!")
相关推荐
田里的水稻9 分钟前
FA_CNN卷积神经网络七---优化器PyTorch
人工智能·pytorch·深度学习·神经网络·cnn
智能直播1 小时前
RK3518:1.5G 内存 + 8G 存储,如何跑起硬件编解码、Web、AI 识别、绿幕特效
前端·人工智能·5g
大模型真好玩1 小时前
初试短视频生成:豆包将我梦中的场景画出来了~
人工智能·agent·deepseek
梦想出海-Phoebe2 小时前
AI Agent能实现自主复制吗?Anthropic研究揭示模型部署与IoT设备安全问题
人工智能·物联网·安全
指针向南2 小时前
PDF转长图用什么?3种方法实测(2026)
图像处理·人工智能·计算机视觉·pdf
郝学胜-神的一滴2 小时前
AI 编程智能体 09:零门槛调用教程
人工智能·数据分析·自动化·numpy·pandas·量化投资
商业看点解说2 小时前
支持私有化部署的 AI 助手有哪些?把“私有化“拆成四层,排除一类常被错放的产品
大数据·人工智能
清华kenny2 小时前
安徽晓得养HIS系统适合哪类健康机构升级使用
大数据·人工智能·安徽晓得养
kyriewen2 小时前
我抽查了 6 万个 Skills:前排没几个真货
人工智能·程序员·ai编程
掘金酱2 小时前
【10.24 特别活动】AI 时代,程序员的新饭碗在哪里?
前端·人工智能·后端