Hugging Face Course-Introduction学习小记 (part1)

在这里插入图片描述

1.Transformer models

首先介绍了 - what is NLP

  • Classifying whole sentences: Getting the sentiment of a review, detecting if an email is spam, determining if a sentence is grammatically correct or whether two sentences are logically related or not

  • Classifying each word in a sentence: Identifying the grammatical components of a sentence (noun, verb, adjective), or the named entities (person, location, organization)

  • Generating text content: Completing a prompt with auto-generated text, filling in the blanks in a text with masked words

  • Extracting an answer from a text: Given a question and a context, extracting the answer to the question based on the information provided in the context

  • Generating a new sentence from an input text: Translating a text into another language, summarizing a text
    NLP isn’t limited to written text though. It also tackles complex challenges in speech recognition and computer vision, such as generating a transcript of an audio sample or a description of an image.

然后介绍了transformer模型的架构和它的衍生模型

encoder model

编码器模型仅使用 Transformer 模型的编码器。在每个阶段,注意力层都可以访问初始句子中的所有单词。这些模型通常具有“双向”注意力的特征,通常称为自动编码模型。

这些模型的预训练通常围绕着以某种方式破坏给定的句子(例如,通过屏蔽其中的随机单词)并让模型找到或重建初始句子。

编码器模型最适合需要理解完整句子的任务,例如句子分类、命名实体识别(以及更一般的单词分类)和提取式问答。

一些主要的encoder模型:

decoder model

解码器模型仅使用 Transformer 模型的解码器。在每个阶段,对于给定的单词,注意力层只能访问句子中位于它之前的单词。这些模型通常称为自回归模型。

解码器模型的预训练通常围绕预测句子中的下一个单词。

这些模型最适合涉及文本生成的任务。

一些主要的decoder模型:

seq2seq model

编码器-解码器模型(也称为序列到序列模型)使用 Transformer 架构的两个部分。在每个阶段,编码器的注意力层可以访问初始句子中的所有单词,而解码器的注意力层只能访问输入中位于给定单词之前的单词。

这些模型的预训练可以使用编码器或解码器模型的目标来完成,但通常涉及更复杂的事情。例如,T5是通过用单个掩码特殊词替换随机文本跨度(可以包含多个词)来预训练的,然后目标是预测这个掩码词替换的文本。

序列到序列模型最适合围绕根据给定输入生成新句子的任务,例如摘要、翻译或生成式问答。

一些主要的seq2seq模型:

总结:
在这里插入图片描述

2.Using Transformers

首先介绍了transformer库的一些特点:

  • 易于使用:只需两行代码即可下载、加载和使用最先进的 NLP 模型进行推理。

  • 灵活性:从本质上讲,所有模型都是简单的 PyTorchnn.ModuleTensorFlowtf.keras.Model类,并且可以像其各自机器学习 (ML) 框架中的任何其他模型一样进行处理。

  • 简单性:在整个库中几乎没有任何抽象。“一体化文件”是一个核心概念:模型的前向传递完全定义在单个文件中,因此代码本身是可理解和可破解的。

然后以一些完整的例子来介绍:

from transformers import pipeline

classifier = pipeline("sentiment-analysis")
classifier(
    [
        "I've been waiting for a HuggingFace course my whole life.",
        "I hate this so much!",
    ]
)

输出:

[{
   
   'label': 'POSITIVE', 'score': 0.9598047137260437},
 {
   
   'label': 'NEGATIVE', 'score': 0.9994558095932007}]

Preprocessing with a tokenizer

正如我们在第 1 章中看到的,这个pipeline将三个步骤组合在一起:预处理、通过模型传递输入和后处理:

在这里插入图片描述
与其他神经网络一样,Transformer 模型不能直接处理原始文本,因此我们pipeline的第一步是将文本输入转换为模型可以理解的数字。为此,我们使用了一个tokenizer,它将负责:

  • 将输入拆分为称为标记的单词、子词或符号(如标点符号)
  • 将每个标记映射到一个整数
  • 添加可能对模型有用的其他输入

所有这些预处理都需要以与模型预训练时完全相同的方式完成,因此我们首先需要从Model Hub下载该信息。为此,我们使用AutoTokenizer类及其from_pretrained()方法。

from transformers import AutoTokenizer

checkpoint = "distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)

一旦我们有了tokenizer,我们就可以直接将我们的句子传递给它,我们将得到一个准备好提供给我们模型的字典!唯一要做的就是将输入 ID 列表转换为张量。

raw_inputs = [
    "I've been waiting for a HuggingFace course my whole life.",
    "I hate this so much!",
]
inputs = tokenizer(raw_inputs, padding=True
### 部署 Hugging Face bge-reranker-v2-m3 模型 为了成功部署 Hugging Face 的 `bge-reranker-v2-m3` 模型,可以遵循以下指南: #### 准备环境 确保安装了 Python 和 pip 工具。接着,在命令行工具中执行如下操作来创建并激活虚拟环境(推荐做法),这有助于管理依赖项。 ```bash python -m venv my_env source my_env/bin/activate # Linux 或 macOS 用户 my_env\Scripts\activate # Windows 用户 ``` #### 安装必要的库 通过 pip 来安装 Transformers 库和其他可能需要的包,比如 Torch 或 TensorFlow,具体取决于所选框架版本。 ```bash pip install transformers torch datasets ``` #### 加载模型 利用 Hugging Face 提供的 API 接口加载指定名称的空间中的预训练模型实例。对于 `bge-reranker-v2-m3` 而言,首次调用将会自动从远程服务器下载对应的权重文件至本地缓存目录[^2]。 ```python from transformers import AutoModelForSequenceClassification, AutoTokenizer model_name = "BAAI/bge-reranker-v2-m3" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained(model_name) ``` #### 使用模型进行预测 定义一个简单的函数来进行输入处理和输出解析,以便能够方便地测试该重排序器的效果。 ```python def rerank(query, documents): inputs = tokenizer([query]*len(documents), documents, return_tensors="pt", padding=True, truncation=True) outputs = model(**inputs).logits.detach().numpy() scores = list(zip(outputs.flatten(), documents)) sorted_scores = sorted(scores, key=lambda x: x[0], reverse=True) for score, doc in sorted_scores[:5]: print(f"Score {score:.4f}: {doc}") # 测试例子 test_query = "example query text here." docs_to_rerank = ["document one content.", "another document's contents."] rerank(test_query, docs_to_rerank) ``` 上述代码片段展示了如何初始化模型以及编写基本的查询文档重排逻辑。实际应用时可根据需求调整参数设置或集成到更大规模的应用程序当中[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值