上半部分介绍了如何从BERT模型提取嵌入,下半部分介绍如何针对下游任务进行微调,分为四个任务。
下游任务:
微调方式:
- 分类器层与BERT模型一起更新权重(通常情况且效果更好)
- 仅更新分类器层的权重而不更新BERT模型的权重。BERT模型仅作为特征提取器
1 情感分类任务
1.1 任务说明
对句子进行情感分析,判断一个句子是积极情绪还是消极情绪。
1.1 代码
1.1.1 requirements
- 注意!装完transformers、nlp、evaluate后需要指定multiprocess和dill的版本,否则可能会冲突。
transformers==4.27.4
nlp==0.4.0
evaluate==0.4.0
multiprocess==0.70.12
dill==0.3.4
torch
1.1.2 加载数据集
- 查看所有数据集:https://huggingface.co/datasets
- 加载数据集:
load_dataset
- 数据集切片:
load_dataset
中split用法:https://huggingface.co/docs/datasets/v0.4.0/splits.html
from nlp import load_dataset
dataset = load_dataset('imdb', split=['train[:10%]', 'test[:100]'])
print('dataset: {}'.format(dataset))
train_set = dataset[0]
test_set = dataset[1]
print('train_set[0]: {}'.format(train_set[0]))
print('test_set[0]: {}'.format(test_set[0]))
print('train_set: {}'.format(train_set))
print('test_set: {}'.format(test_set))
1.1.3 创建模型
- 创建模型:
AutoModelForSequenceClassification.from_pretrained()
- AutoModelForSequenceClassification会依据数据集和标签自动选择合适的序列分类任务的模型
- 模型实际上使用的是BertForSequenceClassification,在BERT模型的基础上添加了线性层的分类器
from transformers import AutoModelForSequenceClassification
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {"NEGATIVE": 0, "POSITIVE": 1}
model = AutoModelForSequenceClassification.from_pretrained(
'bert-base-uncased', num_labels=2, id2label=id2label, label2id=label2id
)
1.1.4 创建词元分析器并处理数据集
- 创建预训练好的词元分析器:
AutoTokenizer.from_pretrained()
- 对数据集批量进行词元分析:首先定义处理函数
preprocess_function
,其次使用map函数作用于数据集,其中batched=True
表示批量处理 -
truncation=True
表示对超出模型限定标记长度之外的文本进行裁剪
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
def preprocess_function(examples):
return tokenizer(examples['text'], truncation=True)
train_set = train_set.map(preprocess_function, batched=True)
test_set = test_set.map(preprocess_function, batched=True)
1.1.5 使用DataCollatorWithPadding补齐句子
-
DataCollatorWithPadding
:把一批样本补齐到这批样本最长句子的长度而非整个数据集的最大长度从而加快补齐速度
from transformers import DataCollatorWithPadding
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
1.1.6 定义评估标准
- 情感分类任务使用acc进行评估:
evaluate.load('accuracy')
import evaluate
accuracy = evaluate.load('accuracy')
def compute_metrics(eval_pred):
predictions, labels = eval_pred
predictions = np.argmax(predictions, axis=1)
return accuracy.compute(predictions=predictions, references=labels)
1.1.7 定义训练参数
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir='./results', # 模型结果输出目录
logging_dir='./logs', # 日志输出目录
optim='adamw_torch', # 优化器
learning_rate=2e-5, # 学习率
per_device_train_batch_size=8, # 训练时batch_size
per_device_eval_batch_size=8, # 验证时batch_size
num_train_epochs=10, # 训练轮数
weight_decay=0.01,
warmup_steps=500,
evaluation_strategy='epoch', # 每轮训练完成时评估模型
save_strategy='epoch', # 每轮训练完成时保存模型
load_best_model_at_end=True,
metric_for_best_model='accuracy',
)
1.1.8 定义训练器
from transformers import Trainer
trainer = Trainer(
model=model, # 模型
args=training_args, # 训练参数
train_dataset=train_set, # 训练集
eval_dataset=test_set, # 验证集
tokenizer=tokenizer, # 词元分析器
data_collator=data_collator, # 数据整理器
compute_metrics=compute_metrics # 评估标准
)
1.1.9 训练
trainer.train()
trainer.evaluate()
# {'eval_loss': 1.4403954992303625e-05, 'eval_accuracy': 1.0, 'eval_runtime': 1.3039, 'eval_samples_per_second': 76.692, 'eval_steps_per_second': 9.97, 'epoch': 10.0}
1.1.10 预测
from transformers import pipeline
text = 'This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three.'
classifier = pipeline('sentiment-analysis', model='./results/model_path', tokenizer='bert-base-uncased')
result = classifier(text)
print(result)
# [{'label': 'POSITIVE', 'score': 0.9999701976776123}]
参考资料
[1]. BERT基础教程Transformer大模型实战
[2]. huggingface官网文本分类任务指南:https://huggingface.co/docs/transformers/tasks/sequence_classification
[3]. pipline文档: https://huggingface.co/docs/transformers/main_classes/pipelines