【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!")
相关推荐
spider'几秒前
ROS2开发环境搭建
人工智能
Yiyaoshujuku8 分钟前
医院API接口,从医院真实世界数据HIS、LJS、EMR、PACS系统到医院药品流向数据....
大数据·前端·人工智能
STLearner12 分钟前
AI论文速读 | 元认知监控赋能深度搜索:认知神经科学启发的分层优化框架
大数据·论文阅读·人工智能·python·深度学习·学习·机器学习
AI浩21 分钟前
第 2 章:Claude Code 环境搭建与API配置。
人工智能·目标检测
不一样的故事12629 分钟前
抓重点、留弹性、重节奏
大数据·网络·人工智能·安全
another heaven35 分钟前
【深度学习 超参调优】optimizer=‘SGD‘ / ‘AUTO‘
人工智能·深度学习
balmtv38 分钟前
从“知识检索”到“深度推理”:Gemini 3.1如何用三层思考模式解决学术难题
人工智能·gpt·chatgpt
2501_9269783341 分钟前
《与AI的妄想对话:如何给机器人造灵魂?》
人工智能·深度学习·机器学习·ai写作·agi
程序员Shawn43 分钟前
【机器学习 | 第三篇】- 线性回归
人工智能·机器学习·线性回归
东离与糖宝1 小时前
Gradle 9.4+Java26:大型项目构建提速100倍实战配置
java·人工智能