关于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 withnum_imgcopies of the value1, 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 withnum_imgcopies of the value0, 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:
- It'll feed
real_imgto the discriminator, compare the model's output toreal_label, and calculate loss to teach the discriminator to recognize real images. - 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
相关产品推荐
相关产品推荐

