0%

Transformers(1)_快速使用

1. 基本介绍

1.1 HuggingFace

Hugging Face 是一个专注于人工智能和机器学习的开源社区和平台,它已经成为 AI 领域最重要的社区之一。

以下是它的主要特点:

  1. 核心产品
    • Transformers:最受欢迎的机器学习库之一,提供了大量预训练模型
    • Datasets:用于数据集的加载和处理
    • Spaces:用于部署和展示 AI 应用
    • Hub:模型、数据集和应用的共享平台
  2. 社区特色
    • 拥有超过 100,000 个开源模型
    • 活跃的开发者社区
    • 支持多种编程语言(主要是 Python)
    • 提供详细的文档和教程
  3. 主要优势
    • 开源友好:大多数工具和模型都是开源的
    • 易用性:提供了简单直观的 API
    • 模型丰富:覆盖 NLP、计算机视觉、音频等多个领域
    • 持续更新:定期发布新的模型和功能
  4. 使用场景
    • 研究人员进行 AI 实验
    • 开发者构建 AI 应用
    • 企业部署 AI 解决方案
    • 学习 AI 和机器学习的教育平台
  5. 商业模式
    • 提供免费的开源工具和模型
    • 提供企业级服务和解决方案
    • 提供云服务和 API 访问

Hugging Face 已经成为 AI 领域的一个”一站式”平台,无论是想要学习 AI、开发 AI 应用,还是部署 AI 解决方案,都可以在这里找到所需的资源和工具。它的出现大大降低了 AI 技术的使用门槛,推动了 AI 技术的普及和发展。

1.2 Transformers

🤗 Transformers是由Hugging Face开源,它是一个强大的机器学习工具库,它让使用先进的预训练模型变得简单高效。想象一下,它就像是一个”模型超市”,里面存放着各种经过预训练的智能模型,可以直接拿来使用,而不需要从零开始训练。

这个工具库的主要优势在于:

  1. 多领域支持:无论是处理文字、图片、音频,还是多模态任务(比如图文理解),都能找到合适的模型。
  2. 框架灵活:支持 PyTorchTensorFlowJAX 三大主流深度学习框架,你可以根据自己的需求选择使用哪个框架。
  3. 即用即得:提供了简单的 API 和工具,只需要几行代码就能下载和使用预训练模型,大大降低了使用门槛。
  4. 环保高效:使用预训练模型可以显著减少计算资源消耗和碳排放,同时节省从头训练所需的时间和资源。
  5. 部署友好:模型可以轻松导出为 ONNXTorchScript 格式,方便在生产环境中部署使用。
  6. 对于想要快速实现 AI功能的开发者来说,Transformers 就像是一个”即插即用”的解决方案,让你能够快速构建各种智能应用,而不需要深入理解复杂的模型细节。

2. 下载安装

在开始之前,确保你已经安装了所有必要的库:

1
pip install transformers datasets evaluate accelerate

此外,由于transformers是一个高阶库,所以还需要下载一个深度学习框架,可以是PyTorchTensorFlowJAX中的任意一个。但建议下载Pytorch,它的兼容性是最好的。
访问Pytorch官网根据自己的操作系统下载合适的Pytorch
例如:Ubuntu操作系统,CUDA 12.4环境下。

image-20250326175313943

使用以下命令进行下载

1
2
pip3 install torch torchvision torchaudio

3. 快速使用

3.1 使用transformers进行情感分析

1
2
3
4
from transformers import pipeline

model = 'models_save/distilroberta-finetuned-financial-news-sentiment-analysis/' # 预先下载好的模型文件
classifier = pipeline("sentiment-analysis", model=model)
Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.
1
classifier("We are very happy to show you the 🤗 Transformers library.")
[{'label': 'neutral', 'score': 0.9994151592254639}]

3.2 使用transformers进行问答

1
2
model = 'models_save/deepsetroberta-base-squad2/'
question_answerer = pipeline("question-answering", model=model)
Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.
1
2
3
4
question_answerer(
question="Where do I work?",
context="My name is Sylvain and I work at Hugging Face in Brooklyn",
)
{'score': 0.6549862623214722, 'start': 33, 'end': 45, 'answer': 'Hugging Face'}

3.3 使用transformers进行文本生成

1
2
model = 'models_save/gpt2/'
text_generator = pipeline("text-generation", model=model)
Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.
1
2
text_generator("The White man worked as a")

Setting `pad_token_id` to `eos_token_id`:None for open-end generation.





[{'generated_text': 'The White man worked as a salesman during World War II and later was named the U.S. Army Intelligence Officer during his service with the British Air Force. The war resulted in the first black war since World War II. (AP Photo/David'}]

3.4 使用transformers进行Zero-shot

1
2
model="models_save/bart-large-mnli/"
classifier = pipeline("zero-shot-classification", model=model)
Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.
1
2
3
4
sequence_to_classify = "Angela Merkel is a politician in Germany and leader of the CDU"
candidate_labels = ["politics", "economy", "entertainment", "environment"]
output = classifier(sequence_to_classify, candidate_labels, multi_label=False)
output
{'sequence': 'Angela Merkel is a politician in Germany and leader of the CDU',
 'labels': ['politics', 'economy', 'environment', 'entertainment'],
 'scores': [0.9638726115226746,
  0.015896767377853394,
  0.014499041251838207,
  0.005731707438826561]}

3.5 使用transformers进行机器翻译

1
2
3
4
5
6
# 首先确保sentencepiece安装成功  pip install sentencepiece
# 然后再执行下面的导入工作,否则会报错
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
model = 'models_save/opus-mt-zh-en/'
tokenizer = AutoTokenizer.from_pretrained(model)
model = AutoModelForSeq2SeqLM.from_pretrained(model)
/root/miniconda3/lib/python3.10/site-packages/transformers/models/marian/tokenization_marian.py:175: UserWarning: Recommended: pip install sacremoses.
  warnings.warn("Recommended: pip install sacremoses.")
1
2
3
zh2en = pipeline("translation_zh_to_en", model=model, tokenizer=tokenizer)
text = "Python是最简洁的编程语言!"
print("Output:\n", zh2en(text)[0]['translation_text'])
Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.


Output:
 Python is the simplest programming language!
-------------本文结束感谢您的阅读-------------