基于 Bert 基本模型进行 Fine-tuned

一)实验任务和数据集

实验任务 微调 Bert 基础模型让其实现情感二分类,使用的数据集为 sst-2,其数据结构如下所示。

javascript 复制代码
DatasetDict({
    train: Dataset({
        features: ['sentence', 'label', 'idx'],
        num_rows: 67349
    })
    validation: Dataset({
        features: ['sentence', 'label', 'idx'],
        num_rows: 872
    })
    test: Dataset({
        features: ['sentence', 'label', 'idx'],
        num_rows: 1821
    })
})

训练数据 67349 条,验证数据 872 条,测试数据 1821 条。SST-2 是自然语言处理(NLP)领域最经典的情感分类数据集之一, 每个样本是单个句子 (而非完整段落),标签为 0(负面)/1(正面),该数据集用于评估模型的句子级情感分类能力,是 NLP 领域的 "基准数据集" 之一 ------ 几乎所有预训练模型(如 BERT、RoBERTa)都会在 SST-2 上做微调测试,以展示其文本理解性能。

其数据的基本内容如下所示。

二)实验模型

实验模型选择 bert-base-uncased ,是 Hugging Face 生态中最常用的预训练模型之一 ,是 BERT 系列的基础版本之一,双向 Transformer 预训练语言模型,"uncased" 含义是训练时会将所有文本转为小写(如 "Hello"→"hello"),因此对大小写不敏感,约 1.1 亿参数,12 层 Transformer 编码器 + 768 维隐藏层 + 12 个注意力头。

python 复制代码
# 1. 加载分词器(必须和预训练模型对应)
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")

# 2. 加载适用于分类任务的BERT模型
# num_labels=2 对应SST-2的"正面/负面"二分类
model = BertForSequenceClassification.from_pretrained(
    "bert-base-uncased",
    num_labels=2  # 分类任务的类别数,根据实际任务调整
)

模型加载后 不能直接预测 ------ 加载的模型分类头是随机初始化的,需要在 SST-2 数据集上微调训练后,才能用于情感分类推理。

因为像 BERT 这样的模型无法直接 "阅读" 文本,它们只能处理数字张量(Tensor)。必须要将原始的文本数据集,通过分词器(Tokenizer)处理成模型可以理解和训练的数字格式。

三)定义评估模型的性能指标

python 复制代码
metric_acc = load_metric("accuracy")
metric_f1 = load_metric("f1")

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    preds = np.argmax(logits, axis=-1)
    acc = metric_acc.compute(predictions=preds, references=labels)["accuracy"]
    f1 = metric_f1.compute(predictions=preds, references=labels, average="binary")["f1"]
    return {"accuracy": acc, "f1": f1}

四)训练

python 复制代码
# 7) training args
training_args = TrainingArguments(
    output_dir="./bert-sst2-finetuned",
    eval_strategy="epoch",
    save_strategy="epoch",
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    num_train_epochs=3,
    weight_decay=0.01,
    load_best_model_at_end=True,
    metric_for_best_model="accuracy",
    greater_is_better=True, 
    save_total_limit=2,
    fp16=True,               # if using an NVIDIA GPU with mixed-precision support
    seed=42,
    logging_strategy="epoch",
    # logging_steps=100,
    report_to="none",
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized["train"],
    eval_dataset=tokenized["validation"],
    tokenizer=tokenizer,
    data_collator=data_collator,
    compute_metrics=compute_metrics,
)

trainer.train()

五)完整脚本

python 复制代码
############ 1 加载库 ############
import numpy as np
from datasets import load_dataset 
from evaluate import load as load_metric
from transformers import (
    AutoTokenizer,
    AutoModelForSequenceClassification,
    TrainingArguments,
    Trainer,
    DataCollatorWithPadding,
    set_seed,
)

############ 2 加载数据集 ############
dataset = load_dataset("glue", "sst2")

############ 3 加载分词器和模型 ############

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased", use_fast=True)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased",num_labels=2)

############ 4 数据处理 ############
def preprocess(batch):
    return tokenizer(batch["sentence"], truncation=True, padding=False, max_length=128)

tokenized = dataset.map(preprocess, batched=True)
data_collator = DataCollatorWithPadding(tokenizer)

############ 5 模型评价 ############
metric_acc = load_metric("accuracy")
metric_f1 = load_metric("f1")
def compute_metrics(eval_pred):
    logits, labels = eval_pred
    preds = np.argmax(logits, axis=-1)
    acc = metric_acc.compute(predictions=preds, references=labels)["accuracy"]
    f1 = metric_f1.compute(predictions=preds, references=labels, average="binary")["f1"]
    return {"accuracy": acc, "f1": f1}

############ 6 模型训练 ############
training_args = TrainingArguments(
    output_dir="./bert-sst2-finetuned",
    eval_strategy="epoch",
    save_strategy="epoch",
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    num_train_epochs=3,
    weight_decay=0.01,
    load_best_model_at_end=True,
    metric_for_best_model="accuracy",
    greater_is_better=True, 
    save_total_limit=2,
    fp16=True,               # if using an NVIDIA GPU with mixed-precision support
    seed=42,
    logging_strategy="epoch",
    # logging_steps=100,
    report_to="none",
)
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized["train"],
    eval_dataset=tokenized["validation"],
    tokenizer=tokenizer,
    data_collator=data_collator,
    compute_metrics=compute_metrics,
)

trainer.train()
相关推荐
GitCode官方13 分钟前
从大语言模型到具身智能:百度百舸 LoongForge 入驻 AtomGit
人工智能·react native·百度·harmonyos·atomgit
Easy_API7 小时前
2.8万亿参数,编程反超GPT-6 Astra:Kimi K3.1 Pro把开源模型推到了哪一步
大数据·人工智能·gpt·深度学习
GlobalInfo7 小时前
2026年机器人多指灵巧手市场分析报告——涵盖行业调查、趋势分析与发展前景
大数据·人工智能·microsoft·微服务·机器人
紧跟先前的步伐8 小时前
Go AI Agent 实战 24|工具系统工程化收尾与阶段验收
人工智能·ai·golang·1024程序员节
释厄6238 小时前
AI学习层更新与跨体转移律——人类社会同构·不缺理解缺 U
人工智能·学习
老金带你玩AI9 小时前
集万家所长,一键复制的Agent.md!
人工智能
ZhuoAIStage9 小时前
舞台工艺多专业审图提速:用 AI 智能体编排 A+B+C+G 四段读图流水线
人工智能·自动化·工作流编排·舞台工艺·审图智能体
小奶包他干奶奶9 小时前
AI学习——1、机器学习概念
人工智能·机器学习
展讯快报10 小时前
悬浮提词器免费App评估报告:说得AI的免费策略与可用性分析
人工智能
Yuzhiyuxia10 小时前
【AI Agent面试系列】AI Agent记忆机制知识点1
人工智能·面试·职场和发展