BERT(Bidirectional Encoder Representations from Transformers)

源码链接

google-research/bert: TensorFlow code and pre-trained models for BERT

论文链接

[1810.04805] BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

模型结构

1、嵌入层(Embeddings):将文本转换为向量表示

①Token嵌入(Token Embeddings):WordPiece子词ID -> 向量

②段落嵌入(Segment Embeddings):区分句子A/B(0/1)

③位置嵌入(Position Embeddings):位置编码

④LayerNorm+Dropout

2、编码器层(Encoder Layers):多层Transfromer编码器,每层包括

①多头自注意力(Multi-Head Self-Attention):双向注意力

②前馈网络(Feed-Forward Network):两层全连接层+GELU激活

③残差链接+LayerNorm

3、输出头(Output Heads)

①预训练:

掩码语言建模MLM Head(Masked Language Modeling):全连接层+Softmax预测掩码token

下一句预测NSP Head(Next Sentencen Prediction):全连接层+Softmax预测句子关系

②微调:

加任务头

  • 基于句子对的分类任务:
    • MNLI:给定一个前提 (Premise) ,根据这个前提去推断假设 (Hypothesis) 与前提的关系。该任务的关系分为三种,蕴含关系 (Entailment)、矛盾关系 (Contradiction) 以及中立关系 (Neutral)。所以这个问题本质上是一个分类问题,我们需要做的是去发掘前提和假设这两个句子对之间的交互信息。
      • QQP:基于Quora,判断 Quora 上的两个问题句是否表示的是一样的意思。
      • QNLI:用于判断文本是否包含问题的答案,类似于我们做阅读理解定位问题所在的段落。
      • STS-B:预测两个句子的相似性,包括5个级别。
      • MRPC:也是判断两个句子是否是等价的。
      • RTE:类似于MNLI,但是只是对蕴含关系的二分类判断,而且数据集更小。
      • SWAG:从四个句子中选择为可能为前句下文的那个。
  • 基于单个句子的分类任务
    • SST-2:电影评价的情感分析。
      • CoLA:句子语义判断,是否是可接受的(Acceptable)。
  • 问答任务
    • SQuAD v1.1:给定一个句子(通常是一个问题)和一段描述文本,输出这个问题的答案,类似于做阅读理解的简答题。
  • 命名实体识别
    • CoNLL-2003 NER:判断一个句子中的单词是不是Person,Organization,Location,Miscellaneous或者other(无命名实体)。​

模型训练过程

1、环境配置

①python版本<=3.7

②requirements.txt

③numpy使用1.16.5版本

BERT 模型复现报错: Cannot convert a symbolic Tensor (bert/encoder/strided_slice:0) to a numpy 解决方法_tensorflow:reraising captured error-CSDN博客

2、下载模型词汇表和配置

①BERT-Tiny模型文件:https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-2_H-128_A-2.zip

②BERT-Base模型文件:https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip

解压后得到:vocab.txt(词汇表)、bert_config.json(模型配置)、bert_model.ckpt.*(可选预训练检查点)

3、预训练部分

(1)预训练数据集

运行create_pretraining_data.py从纯文本文件sample_text.txt中生成预训练数据TFRecord文件

python create_pretraining_data.py 
  --input_file=./sample_text.txt 
  --output_file=./out/tf_examples.tfrecord 
  --vocab_file=./uncased_L-2_H-128_A-2/vocab.txt 
  --do_lower_case=True 
  --max_seq_length=128 
  --max_predictions_per_seq=20 
  --masked_lm_prob=0.15 
  --random_seed=12345 
  --dupe_factor=20

(2)模型预训练

运行run_pretraining.py文件

python run_pretraining.py
  --input_file=./out/tf_examples.tfrecord
  --output_dir=./out/pretraining_output
  --do_train=True
  --do_eval=True
  --bert_config_file=./uncased_L-2_H-128_A-2/bert_config.json
  --train_batch_size=16
  --max_seq_length=128
  --max_predictions_per_seq=20
  --num_train_steps=1000
  --num_warmup_steps=100
  --learning_rate=2e-5

4、微调部分

(1) 微调数据集(使用GLUE数据集中的MRPC数据集)

数据集下载,三种方法

①其他的github仓库

Models/official/nlp/bert/glue_data/MRPC at master · MegEngine/Models

②直接下载链接:GLUE Benchmark,有时会下载失败

③代码下载,代码地址:nyu-mll/GLUE-baselines: [DEPRECATED] Repo for exploring multi-task learning approaches to learning sentence representations

torch0.4版本,在官网下载后pip install,官网下载链接Previous PyTorch Versions

python download_glue_data.py --data_dir=./glue_data --tasks=MRPC

注意:dev_ids.tsv文件可能没有,需要手动划分数据。建议使用方法一。

数据集结果

①train.tsv:3666行

②dev.tsv:408行

③test.tsv:1725行

将三个文件放到bert项目中,文件夹为./glue_data/MRPC/

(2)模型微调

运行run_classifier.py文件

python run_classifier.py
  --data_dir=./glue_data/MRPC
  --task_name=MRPC
  --do_train=True
  --do_eval=True
  --do_predict=True
  --vocab_file=./uncased_L-2_H-128_A-2/vocab.txt 
  --bert_config_file=./uncased_L-2_H-128_A-2/bert_config.json
  --init_checkpoint=./out/pretraining_output/model.ckpt-1000
  --output_dir=./out/classifier_output
  --train_batch_size=16
  --max_seq_length=128
  --eval_batch_size=8
  --predict_batch_size=8
  --learning_rate=2e-5
  --num_train_epochs=3
  --warmup_proportio=0.1

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐