【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!")
相关推荐
DanCheOo15 分钟前
AI 应用的安全架构:Prompt 注入、数据泄露、权限边界
前端·人工智能·prompt·安全架构
刘~浪地球30 分钟前
DeepSeek V4 安全性与伦理:AI发展之路的思考
人工智能·deepseek v4
DanCheOo30 分钟前
开源 | ai-memory v2.6.2:不用配 API Key,一行命令把 Cursor 对话变成结构化知识库
人工智能·ai·ai编程
木枷31 分钟前
rl/swe/sft相关论文列表
人工智能·深度学习
爱学习的张大34 分钟前
具身智能论文精度(八):Pi0.6
人工智能·深度学习
析稿AI写作34 分钟前
如何系统整合文献资源,写出有理论根基与深度的学术论文?
人工智能·ai写作·论文笔记
EnCi Zheng38 分钟前
02-序列到序列模型
人工智能·神经网络·transformer
一起学开源42 分钟前
企业级AI应用开发底座应该怎么设计?
人工智能·系统架构·智能体
生成论实验室1 小时前
《事件关系阴阳博弈动力学:识势应势之道》第二篇:阴阳博弈——认知的动力学基础
数据结构·人工智能·科技·神经网络·算法
guslegend1 小时前
第3章:快速入门SpringAI Alibaba
人工智能·springai