建立用於文字的 GRU 模型
在 PyBooks,你先前訓練的兩個模型表現令團隊印象深刻。不過,為了追求更佳成果,他們希望為目前的任務挑選出最優模型。因此,他們請你進一步擴充專案,嘗試使用以效率與效果見長的 GRU 模型,來處理文字分類。你的新任務是使用 GRU 模型,將 Newsgroup 資料集中的文章分類為以下類別:
rec.autos、sci.med、以及 comp.graphics。
已為你載入下列套件:torch、nn、optim。
本練習屬於課程
Deep Learning for Text with PyTorch
練習說明
- 以必要參數完成 GRU 類別。
- 使用相同參數初始化模型。
- 訓練模型:將參數傳入損失函式(criterion),並對損失進行反向傳播。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Complete the GRU model
class GRUModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(GRUModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.gru = ____
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size)
out, _ = self.gru(x, h0)
out = out[:, -1, :]
out = self.fc(out)
return out
# Initialize the model
gru_model = ____
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(gru_model.parameters(), lr=0.01)
# Train the model and backpropagate the loss after initialization
for epoch in range(15):
optimizer.zero_grad()
outputs = ____
loss = criterion(____, y_train_seq)
____
optimizer.step()
print(f'Epoch: {epoch+1}, Loss: {loss.item()}')