Bert (Bi-directional Encoder Representations from Transformers) Pytorch 源码解读(三)

本文是BERT Pytorch源码解读系列的第三篇,主要解析wiki_dataset.py中预训练数据的预处理过程,包括初始化、Mask操作、Next Sentence Prediction任务和数据组合,帮助理解模型输入数据的构造方式。
摘要由CSDN通过智能技术生成

前言

Bert (Bi-directional Encoder Representations from Transformers) Pytorch 版本源码解读的第三篇,也是最后一部分。这一部分为源码中, wiki_dataset.py 文件中的内容,主要实现了 Bert 模型预训练时,数据的预处理工作。读完这一部分源码有助于更好的理解模型的输入部分的数据是如何构造的。


Bert 源码解读:

1. 模型结构源码: bert_model.py

2. 模型预训练源码:bert_training.py

3. 数据预处理源码:wiki_dataset.py


开始

1.初始化

class BERTDataset(Dataset):
    def __init__(self, corpus_path, word2idx_path, seq_len, hidden_dim=384, on_memory=True):
        # hidden dimension for positional encoding
        self.hidden_dim = hidden_dim
        # define path of dicts
        self.word2idx_path = word2idx_path
        # define max length
        self.seq_len = seq_len
        # load whole corpus at once or not
        self.on_memory = on_memory
        # directory of corpus dataset
        self.corpus_path = corpus_path
        # define special symbols
        self.pad_index = 0
        self.unk_index = 1
        self.cls_index = 2
        self.sep_index = 3
        self.mask_index = 4
        self.num_index = 5

        # 加载字典
        with open(word2idx_path, "r", encoding="utf-8") as f:
            self.word2idx = json.load(f)

        # 加载语料
        with open(corpus_path, "r", encoding="utf-8") as f:
            if not on_memory:
   
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值