(六)为时装设计生成训练和运行GAN

目录

介绍

训练GAN

在训练期间可视化生成的图像

从经过训练的GAN生成时尚图像

下一步


介绍

DeepFashion等数据集的可用性为时尚行业开辟了新的可能性。在本系列文章中,我们将展示一个AI驱动的深度学习系统,它可以帮助我们更好地了解客户的需求,从而彻底改变时装设计行业。

在这个项目中,我们将使用:

我们假设您熟悉深度学习的概念,以及Jupyter NotebooksTensorFlow。如果您不熟悉Jupyter Notebook,请从本教程开始。欢迎下载项目代码

上一篇文章中,我们设计并构建了一个生成对抗网络(GAN)。在本文中,我们将训练 GAN生成逼真的服装图像,类似于DeepFashion数据集中的图像。

训练GAN

生成器训练是通过减少假图像和真实图像之间的损失和误差来完成的 ((log(D(x))+log(D(G(z))。我们将选择大量的时期,因为这种网络需要多次迭代以减少真假图像之间的误差。我们将从40个时期开始进行训练,看看这会带来什么结果。我们将在我们自定义的数据集上训练网络。参数和变量定义如下:

  • G_losses生成器损失,通过将生成器训练期间生成的图像的所有损失相加来计算
  • D_losses判别器损失,通过将真假批次的所有损失相加来计算
  • D(G(z)所有假批次的平均判别器输出
  • D(x)所有真实批次的鉴别器的平均输出(跨批次)

# Lists to keep track of progress
img_list = []  
G_losses = []  
D_losses = [] 
iters = 0
####################################################################
print("Starting Training Loop...")
# For each epoch
for epoch in range(num_epochs):
    # For each batch in the dataloader
    for i, data in enumerate(dataloader, 0):

        ############################
        # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
        ###########################
        ## Train with all-real batch
        netD.zero_grad()
        # Format batch
        real_cpu = data[0].to(device)
        b_size = real_cpu.size(0)
        label = torch.full((b_size,), real_label, dtype=torch.float, device=device)
        # Forward pass real batch through D
        output = netD(real_cpu).view(-1)
        # Calculate loss on all-real batch
        errD_real = criterion(output, label)
        # Calculate gradients for D in backward pass
        errD_real.backward()
        D_x = output.mean().item()

        ## Train with all-fake batch
        # Generate batch of latent vectors
        noise = torch.randn(b_size, nz, 1, 1, device=device)
        # Generate fake image batch with G
        fake = netG(noise)
        label.fill_(fake_label)
        # Classify all fake batch with D
        output = netD(fake.detach()).view(-1)
        # Calculate D's loss on the all-fake batch
        errD_fake = criterion(output, label)
        # Calculate the gradients for this batch
        errD_fake.backward()
        D_G_z1 = output.mean().item()
        # Add the gradients from the all-real and all-fake batches
        errD = errD_real + errD_fake
        # Update D
        optimizerD.step()

        ############################
        # (2) Update G network: maximize log(D(G(z)))
        ###########################
        netG.zero_grad()
        label.fill_(real_label)  # fake labels are real for generator cost
        # Since we just updated D, perform another forward pass of all-fake batch through D
        output = netD(fake).view(-1)
        # Calculate G's loss based on this output
        errG = criterion(output, label)
        # Calculate gradients for G
        errG.backward()
        D_G_z2 = output.mean().item()
        # Update G
        optimizerG.step()

        # Output training stats
        if i % 50 == 0:
            print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
                  % (epoch, num_epochs, i, len(dataloader),
                     errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))

        # Save Losses for plotting later
        G_losses.append(errG.item())
        D_losses.append(errD.item())

        # Check how the generator is doing by saving G's output on fixed_noise
        if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):
            with torch.no_grad():
                fake = netG(fixed_noise).detach().cpu()
            img_list.append(vutils.make_grid(fake, padding=2, normalize=True))

        iters += 1

如您所见,在第40个时期之后,所有假批次的平均判别器输出。

D(G(Z))被降低到一个非常有吸引力的值。有了这个,GAN就足够熟练地生成与数据集中的图像相似的图像。如果你想要更好的图像,你需要增时期的数量并再次训练。

我们还可以绘制训练期间生成器和鉴别器损失的图。

plt.figure(figsize=(10,5))
plt.title("Generator and Discriminator Loss During Training")
plt.plot(G_losses,label="G")
plt.plot(D_losses,label="D")
plt.xlabel("iterations")
plt.ylabel("Loss")
plt.legend()
plt.show()

在训练期间可视化生成的图像

Pytorch提供了将训练期间生成的图像可视化为动画视频的功能。

#%%capture
fig = plt.figure(figsize=(8,8))
plt.axis("off")
ims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]
ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)

HTML(ani.to_jshtml())

从经过训练的GAN生成时尚图像

在我们的GAN训练好之后,我们可以使用这段代码抓取它生成的一批时尚图片。

# Grab a batch of real images from the dataloader
real_batch = next(iter(dataloader))

# Plot the real images
plt.figure(figsize=(15,15))
plt.subplot(1,2,1)
plt.axis("off")
plt.title("Real Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0)))

# Plot the fake images from the last epoch
plt.subplot(1,2,2)
plt.axis("off")
plt.title("Fake Images")
plt.imshow(np.transpose(img_list[-1],(1,2,0)))
plt.show()

看起来我们的GAN能够生成一些与训练数据集中发现的相似的时尚图像。

进一步提高GAN性能的一些快速简便的方法是:

  • 使用转置卷积或上采样层构建更深的生成器
  • 将发生器输入噪声的类型改为高斯
  • 构建更深层次的判别器以提高其预测性能
  • 使用更多的时期和更多的图像训练更长时间

下一步

我们已经到了系列的结尾!我们实现了我们的目标:创建和训练时装设计类别分类的深度网络,并使用GAN开发新的时装设计一代。

尽管如此,我们取得的成果还是可以改进的。例如,您可以在包含各种服装类别的更多图像上训练您的深度网络。您还可以使用深度网络扩展您的项目,该网络可以使用区域建议网络(RPN)检测同一图像中不同类型的衣服。这样的网络将使用预先训练的模型对服装项目进行分类,就像我们在本系列中创建的模型。

https://www.codeproject.com/Articles/5297333/Training-and-Running-a-GAN-for-Fashion-Design-Gene

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值