赞
踩
说来惭愧,BERT等预训练模型用来做下游任务做了这么久了,居然一直不知道怎么用未标注数据训练它们,这里以BERT为例子介绍一下如何使用自己的未标注数据快速训练预训练模型。
其实也很简单,BERT的github上面就有:https://github.com/google-research/bert
分为两步,第一步:准备一个txt文件,这个文件就是你要训练BERT的自己的数据。训练的目的其实就是让BERT能对你数据中的那些黑话(专有名词等)有所熟悉。格式大改这样就行:
然后执行:
- python create_pretraining_data.py \
- --input_file=./sample_text.txt \
- --output_file=/tmp/tf_examples.tfrecord \
- --vocab_file=$BERT_BASE_DIR/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=5
max_predictions_per_seq是每个序列的最大屏蔽LM预测数,应该将其设置为max_seq_length*masked_lm_prob左右(脚本不会自动执行此操作,因为需要将确切的值传递给两个脚本)。
预训练数据准备好了就执行第二步:训练模型。这里我们是从头开始的预训练,所以init_checkpoint要设置为None。模型配置(包括vocab大小)在bert_config_file中指定。num_train_steps可以设置为10000步或更多步。传递给run_pretraining.py的max_seq_length_和max_predicts_per_seq参数必须与create_pretraining_data.py相同。
- python run_pretraining.py \
- --input_file=/tmp/tf_examples.tfrecord \
- --output_dir=/tmp/pretraining_output \
- --do_train=True \
- --do_eval=True \
- --bert_config_file=$BERT_BASE_DIR/bert_config.json \
- --init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \
- --train_batch_size=32 \
- --max_seq_length=128 \
- --max_predictions_per_seq=20 \
- --num_train_steps=20 \
- --num_warmup_steps=10 \
- --learning_rate=2e-5
上面的路径替换成自己storage下的目录,跟作者一样,同样建议将vocab_file以及bert_config_file改为官方本身就有的路径,这样比自己传省时间空间。
最后,你会得到一个像这样的输出:
- ***** Eval results *****
- global_step = 20
- loss = 0.0979674
- masked_lm_accuracy = 0.985479
- masked_lm_loss = 0.0979328
- next_sentence_accuracy = 1.0
- next_sentence_loss = 3.45724e-05
完事。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。