プリンキピア

第16章自然言語処理:応用

16.4.2. The Stanford Natural Language Inference (SNLI) Dataset16.4.2 スタンフォード自然言語推論(SNLI)データセット

Stanford Natural Language Inference (SNLI) Corpus is a collection of over 500000 labeled English sentence pairs (Bowman et al., 2015). We download and store the extracted SNLI dataset in the path ../data/snli_1.0.
英語のヒント
スタンフォード自然言語推論(SNLI)コーパスは、ラベルのついた50万を超える英語の文の対を集めたものである(Bowman et al., 2015)。展開したSNLIのデータセットをダウンロードして、パス../data/snli_1.0に保存する。
import os
import re
import torch
from torch import nn
from d2l import torch as d2l

#@save
d2l.DATA_HUB['SNLI'] = (
    'https://nlp.stanford.edu/projects/snli/snli_1.0.zip',
    '9fcde07509c7e87ec61c640c1b2753d9041758e4')

data_dir = d2l.download_extract('SNLI')

16.4.2.1. Reading the Dataset16.4.2.1 データセットを読む

The original SNLI dataset contains much richer information than what we really need in our experiments. Thus, we define a function read_snli to only extract part of the dataset, then return lists of premises, hypotheses, and their labels.
英語のヒント
元のSNLIのデータセットには、実験で本当に必要なものよりはるかに豊かな情報が含まれている。そこで、データセットの一部だけを取り出し、前提、仮説、そのラベルのリストを返す関数read_snliを定義する。
#@save
def read_snli(data_dir, is_train):
    """Read the SNLI dataset into premises, hypotheses, and labels."""
    def extract_text(s):
        # Remove information that will not be used by us
        s = re.sub('\\(', '', s)
        s = re.sub('\\)', '', s)
        # Substitute two or more consecutive whitespace with space
        s = re.sub('\\s{2,}', ' ', s)
        return s.strip()
    label_set = {'entailment': 0, 'contradiction': 1, 'neutral': 2}
    file_name = os.path.join(data_dir, 'snli_1.0_train.txt'
                             if is_train else 'snli_1.0_test.txt')
    with open(file_name, 'r') as f:
        rows = [row.split('\t') for row in f.readlines()[1:]]
    premises = [extract_text(row[1]) for row in rows if row[0] in label_set]
    hypotheses = [extract_text(row[2]) for row in rows if row[0] in label_set]
    labels = [label_set[row[0]] for row in rows if row[0] in label_set]
    return premises, hypotheses, labels
Now let’s print the first 3 pairs of premise and hypothesis, as well as their labels (“0”, “1”, and “2” correspond to “entailment”, “contradiction”, and “neutral”, respectively ).
英語のヒント
では、前提と仮説の最初の3対とそのラベルを表示しよう(「0」「1」「2」はそれぞれ「entailment」(含意)、「contradiction」(矛盾)、「neutral」(中立)に対応する)。
train_data = read_snli(data_dir, is_train=True)
for x0, x1, y in zip(train_data[0][:3], train_data[1][:3], train_data[2][:3]):
    print('premise:', x0)
    print('hypothesis:', x1)
    print('label:', y)
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is training his horse for a competition .
label: 2
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is at a diner , ordering an omelette .
label: 1
premise: A person on a horse jumps over a broken down airplane .
hypothesis: A person is outdoors , on a horse .
label: 0
The training set has about 550000 pairs, and the testing set has about 10000 pairs. The following shows that the three labels “entailment”, “contradiction”, and “neutral” are balanced in both the training set and the testing set.
英語のヒント
訓練集合にはおよそ550000対、テスト集合にはおよそ10000対がある。次のコードは、訓練集合でもテスト集合でも、三つのラベル「entailment」「contradiction」「neutral」の数が釣り合っていることを示す。
test_data = read_snli(data_dir, is_train=False)
for data in [train_data, test_data]:
    print([[row for row in data[2]].count(i) for i in range(3)])
[183416, 183187, 182764]
[3368, 3237, 3219]

16.4.2.2. Defining a Class for Loading the Dataset16.4.2.2 データセットを読み込むクラスを定義する

Below we define a class for loading the SNLI dataset by inheriting from the Dataset class in Gluon. The argument num_steps in the class constructor specifies the length of a text sequence so that each minibatch of sequences will have the same shape. In other words, tokens after the first num_steps ones in longer sequence are trimmed, while special tokens “<pad>” will be appended to shorter sequences until their length becomes num_steps. By implementing the __getitem__ function, we can arbitrarily access the premise, hypothesis, and label with the index idx.
英語のヒント
以下では、GluonのDatasetクラスを継承して、SNLIのデータセットを読み込むクラスを定義する。クラスのコンストラクタの引数num_stepsは、系列の各ミニバッチが同じ形状になるように、テキストの系列の長さを指定する。言い換えると、長い系列では最初のnum_steps個より後ろのトークンは切り詰められ、短い系列には、長さがnum_stepsになるまで特殊トークン「<pad>」が付け加えられる。__getitem__関数を実装することで、インデックスidxで前提、仮説、ラベルに任意にアクセスできる。
#@save
class SNLIDataset(torch.utils.data.Dataset):
    """A customized dataset to load the SNLI dataset."""
    def __init__(self, dataset, num_steps, vocab=None):
        self.num_steps = num_steps
        all_premise_tokens = d2l.tokenize(dataset[0])
        all_hypothesis_tokens = d2l.tokenize(dataset[1])
        if vocab is None:
            self.vocab = d2l.Vocab(all_premise_tokens + all_hypothesis_tokens,
                                   min_freq=5, reserved_tokens=['<pad>'])
        else:
            self.vocab = vocab
        self.premises = self._pad(all_premise_tokens)
        self.hypotheses = self._pad(all_hypothesis_tokens)
        self.labels = torch.tensor(dataset[2])
        print('read ' + str(len(self.premises)) + ' examples')

    def _pad(self, lines):
        return torch.tensor([d2l.truncate_pad(
            self.vocab[line], self.num_steps, self.vocab['<pad>'])
                         for line in lines])

    def __getitem__(self, idx):
        return (self.premises[idx], self.hypotheses[idx]), self.labels[idx]

    def __len__(self):
        return len(self.premises)

16.4.2.3. Putting It All Together16.4.2.3 すべてをまとめる

Now we can invoke the read_snli function and the SNLIDataset class to download the SNLI dataset and return DataLoader instances for both training and testing sets, together with the vocabulary of the training set. It is noteworthy that we must use the vocabulary constructed from the training set as that of the testing set. As a result, any new token from the testing set will be unknown to the model trained on the training set.
英語のヒント
これで、read_snli関数とSNLIDatasetクラスを呼び出して、SNLIのデータセットをダウンロードし、訓練集合とテスト集合の両方のDataLoaderのインスタンスを、訓練集合の語彙とともに返せる。訓練集合から作った語彙をテスト集合の語彙として使わなければならないことは注目に値する。その結果、テスト集合にある新しいトークンは、訓練集合で訓練したモデルにとってはどれも未知になる。
#@save
def load_data_snli(batch_size, num_steps=50):
    """Download the SNLI dataset and return data iterators and vocabulary."""
    num_workers = d2l.get_dataloader_workers()
    data_dir = d2l.download_extract('SNLI')
    train_data = read_snli(data_dir, True)
    test_data = read_snli(data_dir, False)
    train_set = SNLIDataset(train_data, num_steps)
    test_set = SNLIDataset(test_data, num_steps, train_set.vocab)
    train_iter = torch.utils.data.DataLoader(train_set, batch_size,
                                             shuffle=True,
                                             num_workers=num_workers)
    test_iter = torch.utils.data.DataLoader(test_set, batch_size,
                                            shuffle=False,
                                            num_workers=num_workers)
    return train_iter, test_iter, train_set.vocab
Here we set the batch size to 128 and sequence length to 50, and invoke the load_data_snli function to get the data iterators and vocabulary. Then we print the vocabulary size.
英語のヒント
ここでは、バッチの大きさを128、系列の長さを50に設定し、load_data_snli関数を呼び出してデータイテレータと語彙を得る。それから、語彙の大きさを表示する。
train_iter, test_iter, vocab = load_data_snli(128, 50)
len(vocab)
read 549367 examples
read 9824 examples
18678
Now we print the shape of the first minibatch. Contrary to sentiment analysis, we have two inputs X[0] and X[1] representing pairs of premises and hypotheses.
英語のヒント
では、最初のミニバッチの形状を表示する。感情分析とは逆に、前提と仮説の対を表す二つの入力X[0]とX[1]がある。
for X, Y in train_iter:
    print(X[0].shape)
    print(X[1].shape)
    print(Y.shape)
    break
torch.Size([128, 50])
torch.Size([128, 50])
torch.Size([128])