HuggingFace Transformers快速入门指南:从Pipeline到AutoClass

HuggingFace Transformers快速入门指南:从Pipeline到AutoClass

notebooks Notebooks using the Hugging Face libraries 🤗 notebooks 项目地址: https://gitcode.com/gh_mirrors/note/notebooks

前言

HuggingFace Transformers库已成为自然语言处理领域的标杆工具,它提供了简单易用的API和丰富的预训练模型。本文将带您快速了解Transformers的核心功能,包括Pipeline的便捷使用和AutoClass的灵活配置。

环境准备

在开始之前,我们需要安装必要的库:

pip install transformers datasets

如果您想从源码安装而非最新发布版本,可以使用以下命令:

pip install git+https://github.com/huggingface/transformers.git

Pipeline:快速推理的捷径

Pipeline是使用预训练模型最简单的方式,它封装了完整的推理流程,包括预处理、模型推理和后处理。

支持的任务类型

Transformers Pipeline支持多种常见任务:

文本任务

  • 情感分析:判断文本的情感倾向
  • 文本生成:基于给定输入生成文本
  • 命名实体识别(NER):标注文本中的实体类型
  • 问答系统:根据上下文回答问题
  • 掩码填充:填补文本中的空白部分
  • 文本摘要:生成长文本的摘要
  • 机器翻译:将文本翻译成另一种语言
  • 特征提取:生成文本的张量表示

图像任务

  • 图像分类
  • 图像分割
  • 目标检测

音频任务

  • 音频分类
  • 语音识别(ASR)

Pipeline使用示例

让我们以情感分析为例,展示Pipeline的基本用法:

from transformers import pipeline

# 创建情感分析Pipeline
classifier = pipeline("sentiment-analysis")

首次使用时,Pipeline会自动下载并缓存默认的预训练模型和分词器。现在我们可以对文本进行情感分析:

result = classifier("We are very happy to show you the 🤗 Transformers library.")
print(result)
# 输出: [{'label': 'POSITIVE', 'score': 0.9998}]

对于多个句子,可以传入列表:

results = classifier([
    "We are very happy to show you the 🤗 Transformers library.",
    "We hope you don't hate it."
])
for result in results:
    print(f"label: {result['label']}, with score: {round(result['score'], 4)}")

处理大型数据集

Pipeline还可以处理大型数据集,特别是音频或视觉数据:

import torch
from transformers import pipeline
from datasets import load_dataset, Audio

# 创建语音识别Pipeline
speech_recognizer = pipeline(
    "automatic-speech-recognition",
    model="facebook/wav2vec2-base-960h"
)

# 加载音频数据集
dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")

# 确保采样率匹配
dataset = dataset.cast_column(
    "audio", 
    Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate)
)

# 处理前4个样本
result = speech_recognizer(dataset[:4]["audio"])
print([d["text"] for d in result])

AutoClass:灵活加载模型和分词器

虽然Pipeline使用方便,但有时我们需要更灵活地控制模型和分词器。这时可以使用AutoClass。

AutoTokenizer

分词器负责将文本预处理为模型可理解的格式:

from transformers import AutoTokenizer

model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
tokenizer = AutoTokenizer.from_pretrained(model_name)

AutoModel

根据任务类型选择合适的AutoModel:

from transformers import AutoModelForSequenceClassification

model = AutoModelForSequenceClassification.from_pretrained(model_name)

对于TensorFlow用户:

from transformers import TFAutoModelForSequenceClassification

model = TFAutoModelForSequenceClassification.from_pretrained(model_name)

自定义Pipeline

有了模型和分词器后,我们可以创建自定义Pipeline:

classifier = pipeline(
    "sentiment-analysis", 
    model=model, 
    tokenizer=tokenizer
)
result = classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.")
print(result)
# 输出: [{'label': '5 stars', 'score': 0.7273}]

总结

本文介绍了HuggingFace Transformers的两个核心功能:

  1. Pipeline:提供开箱即用的模型推理能力,适合快速实现常见任务
  2. AutoClass:提供更灵活的模型和分词器加载方式,适合定制化需求

对于更复杂的任务,您可能需要在自己的数据上微调预训练模型。Transformers库也提供了完善的训练API支持这一过程。

notebooks Notebooks using the Hugging Face libraries 🤗 notebooks 项目地址: https://gitcode.com/gh_mirrors/note/notebooks

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

申芹琴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值