使用pytorch构建有监督的条件GAN(conditional GAN)网络模型

2024-04-08 10:12

本文主要是介绍使用pytorch构建有监督的条件GAN(conditional GAN)网络模型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文为此系列的第四篇conditional GAN,上一篇为WGAN-GP。文中在无监督的基础上重点讲解作为有监督对比无监督的差异,若有不懂的无监督知识点可以看本系列第一篇。

原理

  • 有条件与无条件
    在这里插入图片描述
    如图投进硬币随机得到一个乒乓球的例子可以看成是一个无监督的GAN,硬币作为输入(noise),出乒乓球的机器作为生成器(generator),生成的乒乓球作为生成器生成的example。
    从这个例子中我们可以知道生成的乒乓球有什么颜色的,因为这些都是我们训练的数据分布,但我们不知道生成的是什么颜色的乒乓球,因为是无监督的。
    在这里插入图片描述
    这个例子中,投掷硬币和输入想要的饮料名称例如红色的苏打水,就会随机投出一瓶选定类型的红色苏打水,而不会投出绿色的雪碧。
    这里不同于上面的例子的是输入中多了一个饮料名称(class),以及输出可以选择想要的类型。这里输入的类别必须在机器给定的类别之内选择不能选择没有给定的类别,就好像我们训练时只训练这些类别生成器就只知道这些类别的东西,其他类别的东西就会出错。
    这样可以选择类别输出的例子就是有监督的。

    注意:这里虽然可以选择类别输出,但不能控制特性输出,比如我们可以选择投出一瓶苏打水,但不能选择固定生产日期的苏打水,或者某品牌的苏打水等,这类可控制特性输出的叫做Controllable
    GAN,在下一篇作讲解。

    在这里插入图片描述

    这就是有条件与无条件的区别,有条件的在训练时数据需要有标签,前向传播时输入生成器还需要多加一个class向量。

  • 输入
    在这里插入图片描述
    如图,在无监督的GAN中,噪声向量也是一维的;在有监督中的GAN中,我们所需的class也要是one-hot形式的一维向量(长度为类别数量)。但我们不是直接将两个向量输入进生成器中,而是合成一个向量。
    在这里插入图片描述
    作为generator的输入如图:
    在这里插入图片描述
    输入进discriminator也是需要有class的信息
    在这里插入图片描述
    在这里插入图片描述
    但是不是想上图这样分开作为两个向量的输入,而是也是合成为一个向量进行输入。但是图像信息作为三维向量,类别信息作为一维向量,就需要进行处理:
    在这里插入图片描述
    类别信息要先转为one-hot形式,然后每个类别处理成一个image_height * image_width的二维向量作为一个channel与图像信息进行concat。

代码

model.py

from torch import nnclass Generator(nn.Module):def __init__(self, input_dim=10, im_chan=1, hidden_dim=64):super(Generator, self).__init__()self.input_dim = input_dim# Build the neural networkself.gen = nn.Sequential(self.make_gen_block(input_dim, hidden_dim * 4),self.make_gen_block(hidden_dim * 4, hidden_dim * 2, kernel_size=4, stride=1),self.make_gen_block(hidden_dim * 2, hidden_dim),self.make_gen_block(hidden_dim, im_chan, kernel_size=4, final_layer=True),)def make_gen_block(self, input_channels, output_channels, kernel_size=3, stride=2, final_layer=False):if not final_layer:return nn.Sequential(nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride),nn.BatchNorm2d(output_channels),nn.ReLU(inplace=True),)else:return nn.Sequential(nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride),nn.Tanh(),)def forward(self, noise):x = noise.view(len(noise), self.input_dim, 1, 1)return self.gen(x)class Discriminator(nn.Module):def __init__(self, im_chan=1, hidden_dim=64):super(Discriminator, self).__init__()self.disc = nn.Sequential(self.make_disc_block(im_chan, hidden_dim),self.make_disc_block(hidden_dim, hidden_dim * 2),self.make_disc_block(hidden_dim * 2, 1, final_layer=True),)def make_disc_block(self, input_channels, output_channels, kernel_size=4, stride=2, final_layer=False):if not final_layer:return nn.Sequential(nn.Conv2d(input_channels, output_channels, kernel_size, stride),nn.BatchNorm2d(output_channels),nn.LeakyReLU(0.2, inplace=True),)else:return nn.Sequential(nn.Conv2d(input_channels, output_channels, kernel_size, stride),)def forward(self, image):disc_pred = self.disc(image)return disc_pred.view(len(disc_pred), -1)

train.py

import torch
from torch import nn
from tqdm.auto import tqdm
from torchvision import transforms
from torchvision.datasets import MNIST
from torchvision.utils import make_grid
from torch.utils.data import DataLoader
import torch.nn.functional as F
import matplotlib.pyplot as plt
from model import *
torch.manual_seed(0) # Set for our testing purposes, please do not change!def show_tensor_images(image_tensor, num_images=25, size=(1, 28, 28), nrow=5, show=True):'''Function for visualizing images: Given a tensor of images, number of images, andsize per image, plots and prints the images in an uniform grid.'''image_tensor = (image_tensor + 1) / 2image_unflat = image_tensor.detach().cpu()image_grid = make_grid(image_unflat[:num_images], nrow=nrow)plt.imshow(image_grid.permute(1, 2, 0).squeeze())if show:plt.show()def get_noise(n_samples, input_dim, device='cpu'):'''Function for creating noise vectors: Given the dimensions (n_samples, input_dim)creates a tensor of that shape filled with random numbers from the normal distribution.Parameters:n_samples: the number of samples to generate, a scalarinput_dim: the dimension of the input vector, a scalardevice: the device type'''return torch.randn(n_samples, input_dim, device=device)def get_one_hot_labels(labels, n_classes):return F.one_hot(labels,n_classes)def combine_vectors(x, y):combined = torch.cat((x.float(),y.float()), 1)return combinedmnist_shape = (1, 28, 28)
n_classes = 10criterion = nn.BCEWithLogitsLoss()
n_epochs = 200
z_dim = 64
display_step = 500
batch_size = 128
lr = 0.0002
device = 'cuda'transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5,), (0.5,)),
])dataloader = DataLoader(MNIST('.', download=False, transform=transform),batch_size=batch_size,shuffle=True)def get_input_dimensions(z_dim, mnist_shape, n_classes):generator_input_dim = z_dim + n_classesdiscriminator_im_chan = mnist_shape[0] + n_classesreturn generator_input_dim, discriminator_im_changenerator_input_dim, discriminator_im_chan = get_input_dimensions(z_dim, mnist_shape, n_classes)gen = Generator(input_dim=generator_input_dim).to(device)
gen_opt = torch.optim.Adam(gen.parameters(), lr=lr)
disc = Discriminator(im_chan=discriminator_im_chan).to(device)
disc_opt = torch.optim.Adam(disc.parameters(), lr=lr)def weights_init(m):if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):torch.nn.init.normal_(m.weight, 0.0, 0.02)if isinstance(m, nn.BatchNorm2d):torch.nn.init.normal_(m.weight, 0.0, 0.02)torch.nn.init.constant_(m.bias, 0)
gen = gen.apply(weights_init)
disc = disc.apply(weights_init)cur_step = 0
generator_losses = []
discriminator_losses = []# UNIT TEST NOTE: Initializations needed for grading
noise_and_labels = False
fake = Falsefake_image_and_labels = False
real_image_and_labels = False
disc_fake_pred = False
disc_real_pred = Falsebest_gen_loss = float('inf')
last_gen_loss = 0for epoch in range(n_epochs):# Dataloader returns the batches and the labelsfor real, labels in tqdm(dataloader):cur_batch_size = len(real)# Flatten the batch of real images from the datasetreal = real.to(device)one_hot_labels = get_one_hot_labels(labels.to(device), n_classes)image_one_hot_labels = one_hot_labels[:, :, None, None]image_one_hot_labels = image_one_hot_labels.repeat(1, 1, mnist_shape[1], mnist_shape[2])### Update discriminator #### Zero out the discriminator gradientsdisc_opt.zero_grad()# Get noise corresponding to the current batch_sizefake_noise = get_noise(cur_batch_size, z_dim, device=device)noise_and_labels = combine_vectors(fake_noise, one_hot_labels)fake = gen(noise_and_labels)fake_image_and_labels = combine_vectors(fake, image_one_hot_labels)real_image_and_labels = combine_vectors(real, image_one_hot_labels)disc_fake_pred = disc(fake_image_and_labels.detach())disc_real_pred = disc(real_image_and_labels)disc_fake_loss = criterion(disc_fake_pred, torch.zeros_like(disc_fake_pred))disc_real_loss = criterion(disc_real_pred, torch.ones_like(disc_real_pred))disc_loss = (disc_fake_loss + disc_real_loss) / 2disc_loss.backward(retain_graph=True)disc_opt.step()# Keep track of the average discriminator lossdiscriminator_losses += [disc_loss.item()]### Update generator #### Zero out the generator gradientsgen_opt.zero_grad()fake_image_and_labels = combine_vectors(fake, image_one_hot_labels)# This will error if you didn't concatenate your labels to your image correctlydisc_fake_pred = disc(fake_image_and_labels)gen_loss = criterion(disc_fake_pred, torch.ones_like(disc_fake_pred))gen_loss.backward()gen_opt.step()# Keep track of the generator lossesgenerator_losses += [gen_loss.item()]if cur_step % display_step == 0 and cur_step > 0:gen_mean = sum(generator_losses[-display_step:]) / display_stepdisc_mean = sum(discriminator_losses[-display_step:]) / display_stepprint(f"Step {cur_step}: Generator loss: {gen_mean}, discriminator loss: {disc_mean}")show_tensor_images(fake)show_tensor_images(real)step_bins = 20x_axis = sorted([i * step_bins for i in range(len(generator_losses) // step_bins)] * step_bins)num_examples = (len(generator_losses) // step_bins) * step_binsplt.plot(range(num_examples // step_bins),torch.Tensor(generator_losses[:num_examples]).view(-1, step_bins).mean(1),label="Generator Loss")plt.plot(range(num_examples // step_bins),torch.Tensor(discriminator_losses[:num_examples]).view(-1, step_bins).mean(1),label="Discriminator Loss")plt.legend()plt.show()elif cur_step == 0:print("Congratulations! If you've gotten here, it's working. Please let this train until you're happy with how the generated numbers look, and then go on to the exploration!")cur_step += 1# Save generator modelif gen_loss < best_gen_loss:best_gen_loss = gen_losstorch.save(gen.state_dict(), 'best_generator.pth')last_gen_loss = gen_losstorch.save(gen.state_dict(), 'last_generator.pth')# test
import math
gen = gen.eval()checkpoint = torch.load('best_generator.pth')
gen.load_state_dict(checkpoint)
gen.to(device)n_interpolation = 9 # Choose the interpolation: how many intermediate images you want + 2 (for the start and end image)
interpolation_noise = get_noise(1, z_dim, device=device).repeat(n_interpolation, 1)def interpolate_class(first_number, second_number):first_label = get_one_hot_labels(torch.Tensor([first_number]).long(), n_classes)second_label = get_one_hot_labels(torch.Tensor([second_number]).long(), n_classes)# Calculate the interpolation vector between the two labelspercent_second_label = torch.linspace(0, 1, n_interpolation)[:, None]interpolation_labels = first_label * (1 - percent_second_label) + second_label * percent_second_label# Combine the noise and the labelsnoise_and_labels = combine_vectors(interpolation_noise, interpolation_labels.to(device))fake = gen(noise_and_labels)show_tensor_images(fake, num_images=n_interpolation, nrow=int(math.sqrt(n_interpolation)), show=False)start_plot_number = 1 # Choose the start digit
end_plot_number = 5 # Choose the end digitplt.figure(figsize=(8, 8))
interpolate_class(start_plot_number, end_plot_number)
_ = plt.axis('off')plot_numbers = [2, 3, 4, 5, 7]
n_numbers = len(plot_numbers)
plt.figure(figsize=(8, 8))
for i, first_plot_number in enumerate(plot_numbers):for j, second_plot_number in enumerate(plot_numbers):plt.subplot(n_numbers, n_numbers, i * n_numbers + j + 1)interpolate_class(first_plot_number, second_plot_number)plt.axis('off')
plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0.1, wspace=0)
plt.show()
plt.close()n_interpolation = 9 # How many intermediate images you want + 2 (for the start and end image)# This time you're interpolating between the noise instead of the labels
interpolation_label = get_one_hot_labels(torch.Tensor([5]).long(), n_classes).repeat(n_interpolation, 1).float()def interpolate_noise(first_noise, second_noise):# This time you're interpolating between the noise instead of the labelspercent_first_noise = torch.linspace(0, 1, n_interpolation)[:, None].to(device)interpolation_noise = first_noise * percent_first_noise + second_noise * (1 - percent_first_noise)# Combine the noise and the labels againnoise_and_labels = combine_vectors(interpolation_noise, interpolation_label.to(device))fake = gen(noise_and_labels)show_tensor_images(fake, num_images=n_interpolation, nrow=int(math.sqrt(n_interpolation)), show=False)n_noise = 5 # Choose the number of noise examples in the grid
plot_noises = [get_noise(1, z_dim, device=device) for i in range(n_noise)]
plt.figure(figsize=(8, 8))
for i, first_plot_noise in enumerate(plot_noises):for j, second_plot_noise in enumerate(plot_noises):plt.subplot(n_noise, n_noise, i * n_noise + j + 1)interpolate_noise(first_plot_noise, second_plot_noise)plt.axis('off')
plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0.1, wspace=0)
plt.show()
plt.close()

代码解析

  • 网络模型模块没啥可说的,就是生成器和鉴别器的输入channel改变了而已。
  • 一个是将类别信息转成one-hot形式的编码,一个是将两个向量concat成一个向量。
    在这里插入图片描述

比如类别为1,one-hot形式的编码就是第二个位置为1,其余位置为0,长度为类别的数量:
在这里插入图片描述

  • 计算生成器和鉴别器的输入向量的channel,生成器的输入channel为随机噪声的channel+类别数量,鉴别器的channel为生成图片的channel+类别数量。
    在这里插入图片描述
  • 对标签信息进行处理成输入discriminator的格式。首先对label进行one-hot格式处理,然后在最后扩展两个维度便于卷积操作,最后将一个one-hot向量中的每个类别(单个值)都复制成宽高与图像一致的二维向量。
    在这里插入图片描述
    首先我们可以打印出labels及其shape,可以看到有batch_size个标签,且是一维的。
    在这里插入图片描述
    然后打印出其one-hot向量及其shape。
    在这里插入图片描述
    然后打印出扩展维度后的向量及其shape,本来每个label的shape为[10],在最后插入两个维度后变成[10,1,1],相对于进行了两次unsqueeze(-1)操作。
    在这里插入图片描述
    在这里插入图片描述
    然后打印出复制操作后的向量及其shape,将每个label的shape从[10,1,1]变为[10,28,28]。这样就可以知道.repeat()函数中第一个参数1表示:
    • 在第一个维度(批量大小维度)上不进行重复,即不改变批量大小;
    • 第二个参数1表示在第二个维度(类别数维度)上不进行重复,即不改变类别数;
    • mnist_shape[1]表示在高度维度上重复的次数,即重复到与 MNIST图像的高度相匹配;
    • mnist_shape[2]表示在宽度维度上重复的次数,即重复到与 MNIST图像的宽度相匹配。
      在这里插入图片描述
      在这里插入图片描述
  • 显示中间过程模块如下,如果不想看中间过程或者嫌弃一直一个一个关掉窗口太麻烦的话可以直接注释掉这段。
    在这里插入图片描述
  • 到此为止训练部分都已经结束了,训练完保存了best模型和last模型在当前文件夹中。下面的test部分开始是对结果的检验。
    在这里插入图片描述
    这个模块是在两个不同的模式中进行插值,来查看两个模式生成的中间结果。
    • 首先.eval()是PyTorch中模型在评估模式下进行使用的,目的是为了在测试阶段时取消某些层(例如以下两个层)对输出结果的随机性的行为,从而获得更加稳定和可靠的预测结果。
      • 关闭Dropout层。在训练过程中,Dropout层会随机丢弃一部分神经元,起到过拟合的作用。而在评估过程中,为了保证每次的输出不具有随机性,Dropout 层通常会被关闭,使得所有神经元都参与到前向传播过程中。
      • 冻结Batch Normalization层。在训练过程中,BN层会根据每个批次的统计信息对输入进行标准化处理。而在评估过程中,也是因为为了保证每次的输出不具有随机性,BN层通常会被冻结,即使用训练时得到的均值方差来进行标准化。
    • 可以改变n_interpolation的值来查看两个结果的中间过程,如代码中赋值为9,有2个是结果其余7个是中间过程。具体实现方式是:
      • 首先使用torch.linspace函数生成从0到1的等间距的n_interpolation个数据点,然后扩展一个dimension,给每个值单独括起来。生成的这些值用于控制两个标签之间的插值比例。
      • first_label * (1 - percent_second_label) + second_label * percent_second_label然后通过加权的方式计算两个标签之间的插值标签。
      • 最后就是将得到的插值标签与随机噪声结合后送入generator中得到生成结果。
        在这里插入图片描述
  • 我们也可以同时可视化一组数字标签之间的插值结果。
    在这里插入图片描述
    这就是在给定的一组标签之间两两进行插值,得到最早的可视化结果。
    在这里插入图片描述
  • 上面是输入不同的class查看测试结果。下面测试一下保持class不变改变随机向量的结果。
    在这里插入图片描述
    插值原理与上面类似,只不过上面的中间过程是标签插值,这里是噪声插值,生成的插值比例是与随机噪声进行加权相乘计算。本代码这里是固定用数字5作为固定标签,也可以自己改变interpolation_label查看别的标签的结果。
    在这里插入图片描述

下一篇可控制生成GAN。

这篇关于使用pytorch构建有监督的条件GAN(conditional GAN)网络模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/885293

相关文章

python之uv使用详解

《python之uv使用详解》文章介绍uv在Ubuntu上用于Python项目管理,涵盖安装、初始化、依赖管理、运行调试及Docker应用,强调CI中使用--locked确保依赖一致性... 目录安装与更新standalonepip 安装创建php以及初始化项目依赖管理uv run直接在命令行运行pytho

Springboot项目构建时各种依赖详细介绍与依赖关系说明详解

《Springboot项目构建时各种依赖详细介绍与依赖关系说明详解》SpringBoot通过spring-boot-dependencies统一依赖版本管理,spring-boot-starter-w... 目录一、spring-boot-dependencies1.简介2. 内容概览3.核心内容结构4.

C#使用Spire.XLS快速生成多表格Excel文件

《C#使用Spire.XLS快速生成多表格Excel文件》在日常开发中,我们经常需要将业务数据导出为结构清晰的Excel文件,本文将手把手教你使用Spire.XLS这个强大的.NET组件,只需几行C#... 目录一、Spire.XLS核心优势清单1.1 性能碾压:从3秒到0.5秒的质变1.2 批量操作的优雅

Kotlin 枚举类使用举例

《Kotlin枚举类使用举例》枚举类(EnumClasses)是Kotlin中用于定义固定集合值的特殊类,它表示一组命名的常量,每个枚举常量都是该类的单例实例,接下来通过本文给大家介绍Kotl... 目录一、编程枚举类核心概念二、基础语法与特性1. 基本定义2. 带参数的枚举3. 实现接口4. 内置属性三、

Java List 使用举例(从入门到精通)

《JavaList使用举例(从入门到精通)》本文系统讲解JavaList,涵盖基础概念、核心特性、常用实现(如ArrayList、LinkedList)及性能对比,介绍创建、操作、遍历方法,结合实... 目录一、List 基础概念1.1 什么是 List?1.2 List 的核心特性1.3 List 家族成

Go语言使用Gin处理路由参数和查询参数

《Go语言使用Gin处理路由参数和查询参数》在WebAPI开发中,处理路由参数(PathParameter)和查询参数(QueryParameter)是非常常见的需求,下面我们就来看看Go语言... 目录一、路由参数 vs 查询参数二、Gin 获取路由参数和查询参数三、示例代码四、运行与测试1. 测试编程路

Python使用python-pptx自动化操作和生成PPT

《Python使用python-pptx自动化操作和生成PPT》这篇文章主要为大家详细介绍了如何使用python-pptx库实现PPT自动化,并提供实用的代码示例和应用场景,感兴趣的小伙伴可以跟随小编... 目录使用python-pptx操作PPT文档安装python-pptx基础概念创建新的PPT文档查看

C#和Unity中的中介者模式使用方式

《C#和Unity中的中介者模式使用方式》中介者模式通过中介者封装对象交互,降低耦合度,集中控制逻辑,适用于复杂系统组件交互场景,C#中可用事件、委托或MediatR实现,提升可维护性与灵活性... 目录C#中的中介者模式详解一、中介者模式的基本概念1. 定义2. 组成要素3. 模式结构二、中介者模式的特点

MySQL中优化CPU使用的详细指南

《MySQL中优化CPU使用的详细指南》优化MySQL的CPU使用可以显著提高数据库的性能和响应时间,本文为大家整理了一些优化CPU使用的方法,大家可以根据需要进行选择... 目录一、优化查询和索引1.1 优化查询语句1.2 创建和优化索引1.3 避免全表扫描二、调整mysql配置参数2.1 调整线程数2.

C#中SortedSet的具体使用

《C#中SortedSet的具体使用》SortedSet是.NETFramework4.0引入的一个泛型集合类,它实现了一个自动排序的集合,内部使用红黑树数据结构来维护元素的有序性,下面就来介绍一下如... 目录基础概念主要特性创建和初始化基本创建方式自定义比较器基本操作添加和删除元素查询操作范围查询集合运