第15章自然言語処理:事前学習
15.9. The Dataset for Pretraining BERT15.9 BERTを事前学習するためのデータセット
To pretrain the BERT model as implemented in Section 15.8, we need to generate the dataset in the ideal format to facilitate the two pretraining tasks: masked language modeling and next sentence prediction. On the one hand, the original BERT model is pretrained on the concatenation of two huge corpora BookCorpus and English Wikipedia (see Section 15.8.5), making it hard to run for most readers of this book. On the other hand, the off-the-shelf pretrained BERT model may not fit for applications from specific domains like medicine. Thus, it is getting popular to pretrain BERT on a customized dataset. To facilitate the demonstration of BERT pretraining, we use a smaller corpus WikiText-2 (Merity et al., 2016).
英語のヒント
15.8節で実装したBERTモデルを事前学習するには、二つの事前学習のタスク、つまりマスク言語モデリングと次文予測をしやすくする理想的な形式でデータセットを生成する必要がある。一方では、元のBERTモデルは二つの巨大なコーパスBookCorpusと英語版ウィキペディアを連結したもので事前学習されており(15.8.5節を参照)、この本のほとんどの読者にとって実行するのは難しい。他方では、既製の事前学習済みBERTモデルは、医学のような特定の分野の応用には合わないかもしれない。そのため、カスタムのデータセットでBERTを事前学習することが広まりつつある。BERTの事前学習の説明をしやすくするため、もっと小さなコーパスWikiText-2(Merity et al., 2016)を使う。
Comparing with the PTB dataset used for pretraining word2vec in Section 15.3, WikiText-2 (i) retains the original punctuation, making it suitable for next sentence prediction; (ii) retains the original case and numbers; (iii) is over twice larger.
英語のヒント
15.3節でword2vecの事前学習に使ったPTBのデータセットと比べると、WikiText-2は、(i) 元の句読点を残しているので次文予測に適しており、(ii) 元の大文字・小文字と数字を残しており、(iii) 2倍以上大きい。
import os
import random
import torch
from d2l import torch as d2lIn the WikiText-2 dataset, each line represents a paragraph where space is inserted between any punctuation and its preceding token. Paragraphs with at least two sentences are retained. To split sentences, we only use the period as the delimiter for simplicity. We leave discussions of more complex sentence splitting techniques in the exercises at the end of this section.
英語のヒント
WikiText-2のデータセットでは、各行が一つの段落を表し、そこではどの句読点とその前のトークンとの間にも空白が挿入されている。少なくとも二つの文をもつ段落を残す。文を分割するには、簡単にするため、区切りとしてピリオドだけを使う。もっと複雑な文の分割の技法についての議論は、この節の終わりの練習問題に残しておく。
#@save
d2l.DATA_HUB['wikitext-2'] = (
'https://s3.amazonaws.com/research.metamind.io/wikitext/'
'wikitext-2-v1.zip', '3c914d17d80b1459be871a5039ac23e752a53cbe')
#@save
def _read_wiki(data_dir):
file_name = os.path.join(data_dir, 'wiki.train.tokens')
with open(file_name, 'r') as f:
lines = f.readlines()
# Uppercase letters are converted to lowercase ones
paragraphs = [line.strip().lower().split(' . ')
for line in lines if len(line.split(' . ')) >= 2]
random.shuffle(paragraphs)
return paragraphs