開始使用免費開始

建立產生器與鑑別器

在 PyBooks,你受託開發一個自動文字產生器,協助作者克服靈感枯竭。你打算使用 GAN(Generative Adversarial Networks,生成對抗網路),建立一個系統:其中一個網路(產生器)用來產生新文字,另一個網路(鑑別器)用來評估其真實性。為了達成這個目標,你需要初始化產生器與鑑別器兩個網路。之後這兩個網路會彼此對抗式訓練,以產生可信的新文字。

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

本練習屬於課程

Deep Learning for Text with PyTorch

檢視課程

練習說明

  • 定義 Generator 類別,包含一個用於序列資料的線性層與 sigmoid 啟用函式。
  • Generator 類別的 forward() 方法中,將輸入傳遞進已定義的模型。
  • 定義 Discriminator 類別,使用相同的層與啟用函式,並留意維度的設定。

動手互動練習

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

# Define the generator class
class Generator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.____(nn.____(____), nn.____())
    def forward(self, x):
        return self.____(x)

# Define the discriminator networks
class Discriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.____(nn.____(____), nn.____())
    def forward(self, x):
        return self.model(x)
編輯並執行程式碼