【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!")
相关推荐
Jucai_in_AI16 分钟前
AI岗位能力建模:从一份岗位说明书到一张胜任力图谱的技术路线
人工智能·产品
HIT_Weston18 分钟前
233、【AI】【模型部署】基座模型研究:基座与 Instruct 的差别
人工智能·模型部署
周杰伦fans27 分钟前
构建真正智能的CAD AI绘图代理
开发语言·人工智能·c#
u01110267528 分钟前
Blob URL 与 Base64 怎么选?图片预览中的内存和性能差异
人工智能·深度学习·ai作画
LaughingZhu36 分钟前
Product Hunt 每日热榜 | 2026-09-24
人工智能·深度学习·神经网络·搜索引擎·百度
AI早餐汇1 小时前
飞猪首席技术官陈烨丨飞猪AI Native研发一年实录
人工智能
桃西西呀1 小时前
Laya 源码级原理拆解之一:整体架构与运行入口
人工智能·llm·ai编程
拉你进_教堂1 小时前
小龙虾技能之【Intelligent Public Smoking Detection Skill | 公共场所吸烟行为智能检测技能】简介
人工智能·计算机视觉·多模态大模型·openclaw小龙虾技能
ShineWinsu1 小时前
RAG 进阶:知识库构建优化全解析——从分块策略、元数据增强到层级索引与知识图谱
人工智能·知识图谱
吴佳浩2 小时前
Agent 安全红线:越狱防御、间接注入与数据防泄漏实战
人工智能·agent·ai编程