アテンション付き RNN モデルの学習とテスト
PyBooks では、以前にアテンション機構なしで単語予測用の RNN モデルを構築していました。この初期モデル(rnn_model)はすでに学習済みで、インスタンスが読み込まれています。あなたのタスクは、新しい RNNWithAttentionModel を学習し、以前の rnn_model の予測と比較することです。
次のものがあらかじめ読み込まれています:
inputs: テンソルとしての入力系列のリストtargets: 各入力系列に対応する目標単語を含むテンソルoptimizer: Adam オプティマイザ関数criterion: CrossEntropyLoss 関数pad_sequences: バッチ化のために入力系列にパディングを行う関数attention_model: 前の演習で定義したモデルクラスrnn_model: PyBooks のチームが作成した学習済み RNN モデル
この演習はコースの一部です
PyTorch で学ぶテキストの Deep Learning
演習の手順
- テストデータで評価する前に、RNN モデルを評価モードに設定します。
- 適切な入力を RNN モデルに渡して、RNN の出力を取得します。
- RNN 出力から、予測スコアが最も高い単語を取り出します。
- 同様に、アテンションモデルでも、アテンション出力から予測スコアが最も高い単語を取り出します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
for epoch in range(epochs):
attention_model.train()
optimizer.zero_grad()
padded_inputs = pad_sequences(inputs)
outputs = attention_model(padded_inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
for input_seq, target in zip(input_data, target_data):
input_test = torch.tensor(input_seq, dtype=torch.long).unsqueeze(0)
# Set the RNN model to evaluation mode
rnn_model.____()
# Get the RNN output by passing the appropriate input
rnn_output = ____(____)
# Extract the word with the highest prediction score
rnn_prediction = ix_to_word[torch.____(____).item()]
attention_model.eval()
attention_output = attention_model(input_test)
# Extract the word with the highest prediction score
attention_prediction = ix_to_word[torch.____(____).item()]
print(f"\nInput: {' '.join([ix_to_word[ix] for ix in input_seq])}")
print(f"Target: {ix_to_word[target]}")
print(f"RNN prediction: {rnn_prediction}")
print(f"RNN with Attention prediction: {attention_prediction}")