建立用於文字的 LSTM 模型
在 PyBooks,團隊持續運用最新技術來提升使用者體驗。為了呼應這個目標,他們指派給你一項關鍵任務。團隊希望你探索另一個強大的工具:LSTM,以其擅長擷取資料樣式中的更多複雜性而聞名。你將使用同一個 Newsgroup 資料集,目標不變:將新聞文章分類為 3 個不同的類別:
rec.autos、sci.med、comp.graphics。
以下套件已為你載入:torch、nn、optim。
本練習屬於課程
Deep Learning for Text with PyTorch
練習說明
- 設定一個 LSTM 模型,為 LSTM 與線性層補上必要的參數。
- 以必要的參數初始化模型。
- 訓練 LSTM 模型,先將梯度重設為 0,並將輸入資料
X_train_seq傳入模型。 - 依據預測的
outputs與真實標籤計算 loss。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize the LSTM and the output layer with parameters
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(LSTMModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(____, ____, ____, batch_first=True)
self.fc = nn.Linear(____, ____)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
out, _ = self.lstm(x, (h0, c0))
out = out[:, -1, :]
out = self.fc(out)
return out
# Initialize model with required parameters
lstm_model = LSTMModel(____, ____, ____, ____)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(lstm_model.parameters(), lr=0.01)
# Train the model by passing the correct parameters and zeroing the gradient
for epoch in range(10):
optimizer.____
outputs = lstm_model(____)
loss = criterion(____, y_train_seq)
loss.backward()
optimizer.step()
print(f'Epoch: {epoch+1}, Loss: {loss.item()}')