Pipeline 快速入门
Pipeline 是 Transformers 库提供的高层 API,让你能够用最简单的代码完成复杂的机器学习任务。本章将详细介绍 Pipeline 的使用方法和各种任务类型。
什么是 Pipeline?
Pipeline 是一个抽象层,它将模型加载、预处理、推理和后处理封装在一起,让你只需几行代码就能使用最先进的预训练模型。
┌─────────────────────────────────────────────────────────────┐
│ Pipeline 工作流程 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 输入文本 预处理 模型推理 后处理 │
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │
│ │ "Hello"│───▶│ Token │───▶│ Model │──▶│ 结果 │ │
│ │ World │ │ izer │ │ Forward│ │解析 │ │
│ └────────┘ └────────┘ └────────┘ └────────┘ │
│ │ │
│ ▼ │
│ ┌────────┐ │
│ │ logits │ │
│ └────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
基本使用
最简单的示例
from transformers import pipeline
# 创建情感分析 Pipeline
classifier = pipeline("sentiment-analysis")
# 进行预测
result = classifier("I love using Hugging Face Transformers!")
print(result)
# [{'label': 'POSITIVE', 'score': 0.9998765}]
指定模型
# 使用特定的预训练模型
classifier = pipeline(
"sentiment-analysis",
model="nlptown/bert-base-multilingual-uncased-sentiment"
)
# 这个模型支持多语言
result = classifier("我爱使用 Hugging Face!")
print(result)
批量处理
# Pipeline 支持批量输入,效率更高
texts = [
"I love this product!",
"This is terrible...",
"It's okay, nothing special."
]
results = classifier(texts)
for text, result in zip(texts, results):
print(f"{text} -> {result['label']}")
支持的任务类型
自然语言处理任务
| 任务 | Pipeline 名称 | 说明 |
|---|---|---|
| 情感分析 | sentiment-analysis | 分析文本情感倾向 |
| 文本分类 | text-classification | 通用文本分类 |
| 命名实体识别 | ner | 识别文本中的实体 |
| 问答 | question-answering | 抽取式问答 |
| 文本生成 | text-generation | 生成文本续写 |
| 摘要 | summarization | 生成文本摘要 |
| 翻译 | translation_xx_to_yy | 机器翻译 |
| 填充掩码 | fill-mask | 预测被遮盖的词 |
| 特征提取 | feature-extraction | 提取文本特征向量 |
| 零样本分类 | zero-shot-classification | 无需训练的分类 |
计算机视觉任务
| 任务 | Pipeline 名称 | 说明 |
|---|---|---|
| 图像分类 | image-classification | 识别图像内容 |
| 目标检测 | object-detection | 检测图像中的物体 |
| 图像分割 | image-segmentation | 像素级分割 |
音频任务
| 任务 | Pipeline 名称 | 说明 |
|---|---|---|
| 语音识别 | automatic-speech-recognition | 语音转文字 |
| 音频分类 | audio-classification | 识别音频类型 |
详细任务示例
1. 情感分析
from transformers import pipeline
# 创建情感分析器
classifier = pipeline("sentiment-analysis")
# 单条文本
result = classifier("The movie was absolutely fantastic!")
print(result)
# [{'label': 'POSITIVE', 'score': 0.9998}]
# 批量处理
texts = [
"I really enjoyed the concert.",
"The service was disappointing.",
"It's just average, nothing special."
]
results = classifier(texts)
for text, res in zip(texts, results):
print(f"{text}")
print(f" -> {res['label']} (confidence: {res['score']:.4f})\n")
2. 命名实体识别(NER)
# 创建 NER Pipeline
ner_pipeline = pipeline("ner", aggregation_strategy="simple")
# 识别文本中的实体
text = "Apple Inc. is planning to open a new store in Paris next year. Tim Cook announced the news."
results = ner_pipeline(text)
for entity in results:
print(f"实体: {entity['word']}")
print(f"类型: {entity['entity_group']}")
print(f"置信度: {entity['score']:.4f}")
print()
3. 问答系统
# 创建问答 Pipeline
qa_pipeline = pipeline("question-answering")
# 准备上下文和问题
context = """
Hugging Face is a company that develops tools for building applications using machine learning.
It is most notable for its Transformers library built for natural language processing applications.
"""
question = "What is Hugging Face most notable for?"
# 获取答案
result = qa_pipeline(question=question, context=context)
print(f"问题: {question}")
print(f"答案: {result['answer']}")
print(f"置信度: {result['score']:.4f}")
4. 文本生成
# 创建文本生成 Pipeline
generator = pipeline("text-generation", model="gpt2")
# 生成文本
prompt = "The future of artificial intelligence is"
results = generator(
prompt,
max_length=50,
num_return_sequences=3,
temperature=0.7,
do_sample=True
)
for i, result in enumerate(results, 1):
print(f"生成结果 {i}:")
print(result['generated_text'])
print()
5. 翻译
# 创建翻译 Pipeline(中译英)
translator = pipeline("translation_zh_to_en")
# 翻译文本
result = translator("今天天气真好,我们一起去公园吧!")
print(result[0]['translation_text'])
# "The weather is really nice today, let's go to the park together!"
6. 零样本分类
# 创建零样本分类 Pipeline
classifier = pipeline("zero-shot-classification")
# 待分类的文本
text = "The new movie is about a detective solving a mysterious murder case."
# 定义候选标签
candidate_labels = ["technology", "entertainment", "business", "sports"]
# 进行分类
result = classifier(text, candidate_labels)
print(f"文本: {text}")
print(f"最可能的类别: {result['labels'][0]}")
print(f"置信度: {result['scores'][0]:.4f}")
print(f"所有类别概率: {list(zip(result['labels'], result['scores']))}")
7. 图像分类
from transformers import pipeline
# 创建图像分类 Pipeline
classifier = pipeline("image-classification")
# 指定图片(可以是 URL 或本地路径)
result = classifier(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png"
)
for item in result:
print(f"类别: {item['label']}, 置信度: {item['score']:.4f}")
8. 目标检测
from transformers import pipeline
# 创建目标检测 Pipeline
detector = pipeline("object-detection")
# 检测图像中的物体
result = detector("https://images.unsplash.com/photo-1546961342-ea5f60a09d8b?w=400")
for item in result:
print(f"物体: {item['label']}")
print(f"置信度: {item['score']:.4f}")
print(f"边界框: {item['box']}")
print()
高级配置
指定设备
from transformers import pipeline
import torch
# 自动检测可用设备
device = 0 if torch.cuda.is_available() else -1 # -1 表示 CPU
classifier = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english",
device=device
)
自定义模型和分词器
from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer
# 加载自定义模型和分词器
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# 创建 Pipeline
classifier = pipeline(
"sentiment-analysis",
model=model,
tokenizer=tokenizer
)
result = classifier("This is amazing!")
print(result)
调整推理参数
# 文本生成的高级配置
generator = pipeline("text-generation", model="gpt2")
results = generator(
"Once upon a time",
max_length=100,
num_return_sequences=2,
temperature=0.8, # 控制随机性
top_k=50, # Top-K 采样
top_p=0.95, # Top-P 采样
do_sample=True, # 使用采样
repetition_penalty=1.2 # 惩罚重复生成
)
for result in results:
print(result['generated_text'])
Pipeline 内部原理
理解 Pipeline 的工作原理有助于你更好地使用它:
# Pipeline 内部执行的步骤
from transformers import pipeline
# 1. 创建 Pipeline
classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
# 2. Pipeline 内部执行以下步骤:
# Step 1: 预处理 - 将文本转换为模型输入
inputs = classifier.preprocess("I love this movie!")
# 返回: {'input_ids': tensor, 'attention_mask': tensor}
# Step 2: 模型推理
outputs = classifier.forward(inputs)
# 返回: 模型的 logits 输出
# Step 3: 后处理 - 将 logits 转换为可读结果
predictions = classifier.postprocess(outputs)
# 返回: [{'label': 'POSITIVE', 'score': 0.9998}]
常见问题
1. 模型下载慢
# 设置国内镜像(国内用户)
import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
2. 显存不足
# 使用 CPU
classifier = pipeline("sentiment-analysis", device=-1)
# 或使用更小的模型
classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
3. 批量处理提高效率
# 批量处理比逐条处理效率高
texts = ["text1", "text2", "text3", "text4"]
# 低效方式
for text in texts:
result = classifier(text)
# 高效方式
results = classifier(texts) # 一次性处理所有文本
最佳实践
1. 复用 Pipeline 对象
# 不要在循环中创建 Pipeline
# 低效
for text in texts:
classifier = pipeline("sentiment-analysis") # 每次都重新加载模型
result = classifier(text)
# 高效
classifier = pipeline("sentiment-analysis") # 创建一次
for text in texts:
result = classifier(text)
2. 使用批量处理
# 尽量一次性处理多条数据
results = classifier(list_of_texts) # 比循环处理快很多
3. 选择合适的模型
# 根据任务选择专用模型
# 情感分析
classifier = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
# 中文任务使用中文模型
classifier = pipeline("sentiment-analysis", model="uer/roberta-base-finetuned-jd-binary-chinese")
下一步
掌握 Pipeline 的使用后,你可以继续学习: