当前位置:   article > 正文

昇思25天学习打卡营第25天|DCGAN生成漫画头像

昇思25天学习打卡营第25天|DCGAN生成漫画头像

使用场景

        DCGAN(深度卷积生成对抗网络)被广泛应用于生成图像数据的任务。在本教程中,我们将使用DCGAN生成漫画头像。通过这一教程,您可以了解如何搭建DCGAN网络,设置优化器,计算损失函数,以及初始化模型权重。

原理

        DCGAN是GAN(生成对抗网络)的扩展版本,GAN最早由Ian J. Goodfellow于2014年提出,主要由生成器和判别器两个模型组成。生成器负责生成看似真实的图像,而判别器则负责区分图像是真实的还是生成的。在DCGAN中,这两个模型分别使用卷积和转置卷积层进行图像处理。

        在DCGAN中,判别器由卷积层、BatchNorm层和LeakyReLU激活层组成,输入是3x64x64的图像,输出是该图像为真图像的概率。生成器则由转置卷积层、BatchNorm层和ReLU激活层组成,输入是标准正态分布的隐向量z,输出是3x64x64的RGB图像。

实现方法

数据准备与处理

        首先下载并解压数据集:        

  1. from download import download
  2. url = "https://download.mindspore.cn/dataset/Faces/faces.zip"
  3. path = download(url, "./faces", kind="zip", replace=True)

        然后定义数据处理函数:

  1. import numpy as np
  2. import mindspore.dataset as ds
  3. import mindspore.dataset.vision as vision
  4. def create_dataset_imagenet(dataset_path):
  5. dataset = ds.ImageFolderDataset(dataset_path, num_parallel_workers=4, shuffle=True, decode=True)
  6. transforms = [
  7. vision.Resize(image_size),
  8. vision.CenterCrop(image_size),
  9. vision.HWC2CHW(),
  10. lambda x: ((x / 255).astype("float32"))
  11. ]
  12. dataset = dataset.project('image')
  13. dataset = dataset.map(transforms, 'image')
  14. dataset = dataset.batch(batch_size)
  15. return dataset
  16. dataset = create_dataset_imagenet('./faces')
生成器
  1. from mindspore import nn, ops
  2. from mindspore.common.initializer import Normal
  3. weight_init = Normal(mean=0, sigma=0.02)
  4. gamma_init = Normal(mean=1, sigma=0.02)
  5. class Generator(nn.Cell):
  6. def __init__(self):
  7. super(Generator, self).__init__()
  8. self.generator = nn.SequentialCell(
  9. nn.Conv2dTranspose(nz, ngf * 8, 4, 1, 'valid', weight_init=weight_init),
  10. nn.BatchNorm2d(ngf * 8, gamma_init=gamma_init),
  11. nn.ReLU(),
  12. nn.Conv2dTranspose(ngf * 8, ngf * 4, 4, 2, 'pad', 1, weight_init=weight_init),
  13. nn.BatchNorm2d(ngf * 4, gamma_init=gamma_init),
  14. nn.ReLU(),
  15. nn.Conv2dTranspose(ngf * 4, ngf * 2, 4, 2, 'pad', 1, weight_init=weight_init),
  16. nn.BatchNorm2d(ngf * 2, gamma_init=gamma_init),
  17. nn.ReLU(),
  18. nn.Conv2dTranspose(ngf * 2, ngf, 4, 2, 'pad', 1, weight_init=weight_init),
  19. nn.BatchNorm2d(ngf, gamma_init=gamma_init),
  20. nn.ReLU(),
  21. nn.Conv2dTranspose(ngf, nc, 4, 2, 'pad', 1, weight_init=weight_init),
  22. nn.Tanh()
  23. )
  24. def construct(self, x):
  25. return self.generator(x)
  26. generator = Generator()
判别器
  1. class Discriminator(nn.Cell):
  2. def __init__(self):
  3. super(Discriminator, self).__init__()
  4. self.discriminator = nn.SequentialCell(
  5. nn.Conv2d(nc, ndf, 4, 2, 'pad', 1, weight_init=weight_init),
  6. nn.LeakyReLU(0.2),
  7. nn.Conv2d(ndf, ndf * 2, 4, 2, 'pad', 1, weight_init=weight_init),
  8. nn.BatchNorm2d(ndf * 2, gamma_init=gamma_init),
  9. nn.LeakyReLU(0.2),
  10. nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 'pad', 1, weight_init=weight_init),
  11. nn.BatchNorm2d(ndf * 4, gamma_init=gamma_init),
  12. nn.LeakyReLU(0.2),
  13. nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 'pad', 1, weight_init=weight_init),
  14. nn.BatchNorm2d(ndf * 8, gamma_init=gamma_init),
  15. nn.LeakyReLU(0.2),
  16. nn.Conv2d(ndf * 8, 1, 4, 1, 'valid', weight_init=weight_init),
  17. )
  18. self.adv_layer = nn.Sigmoid()
  19. def construct(self, x):
  20. out = self.discriminator(x)
  21. out = out.reshape(out.shape[0], -1)
  22. return self.adv_layer(out)
  23. discriminator = Discriminator()
损失函数和优化器
  1. adversarial_loss = nn.BCELoss(reduction='mean')
  2. optimizer_D = nn.Adam(discriminator.trainable_params(), learning_rate=lr, beta1=beta1)
  3. optimizer_G = nn.Adam(generator.trainable_params(), learning_rate=lr, beta1=beta1)
  4. optimizer_G.update_parameters_name('optim_g.')
  5. optimizer_D.update_parameters_name('optim_d.')
训练模型
  1. import mindspore
  2. import matplotlib.pyplot as plt
  3. def generator_forward(real_imgs, valid):
  4. z = ops.standard_normal((real_imgs.shape[0], nz, 1, 1))
  5. gen_imgs = generator(z)
  6. g_loss = adversarial_loss(discriminator(gen_imgs), valid)
  7. return g_loss, gen_imgs
  8. def discriminator_forward(real_imgs, gen_imgs, valid, fake):
  9. real_loss = adversarial_loss(discriminator(real_imgs), valid)
  10. fake_loss = adversarial_loss(discriminator(gen_imgs), fake)
  11. d_loss = (real_loss + fake_loss) / 2
  12. return d_loss
  13. grad_generator_fn = mindspore.value_and_grad(generator_forward, None, optimizer_G.parameters, has_aux=True)
  14. grad_discriminator_fn = mindspore.value_and_grad(discriminator_forward, None, optimizer_D.parameters)
  15. @mindspore.jit
  16. def train_step(imgs):
  17. valid = ops.ones((imgs.shape[0], 1), mindspore.float32)
  18. fake = ops.zeros((imgs.shape[0], 1), mindspore.float32)
  19. (g_loss, gen_imgs), g_grads = grad_generator_fn(imgs, valid)
  20. optimizer_G(g_grads)
  21. d_loss, d_grads = grad_discriminator_fn(imgs, gen_imgs, valid, fake)
  22. optimizer_D(d_grads)
  23. return g_loss, d_loss, gen_imgs
  24. G_losses = []
  25. D_losses = []
  26. image_list = []
  27. total = dataset.get_dataset_size()
  28. for epoch in range(num_epochs):
  29. generator.set_train()
  30. discriminator.set_train()
  31. for i, (imgs, ) in enumerate(dataset.create_tuple_iterator()):
  32. g_loss, d_loss, gen_imgs = train_step(imgs)
  33. if i % 100 == 0 or i == total - 1:
  34. print('[%2d/%d][%3d/%d] Loss_D:%7.4f Loss_G:%7.4f' % (
  35. epoch + 1, num_epochs, i + 1, total, d_loss.asnumpy(), g_loss.asnumpy()))
  36. D_losses.append(d_loss.asnumpy())
  37. G_losses.append(g_loss.asnumpy())
  38. generator.set_train(False)
  39. fixed_noise = ops.standard_normal((batch_size, nz, 1, 1))
  40. img = generator(fixed_noise)
  41. image_list.append(img.transpose(0, 2, 3, 1).asnumpy())
  42. mindspore.save_checkpoint(generator, "./generator.ckpt")
  43. mindspore.save_checkpoint(discriminator, "./discriminator.ckpt")
结果展示

        绘制损失函数变化图:        

  1. plt.figure(figsize=(10, 5))
  2. plt.title("Generator and Discriminator Loss During Training")
  3. plt.plot(G_losses, label="G", color='blue')
  4. plt.plot(D_losses, label="D", color='orange')
  5. plt.xlabel("iterations")
  6. plt.ylabel("Loss")
  7. plt.legend()
  8. plt.show()

通过隐向量生成图像并保存:

  1. import matplotlib.animation as animation
  2. def showGif(image_list):
  3. show_list = []
  4. fig = plt.figure(figsize=(8, 3), dpi=120)
  5. for epoch in range(len(image_list)):
  6. images = []
  7. for i in range(3):
  8. row = np.concatenate((image_list[epoch][i * 8:(i + 1) * 8]), axis=1)
  9. images.append(row)
  10. img = np.clip(np.concatenate((images[:]), axis=0), 0, 1)
  11. plt.axis("off")
  12. show_list.append([plt.imshow(img)])
  13. ani = animation.ArtistAnimation(fig, show_list, interval=1000, repeat_delay=1000, blit=True)
  14. ani.save('./dcgan.gif', writer='pillow', fps=1)
  15. showGif(image_list)

加载生成器网络模型参数文件来生成图像:

  1. mindspore.load_checkpoint("./generator.ckpt", generator)
  2. fixed_noise = ops.standard_normal((batch_size, nz, 1, 1))
  3. img64 = generator(fixed_noise).transpose(0, 2, 3, 1).asnumpy()
  4. fig = plt.figure(figsize=(8, 3), dpi=120)
  5. images = []
  6. for i in range(3):
  7. images.append(np.concatenate((img64[i * 8:(i + 1) * 8]), axis=1))
  8. img = np.clip(np.concatenate((images[:]), axis=0), 0, 1)
  9. plt.axis("off")
  10. plt.imshow(img)
  11. plt.show()

结果

学习心得:在学习和实现DCGAN(深度卷积生成对抗网络)的过程中,我们通过搭建卷积神经网络来生成漫画头像。这不仅加深了我们对GAN(生成对抗网络)原理的理解,也让我们体验到了生成模型和判别模型之间的博弈过程。通过实际操作,我们学会了如何下载并预处理数据集,如何构建生成器和判别器网络,以及如何设置损失函数和优化器。在训练模型的过程中,观察生成器和判别器的损失变化,逐步优化模型参数,最终生成出高质量的漫画头像图片。这次实践不仅强化了我们对深度学习框架的使用技能,也让我们体会到了生成对抗网络在图像生成领域的强大潜力和应用前景。

如果你觉得这篇博文对你有帮助,请点赞、收藏、关注我,并且可以打赏支持我!

欢迎关注我的后续博文,我将分享更多关于人工智能、自然语言处理和计算机视觉的精彩内容。

谢谢大家的支持!

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号