開始使用免費開始

建立用於文字生成的 RNN 模型

在 PyBooks,你被指派開發一個能進行文字生成的演算法。這個專案要實作書名的自動補全。為了啟動專案,你決定先用循環神經網路(RNN)做實驗。這樣一來,在進一步使用更複雜的模型前,你可以先掌握 RNN 的細節特性。

以下內容已為你匯入:torchtorch.nn(命名為 nn)。

變數 data 已經以 Lewis Carroll 的 Alice's Adventures in Wonderland 節錄初始化。

本練習屬於課程

Deep Learning for Text with PyTorch

檢視課程

練習說明

  • RNNmodel 類別中加入一個 RNN 層與一個線性層。
  • chars 的長度作為輸入維度、16 作為隱藏層大小、chars 的長度作為輸出維度,實例化這個 RNN 模型。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Include an RNN layer and linear layer in RNNmodel class
class RNNmodel(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(RNNmodel, self).__init__()
        self.hidden_size = hidden_size
        self.rnn = nn.____(input_size, hidden_size, batch_first=True)
        self.fc = nn.____(hidden_size, output_size)

    def forward(self, x):
      h0 = torch.zeros(1, x.size(0), self.hidden_size)
      out, _ = self.rnn(x, h0)  
      out = self.fc(out[:, -1, :])  
      return out

# Instantiate the RNN model
model = RNNmodel(____, ____, ____)
編輯並執行程式碼