In GAN, i want to find latent vector z corresponding to the real image. One way to do this is to train z to minimize the error between sampled image and real image.
However, when i ran the code below, Error message appeared: “ValueError: can’t optimize a non-leaf Variable”.
targets             # target images of shape (batch_size, 3, 64, 64)

z = Variable(torch.randn(batch_size, 100), requires_grad=True).cuda()
optim = torch.optim.Adam([z], lr=0.01)            # This causes an error. (if i delete cuda() above, it solve the problem)

samples = generator(z)        # sampled images
loss = torch.mean((targets - samples)**2)
loss.backward()

How can i solve this problem?
Thanks,