You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于GAN训练代码中torch.ones与torch.zeros的功能咨询

Understanding torch.ones() and torch.zeros() in GAN Training

Hey there! Let's break down exactly what these two functions are doing in your PyTorch GAN code. First, let's recap the core job of the discriminator in a GAN: it's a binary classifier that needs to tell apart real images from your dataset and fake images generated by the generator.

Let's start with the code snippet you shared:

for epoch in range(num_epoch):
for i, (img, _) in enumerate(dataloader):
    num_img = img.size(0)
    # =================train discriminator
    img = img.view(num_img, -1)
    real_img = Variable(img).cuda()
    real_label = Variable(torch.ones(num_img)).cuda()
    fake_label = Variable(torch.zeros(num_img)).cuda()

What do torch.ones() and torch.zeros() do here?

  • torch.ones(num_img).cuda(): This creates a tensor filled with num_img copies of the value 1, then moves it to your GPU (via .cuda()). This is the ground-truth label for real images. In binary classification terms, we mark real images as the "positive class" (value 1), essentially telling the discriminator: "These images are real—you should output a value close to 1 for them."
  • torch.zeros(num_img).cuda(): This creates a tensor filled with num_img copies of the value 0, also moved to the GPU. This is the ground-truth label for fake images. We mark generated fake images as the "negative class" (value 0), telling the discriminator: "These images are fake—you should output a value close to 0 for them."

Why this matters for GAN training

Later in the full training loop (not shown in your snippet), the code will use these labels to train the discriminator:

  1. It'll feed real_img to the discriminator, compare the model's output to real_label, and calculate loss to teach the discriminator to recognize real images.
  2. It'll generate fake images with the generator, feed those to the discriminator, compare the output to fake_label, and calculate loss to teach the discriminator to spot fakes.

These labels give the discriminator clear, explicit feedback on whether it's correctly classifying images—they're the foundation of how the discriminator learns to do its job.


内容的提问来源于stack exchange,提问作者Nazzzz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:12:52