
Transformers 序列分类实战指南用 DistilBERT 微调 IMDb 情感分类模型【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers本文以 Transformers 的序列分类Text Classification任务文档为核心完整讲解如何基于 IMDb 电影评论数据集微调 DistilBERT 实现情感二分类从数据加载、分词预处理、动态填充Dynamic Padding、精度指标计算到使用Trainer训练、上传模型以及通过pipeline与手动 forward 两种方式完成推理并结合仓库源码剖析关键参数与底层实现。一、任务概览文本分类是最常见的 NLP 任务之一为一段文本指派一个类别或标签。最典型的形态是情感分析——把一段文本标记为「正面Positive」「负面Negative」或「中性Neutral」。本指南覆盖的完整链路在 IMDb 数据集stanfordnlp/imdb上微调 DistilBERT判断电影评论是正面还是负面使用微调后的模型进行预测。环境准备开始前确认安装必要的依赖库pip install transformers datasets evaluate accelerate建议登录 Hugging Face 账户以便后续下载模型并把训练成果分享给社区 from huggingface_hub import notebook_login notebook_login()二、加载 IMDb 数据集使用 Datasets 库加载数据集 from datasets import load_dataset imdb load_dataset(stanfordnlp/imdb)查看一条样本 imdb[test][0] { label: 0, text: I love sci-fi and am willing to put up with a lot. Sci-fi movies/TV are usually underfunded, ..., }该数据集只有两个字段text电影评论文本label0表示负面评论1表示正面评论。三、数据预处理3.1 加载分词器并编写预处理函数加载 DistilBERT 的分词器用于处理text字段 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(distilbert/distilbert-base-uncased)编写预处理函数完成编码并通过truncationTrue将超长文本截断到 DistilBERT 可接受的最大输入长度 def preprocess_function(examples): ... return tokenizer(examples[text], truncationTrue)使用 Datasets 的Dataset.map把该函数应用到整个数据集。batchedTrue会按批处理数据显著加速maptokenized_imdb imdb.map(preprocess_function, batchedTrue)3.2 用DataCollatorWithPadding做动态填充效率最高的做法是动态填充dynamic padding只把每个批次内的序列填充到该批最长序列而不是把全部数据都填充到全局最大长度。创建数据收集器 from transformers import DataCollatorWithPadding data_collator DataCollatorWithPadding(tokenizertokenizer)源码级解析DataCollatorWithPadding定义于 src/transformers/data/data_collator.py其默认行为与可调参数值得注意padding默认True等价于longest填充到批内最长序列也可设为max_length填充到max_length或模型最大输入长度或False/do_not_pad不填充序列长度可以不一致max_lengthNone时不限制长度pad_to_multiple_of把序列填充为指定值的倍数尤其在 NVIDIA Volta计算能力 7.0及更高架构上对启用 Tensor Cores 有帮助return_tensors默认返回ptPyTorch 张量也支持np一个实用细节__call__会自动把批次中的label键重命名为labels见 data_collator.py 第 233-238 行而Trainer的 loss 计算正是读取labels键——这就是为什么 IMDb 数据集的label字段无需改名即可直接训练。提示Trainer在传入tokenizer时默认就使用动态填充此时可以不显式指定data_collator。四、评估指标accuracy在训练过程中嵌入评估指标有助于监控模型表现。用 Evaluate 库加载准确率指标 import evaluate accuracy evaluate.load(accuracy)然后编写compute_metrics函数把预测 logits 与真实标签交给EvaluationModule.compute计算准确率 import numpy as np def compute_metrics(eval_pred): ... predictions, labels eval_pred ... predictions np.argmax(predictions, axis1) ... return accuracy.compute(predictionspredictions, referenceslabels)该函数现在就绪将在训练配置环节被Trainer调用。五、训练模型5.1 定义标签映射id2label与label2id训练前先建立「类别 id ↔ 标签名」的双向映射 id2label {0: NEGATIVE, 1: POSITIVE} label2id {NEGATIVE: 0, POSITIVE: 1}为什么这两张映射很重要从源码看PreTrainedConfig在 src/transformers/configuration_utils.py 中把id2label/label2id作为标准字段保存进config.json若不提供配置会自动生成LABEL_0、LABEL_1这样的占位名见 configuration_utils.py 第 393-396 行。显式传入id2label后后续pipeline推理输出、model.config.id2label查询都会返回可读的NEGATIVE/POSITIVE而不是LABEL_0。5.2 加载分类模型用AutoModelForSequenceClassification加载 DistilBERT并传入分类数与标签映射 from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer model AutoModelForSequenceClassification.from_pretrained( ... distilbert/distilbert-base-uncased, num_labels2, id2labelid2label, label2idlabel2id ... )注意加载的是...ForSequenceClassification变体它在 DistilBERT 主干之上附加了一个分类头classification_head输出形状为[batch, num_labels]的 logits。DistilBERT 的完整实现位于 src/transformers/models/distilbert/modeling_distilbert.py。5.3 配置TrainingArguments并启动训练只剩三步在TrainingArguments中设置训练超参。唯一必填项是output_dir模型保存位置设置push_to_hubTrue可把模型上传到 Hub需已登录Trainer会在每个 epoch 结束时评估精度并保存检查点。把训练参数连同模型、数据集、分词器、数据收集器、compute_metrics一起传给Trainer。调用trainer.train()开始微调。 training_args TrainingArguments( ... output_dirmy_awesome_model, ... learning_rate2e-5, ... per_device_train_batch_size16, ... per_device_eval_batch_size16, ... num_train_epochs2, ... weight_decay0.01, ... eval_strategyepoch, ... save_strategyepoch, ... load_best_model_at_endTrue, ... push_to_hubTrue, ... ) trainer Trainer( ... modelmodel, ... argstraining_args, ... train_datasettokenized_imdb[train], ... eval_datasettokenized_imdb[test], ... processing_classtokenizer, ... data_collatordata_collator, ... compute_metricscompute_metrics, ... ) trainer.train()各关键参数说明参数取值作用output_dirmy_awesome_model检查点与最终模型的保存目录必填learning_rate2e-5预训练模型微调的典型学习率量级per_device_train_batch_size16单设备训练批大小per_device_eval_batch_size16单设备评估批大小num_train_epochs2训练轮数weight_decay0.01权重衰减缓解过拟合eval_strategy/save_strategyepoch每个 epoch 结束时评估并保存检查点load_best_model_at_endTrue训练结束后加载评估指标最优的检查点push_to_hubTrue训练完成后把模型推送到 Hub训练完成后用trainer.push_to_hub()把模型分享给所有人 trainer.push_to_hub()提示Trainer的完整用法可参考仓库训练文档docs/source/ar/training.md。5.4 进阶用命令行脚本训练如果你更习惯脚本化、参数化的训练流程而非 notebook仓库提供了完整的 PyTorch 分类训练脚本 examples/pytorch/text-classification/run_classification.py配套说明见 examples/pytorch/text-classification/README.md。该脚本用HfArgumentParser把三个参数 dataclassDataTrainingArguments、ModelArguments、TrainingArguments统一解析为命令行参数其中与数据相关的常用项包括--dataset_name通过 Datasets 加载的数据集名--text_column_names输入数据集中的文本列名多列时可用--text_column_delimiter拼接成一句--train_split_name/--validation_split_name/--test_split_name自定义各阶段使用的 split 名--do_regression执行回归而非分类默认从数据集推断任务类型。此外脚本还支持--max_length、--pad_to_max_length等长度控制参数与本文DataCollatorWithPadding的动态填充策略互为对照批内填充本文方案通常更省时而固定最大长度则便于跨数据集对齐序列长度。六、推理Inference微调完成后即可用于推理。6.1 使用pipeline快速推理最简方式是pipeline。创建一个情感分析 pipeline 并传入模型再输入待分类文本 from transformers import pipeline classifier pipeline(sentiment-analysis, modelstevhliu/my_awesome_model) classifier(text) [{label: POSITIVE, score: 0.9994940757751465}]其中text为 text This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three.源码级解析sentiment-analysis任务实际由 src/transformers/pipelines/text_classification.py 中的TextClassificationPipeline处理其postprocess方法第 178-219 行决定了分数的计算方式num_labels 1本例num_labels2或problem_type single_label_classification对 logits 做softmaxnum_labels 1或problem_type multi_label_classification做sigmoidproblem_type regression不做任何变换NONE也可用function_to_apply参数显式指定sigmoid/softmax/nonetop_k参数控制返回结果条数top_k1默认返回单个{label, score}字典top_k取更大值或None时返回按分数降序排列的多个标签字典——多分类任务下查看完整概率分布时有用一个工程细节_forward会检测模型forward签名中是否含use_cache参数并强制置为False第 171-176 行因为分类任务用不到 KV cache强制关闭可避免无谓显存开销文本对分类传入{text: ..., text_pair: ...}字典即可preprocess会将其转发给分词器的text/text_pair。6.2 手动推理从 tokenize 到argmax也可以不依赖 pipeline手动复现整个推理链路。第一步分词并返回 PyTorch 张量 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(stevhliu/my_awesome_model) inputs tokenizer(text, return_tensorspt)第二步把输入送入模型取出logits from transformers import AutoModelForSequenceClassification model AutoModelForSequenceClassification.from_pretrained(stevhliu/my_awesome_model) with torch.no_grad(): ... logits model(**inputs).logits第三步取概率最高的类别 id并用id2label映射回可读标签 predicted_class_id logits.argmax().item() model.config.id2label[predicted_class_id] POSITIVE可以看到model.config.id2label正是训练时通过from_pretrained传入并随config.json持久化的那张映射表——这就是第五节强调显式传入id2label/label2id的原因。七、小结与延伸本指南完整覆盖了序列分类的标准工作流数据load_dataset加载 IMDbtext/label两字段预处理AutoTokenizer编码 truncationDataset.map(batchedTrue)批量分词DataCollatorWithPadding批内动态填充自动把label重命名为labels评估evaluate.load(accuracy)compute_metrics每 epoch 评估并配合load_best_model_at_end保留最优检查点训练AutoModelForSequenceClassification加载分类头TrainingArguments组织超参Trainer.train()执行push_to_hub()发布推理pipeline(sentiment-analysis)一行调用softmax/sigmoid 自动选择或手动tokenizer → model.forward → logits.argmax → config.id2label全链路复现。想继续深入可以阅读仓库中的序列分类任务文档原文 docs/source/ar/tasks/sequence_classification.md、分类训练脚本 examples/pytorch/text-classification/run_classification.py 及其 README以及 DistilBERT 的 configuration_distilbert.py 与 modeling_distilbert.py 源码。【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考