開始使用免費開始

生成器損失

在訓練 GAN 之前,你需要為生成器與辨別器各自定義損失函式。你會先從前者開始。

回想一下,生成器的工作是產生足以欺騙辨別器的假影像,讓辨別器把它們判為真。因此,若辨別器將生成器產生的影像判為假(標籤 0),生成器就會承受損失。

請定義 gen_loss() 函式來計算生成器的損失。它需要四個參數:

  • gen:生成器模型
  • disc:辨別器模型
  • num_images:批次中的影像數量
  • z_dim:輸入隨機雜訊的維度

本練習屬於課程

使用 PyTorch 進行影像深度學習

檢視課程

練習說明

  • 產生形狀為 num_images 乘以 z_dim 的隨機雜訊,指派給 noise
  • 使用生成器將 noise 轉成假影像,指派給 fake
  • 取得辨別器對產生之假影像的預測。
  • 呼叫 criterion,以辨別器的預測與相同形狀的全 1 張量計算生成器的損失。

動手互動練習

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

def gen_loss(gen, disc, criterion, num_images, z_dim):
    # Define random noise
    noise = ____(num_images, z_dim)
    # Generate fake image
    fake = ____
    # Get discriminator's prediction on the fake image
    disc_pred = ____
    # Compute generator loss
    criterion = nn.BCEWithLogitsLoss()
    gen_loss = ____(____, ____)
    return gen_loss
編輯並執行程式碼