使用 RNN 的文字生成——訓練與生成
PyBooks 團隊現在希望你訓練並測試這個 RNN 模型。此模型會根據輸入來預測序列中的下一個字元,用於書名的自動補完。這個專案將協助團隊進一步開發文字補全的模型。
RNNmodel 類別的 model 實例已為你預先載入。data 變數也已完成前處理並編碼為序列。
inputs 和 targets 變數也都已預先載入。
本練習屬於課程
Deep Learning for Text with PyTorch
練習說明
- 建立用來計算模型誤差的損失函式。
- 從 PyTorch 的最佳化模組建立最佳化器。
- 透過將模型設為 train 模式並在進行最佳化步驟前將梯度歸零,來執行模型訓練流程。
- 訓練完成後,將模型切換為評估模式,以在範例輸入上進行測試。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Instantiate the loss function
criterion = nn.____()
# Instantiate the optimizer
optimizer = torch.optim.____(model.parameters(), lr=0.01)
# Train the model
for epoch in range(100):
model.____()
outputs = model(inputs)
loss = criterion(outputs, targets)
optimizer.____()
loss.backward()
optimizer.step()
if (epoch+1) % 10 == 0:
print(f'Epoch {epoch+1}/100, Loss: {loss.item()}')
# Test the model
model.____()
test_input = char_to_ix['r']
test_input = nn.functional.one_hot(torch.tensor(test_input).view(-1, 1), num_classes=len(chars)).float()
predicted_output = model(test_input)
predicted_char_ix = torch.argmax(predicted_output, 1).item()
print(f"Test Input: 'r', Predicted Output: '{ix_to_char[predicted_char_ix]}'")