プリンキピア

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

16.5.2. Training and Evaluating the Model16.5.2 モデルを訓練し評価する

Now we will train and evaluate the defined decomposable attention model on the SNLI dataset. We begin by reading the dataset.
英語のヒント
では、定義した分解可能な注意モデルを、SNLIのデータセットで訓練し評価する。まずデータセットを読む。

16.5.2.1. Reading the dataset16.5.2.1 データセットを読む

We download and read the SNLI dataset using the function defined in Section 16.4. The batch size and sequence length are set to 256 and 50, respectively.
英語のヒント
16.4節で定義した関数を使って、SNLIのデータセットをダウンロードして読む。バッチの大きさと系列の長さは、それぞれ256と50に設定する。
batch_size, num_steps = 256, 50
train_iter, test_iter, vocab = d2l.load_data_snli(batch_size, num_steps)
Downloading ../data/snli_1.0.zip from https://nlp.stanford.edu/projects/snli/snli_1.0.zip...
read 549367 examples
read 9824 examples

16.5.2.2. Creating the Model16.5.2.2 モデルを作る

We use the pretrained 100-dimensional GloVe embedding to represent the input tokens. Thus, we predefine the dimension of vectors 𝐚i and 𝐛j in (16.5.1) as 100. The output dimension of functions f in (16.5.1) and g in (16.5.4) is set to 200. Then we create a model instance, initialize its parameters, and load the GloVe embedding to initialize vectors of input tokens.
英語のヒント
入力トークンを表すのに、事前学習した100次元のGloVeの埋め込みを使う。したがって、(16.5.1)のベクトル𝐚iと𝐛jの次元をあらかじめ100と決める。(16.5.1)の関数fと(16.5.4)の関数gの出力の次元は200に設定する。それから、モデルのインスタンスを作り、そのパラメータを初期化し、GloVeの埋め込みを読み込んで入力トークンのベクトルを初期化する。
embed_size, num_hiddens, devices = 100, 200, d2l.try_all_gpus()
net = DecomposableAttention(vocab, embed_size, num_hiddens)
glove_embedding = d2l.TokenEmbedding('glove.6b.100d')
embeds = glove_embedding[vocab.idx_to_token]
net.embedding.weight.data.copy_(embeds);
Downloading ../data/glove.6B.100d.zip from http://d2l-data.s3-accelerate.amazonaws.com/glove.6B.100d.zip...

16.5.2.3. Training and Evaluating the Model16.5.2.3 モデルを訓練し評価する

In contrast to the split_batch function in Section 13.5 that takes single inputs such as text sequences (or images), we define a split_batch_multi_inputs function to take multiple inputs such as premises and hypotheses in minibatches.
英語のヒント
テキストの系列(または画像)のような単一の入力をとる13.5節のsplit_batch関数とは対照的に、ミニバッチの中の前提と仮説のような複数の入力をとるsplit_batch_multi_inputs関数を定義する。
Now we can train and evaluate the model on the SNLI dataset.
英語のヒント
これで、SNLIのデータセットでモデルを訓練し評価できる。
lr, num_epochs = 0.001, 4
trainer = torch.optim.Adam(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss(reduction="none")
d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)
loss 0.496, train acc 0.805, test acc 0.828
20383.2 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]

16.5.2.4. Using the Model16.5.2.4 モデルを使う

Finally, define the prediction function to output the logical relationship between a pair of premise and hypothesis.
英語のヒント
最後に、前提と仮説の対の間の論理的な関係を出力する予測関数を定義する。
#@save
def predict_snli(net, vocab, premise, hypothesis):
    """Predict the logical relationship between the premise and hypothesis."""
    net.eval()
    premise = torch.tensor(vocab[premise], device=d2l.try_gpu())
    hypothesis = torch.tensor(vocab[hypothesis], device=d2l.try_gpu())
    label = torch.argmax(net([premise.reshape((1, -1)),
                           hypothesis.reshape((1, -1))]), dim=1)
    return 'entailment' if label == 0 else 'contradiction' if label == 1 \
            else 'neutral'
We can use the trained model to obtain the natural language inference result for a sample pair of sentences.
英語のヒント
訓練したモデルを使って、見本の文の対についての自然言語推論の結果を得られる。
predict_snli(net, vocab, ['he', 'is', 'good', '.'], ['he', 'is', 'bad', '.'])
'contradiction'