Hugging Face 的 Transformers 库快速入门 (一)开箱即用的 pipelines

注:本系列教程仅供学习使用, 由原作者授权, 均转载自小昇的博客



前言

Transformers 是由 Hugging Face 开发的一个 NLP 包,支持加载目前绝大部分的预训练模型。随着 BERT、GPT 等大规模语言模型的兴起,越来越多的公司和研究者采用 Transformers 库来构建 NLP 应用,因此熟悉 Transformers 库的使用方法很有必要。

注:本系列教程只专注于处理文本,多模态方法请查阅相关文档


开箱即用的 pipelines

Transformers 库将目前的 NLP 任务归纳为几下几类:

  • 文本分类: 例如情感分析、句子对关系判断等;
  • 对文本中的词语进行分类: 例如词性标注 (POS)、命名实体识别 (NER) 等;
  • 文本生成: 例如填充预设的模板 (prompt)、预测文本中被遮掩掉 (masked) 的词语;
  • 从文本中抽取答案: 例如根据给定的问题从一段文本中抽取出对应的答案;
  • 根据输入文本生成新的句子: 例如文本翻译、自动摘要等。

Transformers 库最基础的对象就是 pipeline() 函数,它封装了预训练模型和对应的前处理和后处理环节。我们只需输入文本,就能得到预期的答案。目前常用的 pipelines 有:

  • feature-extraction (获得文本的向量化表示)
  • fill-mask (填充被遮盖的词、片段)
  • ner (命名实体识别)
  • question-answering (自动问答)
  • sentiment-analysis (情感分析)
  • summarization (自动摘要)
  • text-generation (文本生成)
  • translation (机器翻译)
  • zero-shot-classification (零训练样本分类)

下面我们以常见的几个 NLP 任务为例,展示如何调用这些 pipeline 模型。


情感分析

借助情感分析 pipeline,我们只需要输入文本,就可以得到其情感标签(积极/消极)以及对应的概率:

from transformers import pipeline

classifier = pipeline("sentiment-analysis")
result = classifier("I've been waiting for a HuggingFace course my whole life.")
print(result)
results = classifier(
  ["I've been waiting for a HuggingFace course my whole life.", "I hate this so much!"]
)
print(results)
No model was supplied, defaulted to distilbert-base-uncased-finetuned-sst-2-english (https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english)

[{
   
   'label': 'POSITIVE', 'score': 0.9598048329353333}]
[{
   
   'label': 'POSITIVE', 'score': 0.9598048329353333}, {
   
   'label': 'NEGATIVE', 'score': 0.9994558691978455}]

pipeline 模型会自动完成以下三个步骤:

  1. 将文本预处理为模型可以理解的格式;
  2. 将预处理好的文本送入模型;
  3. 对模型的预测值进行后处理,输出人类可以理解的格式。

pipeline 会自动选择合适的预训练模型来完成任务。例如对于情感分析,默认就会选择微调好的英文情感模型 distilbert-base-uncased-finetuned-sst-2-english

Transformers 库会在创建对象时下载并且缓存模型,只有在首次加载模型时才会下载,后续会直接调用缓存好的模型。


零训练样本分类

零训练样本分类 pipeline 允许我们在不提供任何标注数据的情况下自定义分类标签。

from transformers import pipeline

classifier = pipeline("zero-shot-classification")
result = classifier(
"This is a course about the Transformers library",
candidate_labels=["education", "politics", "business"],
)
print(result)
No model was supplied, defaulted to facebook/bart-large-mnli (https://huggingface.co/facebook/bart-large-mnli)

{
   
   'sequence': 'This is a course about the Transformers library', 
 'labels': ['education', 'business', 'politics'], 
 'scores': [0.8445973992347717, 0.11197526752948761, 0.043427325785160065]}

可以看到,pipeline 自动选择了预训练好的 facebook/bart-large-mnli 模型来完成任务。

文本生成

我们首先根据任务需要构建一个模板 (prompt),然后将其送入到模型中来生成后续文本。注意,由于文本生成具有随机性,因此每次运行都会得到不同的结果。

这种模板被称为前缀模板 (Prefix Prompt),了解更多详细信息可以查看《Prompt 方法简介》

from transformers import pipeline

generator = pipeline("text-generation")
results = generator("In this course, we will teach you how to")
print(results)
results = generator(
    "In this course, we will teach you how to",
    num_return_sequences=2,
    max_length=50
) 
print(results)
No model was supplied, defaulted to gpt2 (https://huggingface.co/gpt2)

[{
   
   'generated_text': "In this course, we will teach you how to use data and models that can be applied in any real-world, everyday situation. In most cases, the following will work better than other courses I've offered for an undergrad or student. In order"
<think>好的,用户之前问过Python中的开源大模型应用项目,我介绍了Hugging Face Transformers等项目。现在用户想知道如何学习Hugging Face Transformers,我需要提供个详细的学习路径。 首先,用户可能是刚接触这个的开发者或学生,他们需要从基础到进阶的学习资源。我应该考虑他们可能的学习方式,比如官方文档、实践项目、社区资源等。 接下来,我需要回忆Transformers的主要功能,比如模型加载、微调、管道使用等。用户可能需要知道如何快速上手,所以分步骤的方法比较有效。例如,先安装,再学习基础API,然后进行微调,最后参与实际项目。 另外,用户可能有不同的学习习惯,有的人喜欢看教程,有的喜欢动手实践。因此,我应该涵盖多种资源类型,如官方教程、视频课程、书籍、社区支持等。 还要注意常见的问题,比如如何处理中文任务,是否需要中文资源。之前提到的Chinese-LLaMA-Alpaca和ChatGLM-6B可能相关,可以推荐他们在中文场景下的应用。 用户可能在学习过程中遇到困难,比如环境配置、调试问题,或者对理论不理解。这时候推荐社区和论坛会有帮助,比如Hugging Face论坛和Stack Overflow。 最后,要强调持续学习的重要性,因为的更新很快,建议用户关注官方动态和最新论文,保持知识更新。总结学习路径的结构,让用户有清晰的路线图。</think>以下是学习Hugging Face Transformers的**系统性路径**,结合官方资源和实践技巧,适合从入门到进阶: --- ### 、基础准备 1. **前置知识** - 掌握Python基础(函数、类、装饰器) - 理解PyTorch/TensorFlow张量操作和自动求导 - 了解Transformer架构(注意力机制、位置编码) 2. **环境安装** ```bash pip install transformers datasets evaluate # 按需安装深度学习框架 pip install torch # 或 tensorflow ``` --- ### 二、官方学习路线(必看) 1. **官方快速入门教程** - [Hugging Face官方课程](https://huggingface.co/learn)(免费互动式教程,含代码沙盒) - 重点章节: - Pipeline API快速调用模型 - Tokenizer的工作原理 - 微调预训练模型 2. **文档精读顺序** 1. [核心API文档](https://huggingface.co/docs/transformers/main_classes/pipelines):`pipeline`, `AutoModel`, `AutoTokenizer` 2. [微调指南](https://huggingface.co/docs/transformers/training):分类、问答、文本生成任务 3. [模型共享与上传](https://huggingface.co/docs/transformers/model_sharing):将训练好的模型发布到Hub --- ### 三、分阶段实践项目 #### 阶段1:API快速调用 ```python from transformers import pipeline # 情感分析 classifier = pipeline("sentiment-analysis") print(classifier("I love coding with Transformers!")) # 文本生成 generator = pipeline("text-generation", model="gpt2") print(generator("In a shocking discovery, scientists found", max_length=100)) ``` #### 阶段2:自定义模型与训练 ```python from transformers import AutoTokenizer, AutoModelForSequenceClassification from datasets import load_dataset # 加载数据集和模型 dataset = load_dataset("imdb") tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased") # 数据预处理 def tokenize_function(examples): return tokenizer(examples["text"], padding="max_length", truncation=True) tokenized_datasets = dataset.map(tokenize_function, batched=True) # 微调训练 from transformers import TrainingArguments, Trainer training_args = TrainingArguments(output_dir="test_trainer") trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_datasets["train"].shuffle(seed=42).select(range(1000)), eval_dataset=tokenized_datasets["test"].shuffle(seed=42).select(range(1000)), ) trainer.train() ``` #### 阶段3:高级应用 - **部署为API服务**:使用`gradio`或`FastAPI`封装模型 - **量化压缩**:应用`bitsandbytes`进行8bit/4bit量化 - **多模态实践**:尝试CLIP(图文匹配)、Whisper(语音识别) --- ### 四、学习资源推荐 1. **书籍** - 《Natural Language Processing with Transformers》(O'Reilly官方书) - 《动手学深度学习》(李沐,含Transformer实现解析) 2. **视频教程** - [Hugging Face官方YouTube频道](https://www.youtube.com/@HuggingFace)(更新频繁) - [吴恩达《ChatGPT提示工程》](https://www.deeplearning.ai/short-courses/)(免费短课) 3. **中文资源** - [Hugging Face中文文档](https://huggingface.co/docs/transformers/zh) - [抱抱脸社区中文博客](https://huggingface.co/blog/zh) --- ### 五、调试与优化技巧 1. **常见错误处理**: - `CUDA out of memory`:减小`batch_size`,启用梯度累积 - 输入长度超限:调整`max_length`或使用长文本处理模型 2. **性能优化**: ```python # 启用混合精度训练 from transformers import TrainingArguments training_args = TrainingArguments(fp16=True) # 使用BetterTransformer加速 model = model.to_bettertransformer() ``` --- ### 六、持续学习 1. 关注[Hugging Face博客](https://huggingface.co/blog)获取最新模型(如Llama 3、Mistral) 2. 参与社区活动: - 在[模型Hub](https://huggingface.co/models)复现Paper实现 - 参加[Hugging Face竞赛](https://huggingface.co/competitions) --- **学习关键点**:先通过Pipeline快速实现功能建立信心,再深入理解Tokenizer和模型结构,最后通过微调掌握全流程。遇到问题时善用[论坛](https://discuss.huggingface.co/)提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值