I need some explanations about GAN codes
Here is github codes



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()


I don`t understand whats the torch.ones and torch.zeros in training codes.

Can anyone explain about this? 

As you probably know: In GAN, generator tries to fool the discriminator by convincing that a fake example is a true example. Discriminator trained to distinguish true examples and fake examples. On the other hand, the generator is trained to generate (fake) examples that look very close to the real examples.



Analysis of the code/example (in the link) you shared.

Generator: is a simple feed-forward neural network. The generator generates 28 * 28 images from random (noisy) distribution. The goal of the generator is to generate images that look like real images.

Discriminator: is a simple feed-forward neural network. The discriminator provides a sigmoid ([0, 1]) score given an image. The goal of the discriminator is to give low score (~0) to fake images and high score (~1) to real images. In essence, the discriminator wants to distinguish real images from fake ones.



How does the code work?

First, the discriminator is provided examples of real images and a loss is computed based on discriminator's predicted score. 

# compute loss of real_img
real_out = D(real_img)
d_loss_real = criterion(real_out, real_label)
real_scores = real_out  # closer to 1 means better


Then the discriminator is provided the fake images generated by the generator. A loss is computed based on discriminator's score on fake examples.

# compute loss of fake_img
z = Variable(torch.randn(num_img, z_dimension)).cuda()
fake_img = G(z)
fake_out = D(fake_img)
d_loss_fake = criterion(fake_out, fake_label)
fake_scores = fake_out  # closer to 0 means better


Essentially, the generator and discriminator are competing against each other to become expert in achieving their goal. We can think in this way: if we have a perfect generator, then it will create fake example exactly look like real ones and the discriminator will fail to distinguish them and vice versa.



The code you provided above is just creating labels using torch.zeros() and torch.ones(). You can simply consider it as binary labels for real and fake images.
