判别器损失
现在需要定义判别器的损失。回顾一下,判别器的任务是将图像分类为真实或生成。因此,如果它把生成器的输出判为真实(标签 1)或把真实图像判为生成(标签 0),就会产生损失。
请定义计算判别器损失的函数 disc_loss()。它接收 5 个参数:
gen,生成器模型disc,判别器模型real,来自训练数据的真实图像样本num_images,批次中的图像数量z_dim,输入随机噪声的维度
本练习是课程的一部分
使用 PyTorch 进行图像深度学习
练习说明
- 使用判别器对
fake图像进行分类,并将预测赋给disc_pred_fake。 - 通过在判别器对假图像的预测与形状相同的全 0 张量上调用
criterion来计算假样本损失分量。 - 使用判别器对
real图像进行分类,并将预测赋给disc_pred_real。 - 通过在判别器对真图像的预测与形状相同的全 1 张量上调用
criterion来计算真样本损失分量。
交互式实操练习
通过完成这段示例代码来试试这个练习。
def disc_loss(gen, disc, real, num_images, z_dim):
criterion = nn.BCEWithLogitsLoss()
noise = torch.randn(num_images, z_dim)
fake = gen(noise)
# Get discriminator's predictions for fake images
disc_pred_fake = ____
# Calculate the fake loss component
fake_loss = ____
# Get discriminator's predictions for real images
disc_pred_real = ____
# Calculate the real loss component
real_loss = ____
disc_loss = (real_loss + fake_loss) / 2
return disc_loss