huggingface调用一些细节记录

这篇笔记详细记录了使用 HuggingFace 库中 BertModel 的一些关键点,包括 ModelInput 的创建,通过 tokenizer 进行文本预处理,以及 ModelForward 中的输出解释。强调了理解 tokenizer 类的直接调用和内部函数的区别,并提醒在前传模型时添加 return_tensors 参数。还介绍了 BERTModel 的输出,特别是 last_hidden_state 和 pooler_output 的含义。建议读者多查阅官方文档以加深理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

huggingface调用一些细节记录

写给我自己看的一些小细节,因为不是每天写代码,总是会忘

要多看文档!!!

Model Input

使用tokenizer进行分词、添加特殊token例如[cls] [sep]、添加attention mask等等操作

注意类的直接调用和类中函数调用好吗??我每次都来tokenizer()tokenizer.encode()之间来回横跳不长记性

(本文都是用bert进行举例,其他预训练模型同理)

类的直接调用tokenizer()

encoded_dict = tokenizer("你是谁?", "我是你妈。")
print(encoded_dict)

结果:

{'input_ids': [101, 872, 3221, 6443, 8043, 102, 2769, 3221, 872, 1968, 511, 102], 
'token_type_ids': [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], 
'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}

注意:前传的时候无脑加入参数return_tensors="pt",省的还得自己转换为tensor

类中函数调用tokenizer.encode(),直接返回input_ids

input_ids = tokenizer.encode("你是谁?", "我是你妈。")
print(input_ids)

结果:

[101, 872, 3221, 6443, 8043, 102, 2769, 3221, 872, 1968, 511, 102]

关于model input 单/双输入、对齐等细节,参考官方文档,事无巨细,生怕我不会用这个接口,谢谢宁

https://huggingface.co/docs/transformers/v4.23.1/en/glossary#feed-forward-chunking

关于tokenzier的基类说明,事无巨细了

https://huggingface.co/docs/transformers/v4.23.1/en/main_classes/tokenizer#transformers.PreTrainedTokenizer

Model Foward

BertModel

函数参数:
参数

返回值:
返回值
一般也就用到last_hidden_state,维度见上图

官方例子就很清楚了,copy一下:
https://huggingface.co/docs/transformers/v4.23.1/en/model_doc/bert#transformers.BertModel

from transformers import BertTokenizer, BertModel
import torch

tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = BertModel.from_pretrained("bert-base-uncased")

inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") # 自动转换为tensor
outputs = model(**inputs)

last_hidden_states = outputs.last_hidden_state # 返回值取last_hidden_state

注意看这个pooler_output: 即为[cls]的表示

pooler_output (torch.FloatTensor of shape (batch_size, hidden_size)) — Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.

再强调一下,仔细看文档!

### Hugging Face Transformers 实战教程示例项目 #### 加载预训练模型并执行文本分类任务 为了展示如何利用Hugging Face Transformers库进行实际操作,下面提供了一个简单的Python脚本实例,该实例展示了如何加载预训练的语言模型,并将其应用于二元情感分析任务。 ```python from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer # 加载预训练的情感分析pipeline classifier = pipeline('sentiment-analysis') # 测试输入语句列表 test_sentences = ["I love programming!", "This movie was terrible."] # 对测试句子进行预测 results = classifier(test_sentences) for result in results: print(f"label: {result['label']}, with score: {round(result['score'], 4)}") ``` 这段代码首先导入必要的模块,接着创建一个用于情感分析的`pipeline`对象。之后定义了一些待测字符串组成的列表作为输入数据源。最后遍历输出结果,打印每条记录对应的标签及其置信度得分[^3]。 #### 使用自定义数据集微调BERT模型 对于更复杂的场景,则可能涉及到基于自有标注的数据来优化现有模型的表现。这里给出一段更为完整的流程: 1. 准备好CSV文件格式的数据集; 2. 定义PyTorch Dataset类读取上述数据; 3. 构建DataLoader迭代器供后续训练过程调用; 4. 初始化指定架构(如BERT)的基础模型以及相应的分词器; 5. 设定超参数配置项; 6. 启动fine-tuning阶段直至收敛; 7. 验证最终效果并通过保存最佳权重完成部署前准备工作。 具体实现细节如下所示: ```python import torch from datasets import load_dataset from transformers import BertForSequenceClassification, Trainer, TrainingArguments, BertTokenizerFast # 加载本地csv文件形式的小规模样例数据集 dataset = load_dataset('csv', data_files={'train': 'path/to/train.csv', 'validation': 'path/to/val.csv'}) tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased') model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) def preprocess_function(examples): return tokenizer(examples['text'], truncation=True, padding='max_length') encoded_datasets = dataset.map(preprocess_function, batched=True) columns_to_return = ['input_ids', 'attention_mask', 'labels'] encoded_datasets.set_format(type='torch', columns=columns_to_return) training_args = TrainingArguments( output_dir='./results', evaluation_strategy="epoch", learning_rate=2e-5, per_device_train_batch_size=8, per_device_eval_batch_size=8, num_train_epochs=3, weight_decay=0.01, ) trainer = Trainer( model=model, args=training_args, train_dataset=encoded_datasets['train'], eval_dataset=encoded_datasets['validation'] ) trainer.train() ``` 此段程序片段主要针对已有结构化的表格型数据实施了初步清理工作;随后借助于Transformers内置工具完成了tokenization环节;紧接着设置了若干关键性的hyperparameters选项;再者便是正式开启了finetune周期直到达到预期目标为止[^1]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值