【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!")
相关推荐
pen-ai19 分钟前
【NLP】 26. 语言模型原理与概率建模方法详解(Language Models)
人工智能·语言模型·自然语言处理
pen-ai21 分钟前
【NLP】30. 深入理解 In-Context Learning 的核心机制与策略
人工智能·自然语言处理
知舟不叙26 分钟前
使用 OpenCV 和 Dlib实现轮廓绘制
人工智能·opencv·计算机视觉·轮廓绘制·人脸关键点检测
struggle20251 小时前
Sim Studio 是一个开源的代理工作流程构建器。Sim Studio 的界面是一种轻量级、直观的方式,可快速构建和部署LLMs与您最喜欢的工具连接
人工智能·开源·deepseek
武子康1 小时前
大语言模型 06 - 从0开始训练GPT 0.25B参数量 - MiniMind 实机配置 GPT训练基本流程概念
人工智能·gpt·ai·语言模型·自然语言处理
CodeJourney.1 小时前
基于DeepSeek与HTML的可视化图表创新研究
数据库·人工智能·信息可视化·excel
IT古董2 小时前
【漫话机器学习系列】234.阈值类特征的方差分析(Thresholding Categorical Feature Variance)
人工智能·python·机器学习
多巴胺与内啡肽.2 小时前
OpenCV进阶操作:图像直方图、直方图均衡化
人工智能·opencv·计算机视觉
白熊1882 小时前
【计算机视觉】3d人脸重建:3DDFA_V2:实时高精度3D人脸重建与密集对齐技术指南
人工智能·计算机视觉·3d
phoenix@Capricornus2 小时前
神经网络发展的时间线——积跬步至千里
人工智能·深度学习·神经网络