0


5分钟NLP:使用 HuggingFace 微调BERT 并使用 TensorBoard 可视化

上篇文章我们已经介绍了Hugging Face的主要类,在本文中将介绍如何使用Hugging Face进行BERT的微调进行评论的分类。其中包含:AutoTokenizer、AutoModel、Trainer、TensorBoard、数据集和指标的使用方法。

在本文中,我们将只关注训练和测试拆分。每个数据集都由一个文本特征(评论的文本)和一个标签特征(表示评论的好坏)组成。

  1. from datasets import load_dataset, load_metric
  2. task = "imdb"
  3. dataset = load_dataset(task)
  4. print(dataset)
  5. """
  6. DatasetDict({
  7. train: Dataset({
  8. features: ['text', 'label'],
  9. num_rows: 25000
  10. })
  11. test: Dataset({
  12. features: ['text', 'label'],
  13. num_rows: 25000
  14. })
  15. unsupervised: Dataset({
  16. features: ['text', 'label'],
  17. num_rows: 50000
  18. })
  19. })
  20. """

IMDb数据集的通用基准指标是准确率,所以这里使用 datasets 库的 load_metric 函数来加载 metric 脚本,稍后可以与 compute 方法一起使用。

  1. metric = load_metric("accuracy")
  2. metric.compute(predictions=[0,0,1,1], references=[0,1,1,1])
  3. # {'accuracy': 0.75}

下载的数据集有训练和测试拆分,但我们还需要拆分出验证集来判断模型在训练期间表现以避免过拟合。

使用train_test_split 应用于 test_size = 0.3 进行拆分:这会产生一个包含 70% 原始样本的新训练集和一个包含 30% 原始样本的验证集。

  1. splitted_datasets = dataset["train"].train_test_split(test_size=0.3)
  2. print(splitted_datasets)
  3. """
  4. DatasetDict({
  5. train: Dataset({
  6. features: ['text', 'label'],
  7. num_rows: 17500
  8. })
  9. test: Dataset({
  10. features: ['text', 'label'],
  11. num_rows: 7500
  12. })
  13. })
  14. """

接下来使用 Hugging Face的AutoTokenizer 类加载 BERT Tokenizer。

本文实际上加载 DistilBERT 作为 快速替代方案,如果需要加载 BERT,代码基本是相同的(即将 distilbert-base-uncased 替换为 Bert-base-uncased)。DistilBERT 是一种小型、快速、廉价和轻量级的 Transformer 模型,通过蒸馏 BERT 基础进行训练。根据 GLUE 语言理解基准测试,它的参数比 Bert-base-uncased 少 40%,运行速度提高 60%,同时保持 BERT 95% 以上的性能。

  1. from transformers import AutoTokenizer
  2. model_checkpoint = "distilbert-base-uncased"
  3. # use_fast: Whether or not to try to load the fast version of the tokenizer.
  4. # Most of the tokenizers are available in two flavors: a full python
  5. # implementation and a “Fast” implementation based on the Rust library 🤗 Tokenizers.
  6. # The “Fast” implementations allows a significant speed-up in particular
  7. # when doing batched tokenization, and additional methods to map between the
  8. # original string (character and words) and the token space.
  9. tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True)
  10. tokenizer(["Hello, this one sentence!"])
  11. # {'input_ids': [[101, 7592, 1010, 2023, 2028, 6251, 999, 102]], 'attention_mask':
  12. # [[1, 1, 1, 1, 1, 1, 1, 1]]}
  13. # input_ids: the tokenizer vocabulary indexes of the tokenized input sentence
  14. # attention_mask: 0 if the corresponding input_id is padding, 1 otherwise

tokenizer输出为:

  1. input_ids:分词输入句子的分词器词汇索引。
  2. attention_mask:一个由 1 0 组成的数组,其中 0 表示发生填充的位置。

input_ids 和 attention_mask 都将被输入 DistilBERT 模型中。

  1. def preprocess_function_batch(examples):
  2. # truncation=True: truncate to the maximum acceptable input length for
  3. # the model.
  4. return tokenizer(examples["text"], truncation=True)
  5. # batched=True: use this if you have a mapped function which can efficiently
  6. # handle batches of inputs like the tokenizer
  7. splitted_datasets_encoded = splitted_datasets.map(preprocess_function_batch, batched=True)
  8. """
  9. DatasetDict({
  10. train: Dataset({
  11. features: ['text', 'label', 'input_ids', 'attention_mask'],
  12. num_rows: 17500
  13. })
  14. test: Dataset({
  15. features: ['text', 'label', 'input_ids', 'attention_mask'],
  16. num_rows: 7500
  17. })
  18. })
  19. """

现在可以使用 AutoModelForSequenceClassification 类及其 from_pretrained 方法加载预训练的 BERT。这里要使用num_label = 2 参数,因为现在需要在是二进制分类任务上微调 BERT,我们将重新生成的head部分,用一个随机初始化的带有两个标签的分类头替换原始层(其权重将在训练期间学习) .

  1. from transformers import TrainingArguments, Trainer
  2. from transformers import AutoModelForSequenceClassification
  3. # num_labels: number of labels to use in the last layer added to the model,
  4. # typically for a classification task.
  5. # The AutoModelForSequenceClassification class loads the
  6. # DistilBertForSequenceClassification class as underlying model. Since
  7. # AutoModelForSequenceClassification doesn't accept the parameter 'num_labels',
  8. # it is passed to the underlying class DistilBertForSequenceClassification, which
  9. # accepts it.
  10. model = AutoModelForSequenceClassification.from_pretrained(model_checkpoint, num_labels=2)
  11. # This will issue a warning about some of the pretrained weights not being used
  12. # and some weights being randomly initialized. That’s because we are throwing
  13. # away the pretraining head of the BERT model to replace it with a classification
  14. # head which is randomly initialized. We will fine-tune this model on our task,
  15. # transferring the knowledge of the pretrained model to it (which is why doing
  16. # this is called transfer learning).

在编写训练代码之前,需要启动 TensorBoard,这样可以获得模型的实时训练信息。这里显示的代码适用于 Google Colab,其中已经安装了 TensorBoard,并且 Jupyter 魔术命令允许直接从 Notebook 单元显示 TensorBoard 前端。

启动 TensorBoard 时,logdir 参数应该代表 Hugging Face 写入模型训练日志的目录。

  1. model_output_dir = f"{model_checkpoint}-finetuned-{task}"
  2. print(model_output_dir) # distilbert-base-uncased-finetuned-imdb
  3. # Start TensorBoard before training to monitor it in progress
  4. %load_ext tensorboard
  5. %tensorboard --logdir '{model_output_dir}'/runs

启动时,TensorBoard 面板将显示当前没有可用的仪表板。如果在模型训练期间刷新此页面则会查看到一些实时的数据。

接下来是配置一些训练参数。代码片段中已经为每个参数添加说明。

  • output_dir 存储最终模型的位置。
  • evaluation_strategy和eval_steps每50个训练step在验证集上验证训练模型。
  • logging_strategy 和 logging_steps 每 50 个训练step保存日志(将由 TensorBoard 可视化)。
  • save_strategy 和 save_steps 表示每 200 个训练step保存训练模型。
  • learning_rate 学习率。per_device_train_batch_size 和 per_device_eval_batch_size 分别表示在训练和验证期间使用的批大小。
  • num_train_epochs表示训练的轮次数。
  • load_best_model_at_end 表示在测试集上计算使用性能最好的模型(用 metric_for_best_model 指定)的模型。
  • report_to 将所有训练和验证的数据报告给 TensorBoard。
  1. args = TrainingArguments(
  2. # output_dir: directory where the model checkpoints will be saved.
  3. output_dir=model_output_dir,
  4. # evaluation_strategy (default "no"):
  5. # Possible values are:
  6. # "no": No evaluation is done during training.
  7. # "steps": Evaluation is done (and logged) every eval_steps.
  8. # "epoch": Evaluation is done at the end of each epoch.
  9. evaluation_strategy="steps",
  10. # eval_steps: Number of update steps between two evaluations if
  11. # evaluation_strategy="steps". Will default to the same value as
  12. # logging_steps if not set.
  13. eval_steps=50,
  14. # logging_strategy (default: "steps"): The logging strategy to adopt during
  15. # training (used to log training loss for example). Possible values are:
  16. # "no": No logging is done during training.
  17. # "epoch": Logging is done at the end of each epoch.
  18. # "steps": Logging is done every logging_steps.
  19. logging_strategy="steps",
  20. # logging_steps (default 500): Number of update steps between two logs if
  21. # logging_strategy="steps".
  22. logging_steps=50,
  23. # save_strategy (default "steps"):
  24. # The checkpoint save strategy to adopt during training. Possible values are:
  25. # "no": No save is done during training.
  26. # "epoch": Save is done at the end of each epoch.
  27. # "steps": Save is done every save_steps (default 500).
  28. save_strategy="steps",
  29. # save_steps (default: 500): Number of updates steps before two checkpoint
  30. # saves if save_strategy="steps".
  31. save_steps=200,
  32. # learning_rate (default 5e-5): The initial learning rate for AdamW optimizer.
  33. # Adam algorithm with weight decay fix as introduced in the paper
  34. # Decoupled Weight Decay Regularization.
  35. learning_rate=2e-5,
  36. # per_device_train_batch_size: The batch size per GPU/TPU core/CPU for training.
  37. per_device_train_batch_size=16,
  38. # per_device_eval_batch_size: The batch size per GPU/TPU core/CPU for evaluation.
  39. per_device_eval_batch_size=16,
  40. # num_train_epochs (default 3.0): Total number of training epochs to perform
  41. # (if not an integer, will perform the decimal part percents of the last epoch
  42. # before stopping training).
  43. num_train_epochs=1,
  44. # load_best_model_at_end (default False): Whether or not to load the best model
  45. # found during training at the end of training.
  46. load_best_model_at_end=True,
  47. # metric_for_best_model:
  48. # Use in conjunction with load_best_model_at_end to specify the metric to use
  49. # to compare two different models. Must be the name of a metric returned by
  50. # the evaluation with or without the prefix "eval_".
  51. metric_for_best_model="accuracy",
  52. # report_to:
  53. # The list of integrations to report the results and logs to. Supported
  54. # platforms are "azure_ml", "comet_ml", "mlflow", "tensorboard" and "wandb".
  55. # Use "all" to report to all integrations installed, "none" for no integrations.
  56. report_to="tensorboard"
  57. )

然后需要将这些训练参数传递给 Trainer 对象, Trainer 对象被实例化就可以使用 train 方法开始训练。

  1. # Function that returns an untrained model to be trained
  2. def model_init():
  3. return AutoModelForSequenceClassification.from_pretrained(model_checkpoint,
  4. num_labels=2)
  5. # Function that will be called at the end of each evaluation phase on the whole
  6. # arrays of predictions/labels to produce metrics.
  7. def compute_metrics(eval_pred):
  8. # Predictions and labels are grouped in a namedtuple called EvalPrediction
  9. predictions, labels = eval_pred
  10. # Get the index with the highest prediction score (i.e. the predicted labels)
  11. predictions = np.argmax(predictions, axis=1)
  12. # Compare the predicted labels with the reference labels
  13. results = metric.compute(predictions=predictions, references=labels)
  14. # results: a dictionary with string keys (the name of the metric) and float
  15. # values (i.e. the metric values)
  16. return results
  17. # Since PyTorch does not provide a training loop, the 🤗 Transformers library
  18. # provides a Trainer API that is optimized for 🤗 Transformers models, with a
  19. # wide range of training options and with built-in features like logging,
  20. # gradient accumulation, and mixed precision.
  21. trainer = Trainer(
  22. # Function that returns the model to train. It's useful to use a function
  23. # instead of directly the model to make sure that we are always training
  24. # an untrained model from scratch.
  25. model_init=model_init,
  26. # The training arguments.
  27. args=args,
  28. # The training dataset.
  29. train_dataset=splitted_datasets_encoded["train"],
  30. # The evaluation dataset. We use a small subset of the validation set
  31. # composed of 150 samples to speed up computations...
  32. eval_dataset=splitted_datasets_encoded["test"].shuffle(42).select(range(150)),
  33. # Even though the training set and evaluation set are already tokenized, the
  34. # tokenizer is needed to pad the "input_ids" and "attention_mask" tensors
  35. # to the length managed by the model. It does so one batch at a time, to
  36. # use less memory as possible.
  37. tokenizer=tokenizer,
  38. # Function that will be called at the end of each evaluation phase on the whole
  39. # arrays of predictions/labels to produce metrics.
  40. compute_metrics=compute_metrics
  41. )
  42. # ... train the model!
  43. trainer.train()

在训练过程中,可以刷新 TensorBoard 来查看训练指标的更新。在本文中,只看到训练集上的损失、验证集上的损失和验证集上的准确率。

训练集上的损失在第一个训练步骤期间迅速减少。训练结束时损失约为 0.23。

验证集上的损失几乎相同。在训练结束时损失在 0.21 左右,低于训练集上的损失,表明可以在不过度拟合的情况下进行进一步的训练。

验证集的准确率迅速接近 90%,并且在训练结束时仍在增加,达到约 93% 的值。

最后使用经过最佳训练的模型对测试集进行预测并计算其准确性。可以使用 Trainer 对象的 predict 方法生成预测。

  1. Tokenize test set
  2. dataset_test_encoded = dataset["test"].map(preprocess_function_batch, batched=True)
  3. # Use the model to get predictions
  4. test_predictions = trainer.predict(dataset_test_encoded)
  5. # For each prediction, create the label with argmax
  6. test_predictions_argmax = np.argmax(test_predictions[0], axis=1)
  7. # Retrieve reference labels from test set
  8. test_references = np.array(dataset["test"]["label"])
  9. # Compute accuracy
  10. metric.compute(predictions=test_predictions_argmax, references=test_references)
  11. # {'accuracy': 0.91888}

获得了大约 91.9% 的准确率。它与其他模型相比如何?

看看检查一下 IMDb 数据集上的PaperWithCode排行榜的论文。可以看到最佳准确率从 2015 年的 92.3% 到 2019 年的 97.4% 不等。看起来 IMDb 数据集上的表现已经基本上不会再有什么提高了,因为进一步的改进不会那么重要,而类似 BERT 的模型已经能够达到95%以上的准确率。

那么下一步要干什么?

  • 使用 Trainer 对象调整超参数。
  • 微调 更好的模型例如RoBERTa,Bigbird等。
  • 使用其他的方式进行训练,例如半监督等。

最后总结,在本文中我们拆分训练数据以创建验证集加载并测试 BERT Tokenizer和 BERT 预训练模型。准备好训练数据和参数后使用 Trainer 类对 BERT 进行微调训练。然后再 TensorBoard 上的记录了训练日志,计算了测试集的最终准确度,并将其与最先进的结果进行了比较。这就是使用Hugging Face库进行NLP的一般性的步骤。

作者:Fabio Chiusano

“5分钟NLP:使用 HuggingFace 微调BERT 并使用 TensorBoard 可视化”的评论:

还没有评论