開始使用免費開始

以注意力機制訓練與測試 RNN 模型

在 PyBooks,團隊先前曾建立一個沒有注意力機制的 RNN 單字預測模型。這個初始模型稱為 rnn_model,已完成訓練且其實例已預先載入。你現在的任務是訓練新的 RNNWithAttentionModel,並將它的預測與較早的 rnn_model 做比較。

已為你預先載入以下物件:

  • inputs:以張量表示的輸入序列清單
  • targets:包含每個輸入序列目標單字的張量
  • optimizer:Adam 最佳化器函式
  • criterion:CrossEntropyLoss 函式
  • pad_sequences:用於將輸入序列填充以便批次處理的函式
  • attention_model:前一個練習中定義的模型類別
  • rnn_model:PyBooks 團隊訓練完成的 RNN 模型

本練習屬於課程

Deep Learning for Text with PyTorch

檢視課程

練習說明

  • 在使用測試資料進行測試之前,將 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}")
編輯並執行程式碼