

PyTorch预训练Bert模型
source link: http://www.blackedu.vip/729/pytorch-yu-xun-lianbert-mo-xing/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PyTorch预训练Bert模型
本文介绍以下内容:
1. 使用transformers框架做预训练的bert-base模型;
2. 开发平台使用Google的Colab平台,白嫖GPU加速;
3. 使用datasets模块下载IMDB影评数据作为训练数据。
transformers模块简介
transformers框架为Huggingface开源的深度学习框架,支持几乎所有的Transformer架构的预训练模型。使用非常的方便,本文基于此框架,尝试一下预训练模型的使用,简单易用。
本来打算预训练bert-large模型,发现colab上GPU显存不够用,只能使用base版本了。打开colab,并且设置好GPU加速,接下来开始介绍代码。
首先安装数据下载模块和transformers包。
!pip install datasets
!pip install transformers
使用datasets下载IMDB数据,返回DatasetDict类型的数据.返回的数据是文本类型,需要进行编码。下面会使用tokenizer进行编码。
from datasets import load_dataset
imdb = load_dataset('imdb')
print(imdb['train'][:3]) # 打印前3条训练数据
接下来加载tokenizer和模型.从transformers导入AutoModelForSequenceClassification, AutoTokenizer,创建模型和tokenizer。
from transformers import AutoModelForSequenceClassification, AutoTokenizer
model_checkpoint = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
model = AutoModelForSequenceClassification.from_pretrained(model_checkpoint, num_labels=2)
对原始数据进行编码,并且分批次(batch)
def preprocessing_func(examples):
return tokenizer(examples['text'],
padding=True,
truncation=True, max_length=300)
batch_size = 16
encoded_data = imdb.map(preprocessing_func, batched=True, batch_size=batch_size)
上面得到编码数据,每个批次设置为16.接下来需要指定训练的参数,训练参数的指定使用transformers给出的接口类TrainingArguments,模型的训练可以使用Trainer。
from transformers import Trainer, TrainingArguments
args = TrainingArguments(
'out',
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
learning_rate=5e-5,
evaluation_strategy='epoch',
num_train_epochs=10,
load_best_model_at_end=True,
)
trainer = Trainer(
model,
args=args,
train_dataset=encoded_data['train'],
eval_dataset=encoded_data['test'],
tokenizer=tokenizer
)
训练模型使用trainer对象的train方法
trainer.train()

评估模型使用trainer对象的evaluate方法
trainer.evaluate()
本文介绍了基于transformers框架实现的bert预训练模型,此框架提供了非常友好的接口,可以方便读者尝试各种预训练模型。同时datasets也提供了很多数据集,便于学习NLP的各种问题。加上Google提供的colab环境,数据下载和预训练模型下载都非常快,建议读者自行去炼丹。本文完整的案例下载
Recommend
-
45
Photo by Clément H on...
-
11
阿里天池 NLP 入门赛 Bert 方案 -3 Bert 预训练与分类哈尔滨工程大学 计算机硕士在读前言这篇文章用于记录阿里天池 NLP 入门赛,详细讲解了整个数据处理流程,以...
-
10
作者: 邱震宇( 华泰证券股份有限公司 算法工程师)
-
18
NewBeeNLP原创出品 公众号专栏作者@上杉翔二 悠闲会 · 信息检索 BERT以及BERT后时代在NLP各项任务上都...
-
4
在放假前刷到Arxiv的一篇和知识图谱相关的论文,是研究实体链接...
-
8
关于BERT预训练模型,你想知道的都在这~ ...
-
8
之前总是直接用预训练好的BERT模型,对预训练部分的认识只停留在其同时训练两个无监督的任务:masked LM和Next Sentence Prediction (NSP)。而之后的SOTA模型如XLNet、RoBERTa、ALBERT等都属于BERT的追随者。因此有必要详细了解BERT预训练的细节。 本篇...
-
4
2.69分钟完成BERT训练!新发CANN 5.0加持 精选 原创 摘要:快,着实有点快。 现在,经典模型BERT只...
-
5
【pytorch】BERT 2022年10月23日 Author:Guofei 文章归类: 0x26_torch 文章编号: 274 ...
-
8
挑战单卡单日训练BERT,ViT作者推荐
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK