G3、CGAN|生成手势图像
- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
- 🚀 文章来源:K同学的学习圈子
本周任务:
📌 基础任务:
- 条件生成对抗网络(CGAN)的基本原理
- 学习本文CGAN代码,并跑通代码
🎈进阶任务:
- 生成指定手势的图像
一、理论基础¶
1、DCGAN原理¶
条件生成对抗网络(CGAN)是在生成对抗网络(GAN)的基础上进行了一些改进。对于原始GAN的生成器而言,其生成的图像数据是随机不可预测的,因此我们无法控制网络的输出,在实际操作中的可控性不强。
针对上述原始GAN无法生成具有特定属性的图像数据的问题,Mehdi Mirza等人在2014年提出了条件生成对抗网络(CGAN),全称为Conditional Generative Adversarial Network。与标准的 GAN 不同,CGAN 通过给定额外的条件信息来控制生成的样本的特征。这个条件信息可以是任何类型的,例如图像标签、文本标签等。
在 CGAN 中,生成器(Generator)和判别器(Discriminator)都接收条件信息。生成器的目标是生成与条件信息相关的合成样本,而判别器的目标是将生成的样本与真实样本区分开来。当生成器和判别器通过反馈循环不断地进行训练时,生成器会逐渐学会如何生成符合条件信息的样本,而判别器则会逐渐变得更加准确。
由上图的网络结构可知,条件信息y作为额外的输入被引入对抗网络中,与生成器中的噪声z合并作为隐含层表达;而在判别器D中,条件信息y则与原始数据x合并作为判别函数的输入。
二、准备工作¶
数据:百度网盘
1、导入包¶
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
from torchvision.utils import save_image
from torchvision.utils import make_grid
from torch.utils.tensorboard import SummaryWriter
from torchsummary import summary
import matplotlib.pyplot as plt
2、设置超参数¶
dataroot = "./data/GAN-3-day-rps/" # 数据路径
batch_size = 128 # 训练过程中的批次大小
image_size = 128 # 图像的尺寸(宽度和高度)
image_shape = (3, 128, 128)
image_dim = int(np.prod(image_shape))
latent_dim = 100
n_classes = 3 # 条件标签的总数
embedding_dim = 100
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
3、导入数据¶
- 首先使用ImageFolder类创建一个数据集对象,该对象表示从文件夹中加载的图像数据集
- 然后,通过transforms.Compose组合了一系列图像变换操作来对图像进行预处理,包括调整大小、中心裁剪、转换为张量以及标准化
- 接着,使用DataLoader类创建一个数据加载器对象,该对象可以在训练过程中按批次加载数据,并可以选择是否打乱数据集以及使用多线程加载数据。代码还选择设备(GPU或CPU)来运行代码,并显示所选择的设备
- 最后,代码通过数据加载器获取一批训练图像,并使用Matplotlib库绘制这些图像
解决一个小问题,关于路径图像读取的,图像实际的目录为./data/GAN-Data/FaceSample,而将数据集路径定为上一级目录 "./data/GAN-Data",是因为PyTorch支持自动扫描指定目录下的所有子目录,以发现数据集文件。使用 torchvision.datasets.ImageFolder 类来读取数据集。此时,你只需要将数据集路径定为 "./data/GAN-Data" 即可,因为 ImageFolder 类会自动扫描该目录下的所有子目录,以发现数据集文件。如果目录下有多个不同的文件夹,ImageFolder 类会将每个文件夹名作为一个标签类别,并将文件夹中的所有图像文件都视为该类别下的样本。如果数据集目录 "./data/GAN-Data",其中包含三个子目录 "cats"、"dogs" 和 "pandas",每个子目录下都包含对应的图像文件。ImageFolder 类将读取 "./data/GAN-Data" 目录下的所有子目录,并将每个子目录名作为一个标签类别。
# 创建数据集
train_dataset = datasets.ImageFolder(root=dataroot,
transform=transforms.Compose([
transforms.Resize(image_size), # 调整图像大小
transforms.ToTensor(), # 将图像转换为张量
transforms.Normalize((0.5, 0.5, 0.5), # 标准化图像张量
(0.5, 0.5, 0.5)),
]))
# 创建数据加载器
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size, # 批量大小
shuffle=True, # 是否打乱数据集
num_workers=6 # 使用多个线程加载数据的工作进程数
)
4、数据可视化¶
def show_images(images):
fig, ax = plt.subplots(figsize=(20, 20))
ax.set_xticks([]); ax.set_yticks([])
ax.imshow(make_grid(images.detach(), nrow=22).permute(1, 2, 0))
def show_batch(dl):
for images, _ in dl:
show_images(images)
break
show_batch(train_loader)
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
# 自定义权重初始化函数,用于初始化生成器和判别器的权重
def weights_init(m):
# 获取当前层的类名
classname = m.__class__.__name__
# 如果当前层是卷积层(类名中包含 'Conv' )
if classname.find('Conv') != -1:
# 使用正态分布随机初始化权重,均值为0,标准差为0.02
torch.nn.init.normal_(m.weight, 0.0, 0.02)
# 如果当前层是批归一化层(类名中包含 'BatchNorm' )
elif classname.find('BatchNorm') != -1:
# 使用正态分布随机初始化权重,均值为1,标准差为0.02
torch.nn.init.normal_(m.weight, 1.0, 0.02)
# 将偏置项初始化为全零
torch.nn.init.zeros_(m.bias)
2、定义生成器¶
- label_conditioned_generator:Sequential 模型,用于将条件标签映射到嵌入空间中
nn.Embedding 用于将条件标签映射为稠密向量,nn.Linear 用于将稠密向量转换为更高维度
- latent: Sequential 模型,用于将噪声向量映射到图像空间中
nn.Linear 用于将潜在向量转换为更高维度,nn.LeakyReLU 用于进行非线性映射
- model: Sequential 模型,用于将条件标签和潜在向量合并成生成的图像
nn.ConvTranspose2d 表示反卷积操作,用于将特征图映射为图像。nn.BatchNorm2d 表示批标准化,用于提高模型的稳定性和收敛速度。nn.ReLU 表示 ReLU 激活函数,用于进行非线性映射。nn.Tanh 表示 Tanh 激活函数,用于将生成的图像像素值映射到 [-1, 1] 范围内
- forward 方法,用于前向传播计算
inputs 是一个元组,包含两个张量:noise_vector 表示噪声向量,label 表示条件标签。在 forward 方法中,先通过 label_conditioned_generator 将 label 映射为嵌入向量,再通过 latent 将 noise_vector 映射为潜在向量。然后,将嵌入向量和潜在向量在通道维度上进行合并,得到合并后的特征图。最后,通过 model 将特征图生成为 RGB 图像
- 将生成器模型实例化为 generator,并对其权重进行初始化
weights_init 是一个函数,用于初始化模型权重
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
# 定义条件标签的生成器部分,用于将标签映射到嵌入空间中
# n_classes:条件标签的总数
# embedding_dim:嵌入空间的维度
self.label_conditioned_generator = nn.Sequential(
nn.Embedding(n_classes, embedding_dim), # 使用Embedding层将条件标签映射为稠密向量
nn.Linear(embedding_dim, 16) # 使用线性层将稠密向量转换为更高维度
)
# 定义潜在向量的生成器部分,用于将噪声向量映射到图像空间中
# latent_dim:潜在向量的维度
self.latent = nn.Sequential(
nn.Linear(latent_dim, 4*4*512), # 使用线性层将潜在向量转换为更高维度
nn.LeakyReLU(0.2, inplace=True) # 使用LeakyReLU激活函数进行非线性映射
)
# 定义生成器的主要结构,将条件标签和潜在向量合并成生成的图像
self.model = nn.Sequential(
# 反卷积层1:将合并后的向量映射为64x8x8的特征图
nn.ConvTranspose2d(513, 64*8, 4, 2, 1, bias=False),
nn.BatchNorm2d(64*8, momentum=0.1, eps=0.8), # 批标准化
nn.ReLU(True), # ReLU激活函数
# 反卷积层2:将64x8x8的特征图映射为64x4x4的特征图
nn.ConvTranspose2d(64*8, 64*4, 4, 2, 1, bias=False),
nn.BatchNorm2d(64*4, momentum=0.1, eps=0.8),
nn.ReLU(True),
# 反卷积层3:将64x4x4的特征图映射为64x2x2的特征图
nn.ConvTranspose2d(64*4, 64*2, 4, 2, 1, bias=False),
nn.BatchNorm2d(64*2, momentum=0.1, eps=0.8),
nn.ReLU(True),
# 反卷积层4:将64x2x2的特征图映射为64x1x1的特征图
nn.ConvTranspose2d(64*2, 64*1, 4, 2, 1, bias=False),
nn.BatchNorm2d(64*1, momentum=0.1, eps=0.8),
nn.ReLU(True),
# 反卷积层5:将64x1x1的特征图映射为3x64x64的RGB图像
nn.ConvTranspose2d(64*1, 3, 4, 2, 1, bias=False),
nn.Tanh() # 使用Tanh激活函数将生成的图像像素值映射到[-1, 1]范围内
)
def forward(self, inputs):
noise_vector, label = inputs
# 通过条件标签生成器将标签映射为嵌入向量
label_output = self.label_conditioned_generator(label)
# 将嵌入向量的形状变为(batch_size, 1, 4, 4),以便与潜在向量进行合并
label_output = label_output.view(-1, 1, 4, 4)
# 通过潜在向量生成器将噪声向量映射为潜在向量
latent_output = self.latent(noise_vector)
# 将潜在向量的形状变为(batch_size, 512, 4, 4),以便与条件标签进行合并
latent_output = latent_output.view(-1, 512, 4, 4)
# 将条件标签和潜在向量在通道维度上进行合并,得到合并后的特征图
concat = torch.cat((latent_output, label_output), dim=1)
# 通过生成器的主要结构将合并后的特征图生成为RGB图像
image = self.model(concat)
return image
generator = Generator().to(device)
generator.apply(weights_init)
print(generator)
Generator(
(label_conditioned_generator): Sequential(
(0): Embedding(3, 100)
(1): Linear(in_features=100, out_features=16, bias=True)
)
(latent): Sequential(
(0): Linear(in_features=100, out_features=8192, bias=True)
(1): LeakyReLU(negative_slope=0.2, inplace=True)
)
(model): Sequential(
(0): ConvTranspose2d(513, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): BatchNorm2d(512, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU(inplace=True)
(3): ConvTranspose2d(512, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(4): BatchNorm2d(256, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(5): ReLU(inplace=True)
(6): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(7): BatchNorm2d(128, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(8): ReLU(inplace=True)
(9): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(10): BatchNorm2d(64, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(11): ReLU(inplace=True)
(12): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(13): Tanh()
)
)
查看模型参数
from torchinfo import summary
summary(generator)
a = torch.ones(100)
b = torch.ones(1)
b = b.long()
a = a.to(device)
b = b.to(device)
=================================================================
Layer (type:depth-idx) Param #
=================================================================
Generator --
├─Sequential: 1-1 --
│ └─Embedding: 2-1 300
│ └─Linear: 2-2 1,616
├─Sequential: 1-2 --
│ └─Linear: 2-3 827,392
│ └─LeakyReLU: 2-4 --
├─Sequential: 1-3 --
│ └─ConvTranspose2d: 2-5 4,202,496
│ └─BatchNorm2d: 2-6 1,024
│ └─ReLU: 2-7 --
│ └─ConvTranspose2d: 2-8 2,097,152
│ └─BatchNorm2d: 2-9 512
│ └─ReLU: 2-10 --
│ └─ConvTranspose2d: 2-11 524,288
│ └─BatchNorm2d: 2-12 256
│ └─ReLU: 2-13 --
│ └─ConvTranspose2d: 2-14 131,072
│ └─BatchNorm2d: 2-15 128
│ └─ReLU: 2-16 --
│ └─ConvTranspose2d: 2-17 3,072
│ └─Tanh: 2-18 --
=================================================================
Total params: 7,789,308
Trainable params: 7,789,308
Non-trainable params: 0
=================================================================
# 定义了两个张量 a 和 b,分别表示噪声向量和条件标签
# 其中,a 的形状为 (100,),b 的形状为 (1,)
# 由于生成器模型需要的条件标签是一个整数,因此需要将 b 的数据类型转换为 long
# 最后,将 a 和 b 分别转移到 GPU 上,以便在 GPU 上进行模型计算
a = torch.ones(100)
b = torch.ones(1)
b = b.long()
a = a.to(device)
b = b.to(device)
generator((a,b))
tensor([[[[ 2.7624e-05, -1.1925e-03, 7.8016e-04, ..., -1.6086e-05,
2.3425e-03, -7.8962e-04],
[-1.1563e-03, -3.3760e-03, -5.5881e-03, ..., 6.3103e-03,
-1.8744e-03, -4.0363e-04],
[ 1.2206e-03, -5.0634e-03, 3.9738e-03, ..., -2.4712e-03,
3.9208e-03, -1.9221e-03],
...,
[-1.3548e-03, 9.6281e-04, -1.4134e-03, ..., 2.2500e-03,
2.9837e-04, 2.5448e-04],
[ 3.8311e-03, -2.6578e-03, 3.1358e-03, ..., -2.2440e-03,
3.0415e-03, -2.5750e-03],
[-8.3919e-04, 1.9576e-03, -3.4348e-04, ..., 2.4164e-04,
-4.5968e-04, 7.8597e-04]],
[[ 1.9212e-03, 2.7891e-03, -4.4548e-04, ..., 3.8793e-03,
1.2622e-03, -2.0034e-03],
[-2.7110e-05, -4.3667e-03, 2.9475e-03, ..., -4.8076e-03,
1.4988e-03, -1.0174e-05],
[-1.1267e-03, 1.5863e-03, 1.3231e-03, ..., 4.2248e-03,
-1.9428e-03, 7.9145e-04],
...,
[ 1.5216e-03, -4.3259e-03, -9.8797e-04, ..., -2.3144e-03,
1.6633e-03, 6.2363e-04],
[-2.1298e-03, -1.5092e-03, -7.1997e-05, ..., 5.0918e-03,
-1.0543e-03, -4.1783e-04],
[ 4.0840e-04, 6.2414e-04, 1.0283e-03, ..., -1.5465e-03,
1.4416e-03, 6.6619e-04]],
[[ 1.3126e-03, 1.7071e-03, -2.4759e-03, ..., 2.8572e-03,
-3.5860e-04, 5.8868e-04],
[-3.8275e-03, 2.5726e-03, -5.9551e-04, ..., -9.9753e-04,
3.2158e-04, -4.5780e-03],
[ 1.2700e-03, 9.3941e-04, -4.5517e-03, ..., 5.1489e-03,
6.3615e-04, -2.2956e-03],
...,
[-2.7524e-03, 3.8852e-04, 1.1874e-03, ..., 9.6853e-04,
-4.6598e-03, -3.1849e-03],
[-6.3093e-04, 1.2432e-03, -4.5319e-04, ..., 1.5603e-03,
-4.5440e-04, -1.0476e-03],
[-2.4878e-03, 4.9482e-04, -3.5592e-03, ..., -1.5734e-03,
-3.6502e-03, -1.9177e-04]]]], device='cuda:0',
grad_fn=<TanhBackward0>)
3、定义鉴别器¶
- label_condition_disc:条件标签的嵌入层,用于将类别标签转换为特征向量
这个嵌入层由两个层组成:一个嵌入层(Embedding)和一个线性层(Linear)。嵌入层将类别标签编码为固定长度的向量,线性层将嵌入的向量转换为与图像尺寸相匹配的特征张量。
- model:Sequential 模型
由多个卷积层、批量归一化层、激活函数层、展平层、随机失活层和全连接层组成。这些层将特征图逐渐变小,最后输出一个维度为1的概率值,表示输入的图像是真实的还是伪造的
- forward方法中,接受了一个inputs参数,其中包含了图像和标签两个部分
首先将标签通过条件标签的嵌入层转换为特征向量,然后通过重塑操作将特征向量转换为与图像尺寸相匹配的特征张量
接下来将图像和标签特征拼接在一起作为鉴别器的输入,通过鉴别器模型进行前向传播,得到输出结果
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
# 定义一个条件标签的嵌入层,用于将类别标签转换为特征向量
self.label_condition_disc = nn.Sequential(
nn.Embedding(n_classes, embedding_dim), # 嵌入层将类别标签编码为固定长度的向量
nn.Linear(embedding_dim, 3*128*128) # 线性层将嵌入的向量转换为与图像尺寸相匹配的特征张量
)
# 定义主要的鉴别器模型
self.model = nn.Sequential(
nn.Conv2d(6, 64, 4, 2, 1, bias=False), # 输入通道为6(包含图像和标签的通道数),输出通道为64,4x4的卷积核,步长为2,padding为1
nn.LeakyReLU(0.2, inplace=True), # LeakyReLU激活函数,带有负斜率,增加模型对输入中的负值的感知能力
nn.Conv2d(64, 64*2, 4, 3, 2, bias=False), # 输入通道为64,输出通道为64*2,4x4的卷积核,步长为3,padding为2
nn.BatchNorm2d(64*2, momentum=0.1, eps=0.8), # 批量归一化层,有利于训练稳定性和收敛速度
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(64*2, 64*4, 4, 3, 2, bias=False), # 输入通道为64*2,输出通道为64*4,4x4的卷积核,步长为3,padding为2
nn.BatchNorm2d(64*4, momentum=0.1, eps=0.8),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(64*4, 64*8, 4, 3, 2, bias=False), # 输入通道为64*4,输出通道为64*8,4x4的卷积核,步长为3,padding为2
nn.BatchNorm2d(64*8, momentum=0.1, eps=0.8),
nn.LeakyReLU(0.2, inplace=True),
nn.Flatten(), # 将特征图展平为一维向量,用于后续全连接层处理
nn.Dropout(0.4), # 随机失活层,用于减少过拟合风险
nn.Linear(4608, 1), # 全连接层,将特征向量映射到输出维度为1的向量
nn.Sigmoid() # Sigmoid激活函数,用于输出范围限制在0到1之间的概率值
)
def forward(self, inputs):
img, label = inputs
# 将类别标签转换为特征向量
label_output = self.label_condition_disc(label)
# 重塑特征向量为与图像尺寸相匹配的特征张量
label_output = label_output.view(-1, 3, 128, 128)
# 将图像特征和标签特征拼接在一起作为鉴别器的输入
concat = torch.cat((img, label_output), dim=1)
# 将拼接后的输入通过鉴别器模型进行前向传播,得到输出结果
output = self.model(concat)
return output
discriminator = Discriminator().to(device)
discriminator.apply(weights_init)
print(discriminator)
Discriminator(
(label_condition_disc): Sequential(
(0): Embedding(3, 100)
(1): Linear(in_features=100, out_features=49152, bias=True)
)
(model): Sequential(
(0): Conv2d(6, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): LeakyReLU(negative_slope=0.2, inplace=True)
(2): Conv2d(64, 128, kernel_size=(4, 4), stride=(3, 3), padding=(2, 2), bias=False)
(3): BatchNorm2d(128, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(4): LeakyReLU(negative_slope=0.2, inplace=True)
(5): Conv2d(128, 256, kernel_size=(4, 4), stride=(3, 3), padding=(2, 2), bias=False)
(6): BatchNorm2d(256, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(7): LeakyReLU(negative_slope=0.2, inplace=True)
(8): Conv2d(256, 512, kernel_size=(4, 4), stride=(3, 3), padding=(2, 2), bias=False)
(9): BatchNorm2d(512, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(10): LeakyReLU(negative_slope=0.2, inplace=True)
(11): Flatten(start_dim=1, end_dim=-1)
(12): Dropout(p=0.4, inplace=False)
(13): Linear(in_features=4608, out_features=1, bias=True)
(14): Sigmoid()
)
)
查看模型参数
summary(discriminator)
=================================================================
Layer (type:depth-idx) Param #
=================================================================
Discriminator --
├─Sequential: 1-1 --
│ └─Embedding: 2-1 300
│ └─Linear: 2-2 4,964,352
├─Sequential: 1-2 --
│ └─Conv2d: 2-3 6,144
│ └─LeakyReLU: 2-4 --
│ └─Conv2d: 2-5 131,072
│ └─BatchNorm2d: 2-6 256
│ └─LeakyReLU: 2-7 --
│ └─Conv2d: 2-8 524,288
│ └─BatchNorm2d: 2-9 512
│ └─LeakyReLU: 2-10 --
│ └─Conv2d: 2-11 2,097,152
│ └─BatchNorm2d: 2-12 1,024
│ └─LeakyReLU: 2-13 --
│ └─Flatten: 2-14 --
│ └─Dropout: 2-15 --
│ └─Linear: 2-16 4,609
│ └─Sigmoid: 2-17 --
=================================================================
Total params: 7,729,709
Trainable params: 7,729,709
Non-trainable params: 0
=================================================================
a = torch.ones(2,3,128,128) # 创建大小为2x3x128x128的张量a,元素值都为1
b = torch.ones(2,1) # 创建大小为2x1的张量b,元素值都为1
b = b.long() # 将张量b的数据类型转换为long型
a = a.to(device) # 将张量a移动到指定的设备上
b = b.to(device) # 将张量b移动到指定的设备上
c = discriminator((a,b)) # 对a和b进行前向传播,得到输出结果
c.size() # 打印输出结果c的大小
torch.Size([2, 1])
adversarial_loss = nn.BCELoss()
def generator_loss(fake_output, label):
gen_loss = adversarial_loss(fake_output, label)
return gen_loss
def discriminator_loss(output, label):
disc_loss = adversarial_loss(output, label)
return disc_loss
2、定义优化器¶
learning_rate = 0.0002
G_optimizer = optim.Adam(generator.parameters(), lr = learning_rate, betas=(0.5, 0.999))
D_optimizer = optim.Adam(discriminator.parameters(), lr = learning_rate, betas=(0.5, 0.999))
3、训练模型¶
这段代码是用于训练GAN模型生成图像的
- 首先设置了训练的总轮数和用于存储每轮训练中判别器和生成器损失的列表
- 然后进行GAN模型的训练。在每轮训练中,它首先从数据加载器中加载真实图像和标签,然后计算判别器对真实图像的损失,接着从噪声向量中生成假图像,计算判别器对假图像的损失,计算判别器总体损失并反向传播更新判别器的参数,然后计算生成器的损失并反向传播更新生成器的参数
- 最后,它打印当前轮次的判别器和生成器的平均损失,并将当前轮次的判别器和生成器的平均损失保存到列表中
- 在每10轮训练后,它会将生成的假图像保存为图片文件,并将当前轮次的生成器和判别器的权重保存到文件
# 设置训练的总轮数
num_epochs = 100
# 初始化用于存储每轮训练中判别器和生成器损失的列表
D_loss_plot, G_loss_plot = [], []
# 循环进行训练
for epoch in range(1, num_epochs + 1):
# 初始化每轮训练中判别器和生成器损失的临时列表
D_loss_list, G_loss_list = [], []
# 遍历训练数据加载器中的数据
for index, (real_images, labels) in enumerate(train_loader):
# 清空判别器的梯度缓存
D_optimizer.zero_grad()
# 将真实图像数据和标签转移到GPU(如果可用)
real_images = real_images.to(device)
labels = labels.to(device)
# 将标签的形状从一维向量转换为二维张量(用于后续计算)
labels = labels.unsqueeze(1).long()
# 创建真实目标和虚假目标的张量(用于判别器损失函数)
real_target = Variable(torch.ones(real_images.size(0), 1).to(device))
fake_target = Variable(torch.zeros(real_images.size(0), 1).to(device))
# 计算判别器对真实图像的损失
D_real_loss = discriminator_loss(discriminator((real_images, labels)), real_target)
# 从噪声向量中生成假图像(生成器的输入)
noise_vector = torch.randn(real_images.size(0), latent_dim, device=device)
noise_vector = noise_vector.to(device)
generated_image = generator((noise_vector, labels))
# 计算判别器对假图像的损失(注意detach()函数用于分离生成器梯度计算图)
output = discriminator((generated_image.detach(), labels))
D_fake_loss = discriminator_loss(output, fake_target)
# 计算判别器总体损失(真实图像损失和假图像损失的平均值)
D_total_loss = (D_real_loss + D_fake_loss) / 2
D_loss_list.append(D_total_loss)
# 反向传播更新判别器的参数
D_total_loss.backward()
D_optimizer.step()
# 清空生成器的梯度缓存
G_optimizer.zero_grad()
# 计算生成器的损失
G_loss = generator_loss(discriminator((generated_image, labels)), real_target)
G_loss_list.append(G_loss)
# 反向传播更新生成器的参数
G_loss.backward()
G_optimizer.step()
# 打印当前轮次的判别器和生成器的平均损失
print('Epoch: [%d/%d]: D_loss: %.3f, G_loss: %.3f' % (
(epoch), num_epochs, torch.mean(torch.FloatTensor(D_loss_list)),
torch.mean(torch.FloatTensor(G_loss_list))))
# 将当前轮次的判别器和生成器的平均损失保存到列表中
D_loss_plot.append(torch.mean(torch.FloatTensor(D_loss_list)))
G_loss_plot.append(torch.mean(torch.FloatTensor(G_loss_list)))
if epoch%10 == 0:
# 将生成的假图像保存为图片文件
save_image(generated_image.data[:50], './data/images_GAN3/sample_%d' % epoch + '.png', nrow=5, normalize=True)
# 将当前轮次的生成器和判别器的权重保存到文件
torch.save(generator.state_dict(), './training_weights/generator_epoch_%d.pth' % (epoch))
torch.save(discriminator.state_dict(), './training_weights/discriminator_epoch_%d.pth' % (epoch))
Epoch: [1/100]: D_loss: 0.401, G_loss: 2.179
Epoch: [2/100]: D_loss: 0.367, G_loss: 2.050
Epoch: [3/100]: D_loss: 0.411, G_loss: 2.037
Epoch: [4/100]: D_loss: 0.407, G_loss: 1.826
Epoch: [5/100]: D_loss: 0.432, G_loss: 1.740
Epoch: [6/100]: D_loss: 0.443, G_loss: 1.668
Epoch: [7/100]: D_loss: 0.421, G_loss: 1.591
Epoch: [8/100]: D_loss: 0.401, G_loss: 1.553
Epoch: [9/100]: D_loss: 0.431, G_loss: 1.605
Epoch: [10/100]: D_loss: 0.435, G_loss: 1.674
Epoch: [11/100]: D_loss: 0.453, G_loss: 1.723
Epoch: [12/100]: D_loss: 0.459, G_loss: 1.686
Epoch: [13/100]: D_loss: 0.408, G_loss: 1.667
Epoch: [14/100]: D_loss: 0.373, G_loss: 1.612
Epoch: [15/100]: D_loss: 0.406, G_loss: 1.739
Epoch: [16/100]: D_loss: 0.475, G_loss: 1.889
Epoch: [17/100]: D_loss: 0.398, G_loss: 1.796
Epoch: [18/100]: D_loss: 0.378, G_loss: 1.744
Epoch: [19/100]: D_loss: 0.406, G_loss: 1.861
Epoch: [20/100]: D_loss: 0.419, G_loss: 1.829
Epoch: [21/100]: D_loss: 0.407, G_loss: 1.813
Epoch: [22/100]: D_loss: 0.376, G_loss: 1.775
Epoch: [23/100]: D_loss: 0.595, G_loss: 2.176
Epoch: [24/100]: D_loss: 0.342, G_loss: 1.947
Epoch: [25/100]: D_loss: 0.348, G_loss: 1.732
Epoch: [26/100]: D_loss: 0.373, G_loss: 1.897
Epoch: [27/100]: D_loss: 0.360, G_loss: 1.795
Epoch: [28/100]: D_loss: 0.365, G_loss: 1.872
Epoch: [29/100]: D_loss: 0.427, G_loss: 2.017
Epoch: [30/100]: D_loss: 0.366, G_loss: 1.855
Epoch: [31/100]: D_loss: 0.404, G_loss: 2.032
Epoch: [32/100]: D_loss: 0.423, G_loss: 2.034
Epoch: [33/100]: D_loss: 0.339, G_loss: 1.900
Epoch: [34/100]: D_loss: 0.417, G_loss: 2.068
Epoch: [35/100]: D_loss: 0.318, G_loss: 1.949
Epoch: [36/100]: D_loss: 0.432, G_loss: 2.065
Epoch: [37/100]: D_loss: 0.423, G_loss: 2.067
Epoch: [38/100]: D_loss: 0.312, G_loss: 1.968
Epoch: [39/100]: D_loss: 0.312, G_loss: 2.051
Epoch: [40/100]: D_loss: 0.320, G_loss: 2.151
Epoch: [41/100]: D_loss: 0.339, G_loss: 2.034
Epoch: [42/100]: D_loss: 0.349, G_loss: 2.154
Epoch: [43/100]: D_loss: 0.316, G_loss: 2.187
Epoch: [44/100]: D_loss: 0.386, G_loss: 2.270
Epoch: [45/100]: D_loss: 0.310, G_loss: 2.159
Epoch: [46/100]: D_loss: 0.318, G_loss: 2.180
Epoch: [47/100]: D_loss: 0.373, G_loss: 2.332
Epoch: [48/100]: D_loss: 0.336, G_loss: 2.307
Epoch: [49/100]: D_loss: 0.268, G_loss: 2.253
Epoch: [50/100]: D_loss: 0.300, G_loss: 2.323
Epoch: [51/100]: D_loss: 0.340, G_loss: 2.352
Epoch: [52/100]: D_loss: 0.331, G_loss: 2.408
Epoch: [53/100]: D_loss: 0.419, G_loss: 2.601
Epoch: [54/100]: D_loss: 0.524, G_loss: 2.278
Epoch: [55/100]: D_loss: 0.261, G_loss: 2.214
Epoch: [56/100]: D_loss: 0.260, G_loss: 2.342
Epoch: [57/100]: D_loss: 0.266, G_loss: 2.379
Epoch: [58/100]: D_loss: 0.278, G_loss: 2.412
Epoch: [59/100]: D_loss: 0.259, G_loss: 2.447
Epoch: [60/100]: D_loss: 0.362, G_loss: 2.596
Epoch: [61/100]: D_loss: 0.262, G_loss: 2.365
Epoch: [62/100]: D_loss: 0.257, G_loss: 2.484
Epoch: [63/100]: D_loss: 0.249, G_loss: 2.525
Epoch: [64/100]: D_loss: 0.248, G_loss: 2.539
Epoch: [65/100]: D_loss: 0.344, G_loss: 2.712
Epoch: [66/100]: D_loss: 0.368, G_loss: 2.565
Epoch: [67/100]: D_loss: 0.291, G_loss: 2.586
Epoch: [68/100]: D_loss: 0.254, G_loss: 2.640
Epoch: [69/100]: D_loss: 0.218, G_loss: 2.662
Epoch: [70/100]: D_loss: 0.229, G_loss: 2.647
Epoch: [71/100]: D_loss: 0.329, G_loss: 2.722
Epoch: [72/100]: D_loss: 0.312, G_loss: 2.775
Epoch: [73/100]: D_loss: 0.253, G_loss: 2.646
Epoch: [74/100]: D_loss: 0.277, G_loss: 2.738
Epoch: [75/100]: D_loss: 0.269, G_loss: 2.748
Epoch: [76/100]: D_loss: 0.262, G_loss: 2.872
Epoch: [77/100]: D_loss: 0.227, G_loss: 2.795
Epoch: [78/100]: D_loss: 0.330, G_loss: 2.854
Epoch: [79/100]: D_loss: 0.324, G_loss: 2.739
Epoch: [80/100]: D_loss: 0.220, G_loss: 2.787
Epoch: [81/100]: D_loss: 0.285, G_loss: 2.818
Epoch: [82/100]: D_loss: 0.272, G_loss: 2.925
Epoch: [83/100]: D_loss: 0.224, G_loss: 2.778
Epoch: [84/100]: D_loss: 0.206, G_loss: 2.909
Epoch: [85/100]: D_loss: 0.305, G_loss: 2.941
Epoch: [86/100]: D_loss: 0.248, G_loss: 2.933
Epoch: [87/100]: D_loss: 0.228, G_loss: 2.928
Epoch: [88/100]: D_loss: 0.204, G_loss: 2.947
Epoch: [89/100]: D_loss: 0.204, G_loss: 2.987
Epoch: [90/100]: D_loss: 0.278, G_loss: 3.057
Epoch: [91/100]: D_loss: 0.245, G_loss: 3.064
Epoch: [92/100]: D_loss: 0.260, G_loss: 2.959
Epoch: [93/100]: D_loss: 0.242, G_loss: 3.050
Epoch: [94/100]: D_loss: 0.183, G_loss: 3.086
Epoch: [95/100]: D_loss: 0.205, G_loss: 3.144
Epoch: [96/100]: D_loss: 0.241, G_loss: 3.200
Epoch: [97/100]: D_loss: 0.866, G_loss: 3.776
Epoch: [98/100]: D_loss: 0.844, G_loss: 2.616
Epoch: [99/100]: D_loss: 0.293, G_loss: 2.499
Epoch: [100/100]: D_loss: 0.232, G_loss: 2.643
3、可视化¶
- 训练过程loss可视化
plt.figure(figsize=(10,5))
plt.title("Generator and Discriminator Loss During Training")
plt.plot(G_loss_plot,label="G")
plt.plot(D_loss_plot,label="D")
plt.xlabel("iterations")
plt.ylabel("Loss")
plt.legend()
plt.show()
generator.load_state_dict(torch.load('./training_weights/generator_epoch_100.pth'), strict=False)
generator.eval()
Generator(
(label_conditioned_generator): Sequential(
(0): Embedding(3, 100)
(1): Linear(in_features=100, out_features=16, bias=True)
)
(latent): Sequential(
(0): Linear(in_features=100, out_features=8192, bias=True)
(1): LeakyReLU(negative_slope=0.2, inplace=True)
)
(model): Sequential(
(0): ConvTranspose2d(513, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): BatchNorm2d(512, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU(inplace=True)
(3): ConvTranspose2d(512, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(4): BatchNorm2d(256, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(5): ReLU(inplace=True)
(6): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(7): BatchNorm2d(128, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(8): ReLU(inplace=True)
(9): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(10): BatchNorm2d(64, eps=0.8, momentum=0.1, affine=True, track_running_stats=True)
(11): ReLU(inplace=True)
(12): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(13): Tanh()
)
)
# 导入所需的库
from numpy import asarray
from numpy.random import randn
from numpy.random import randint
from numpy import linspace
from matplotlib import pyplot
from matplotlib import gridspec
# 生成潜在空间的点,作为生成器的输入
def generate_latent_points(latent_dim, n_samples, n_classes=3):
# 从标准正态分布中生成潜在空间的点
x_input = randn(latent_dim * n_samples)
# 将生成的点整形成用于神经网络的输入的批量
z_input = x_input.reshape(n_samples, latent_dim)
return z_input
# 在两个潜在空间点之间进行均匀插值
def interpolate_points(p1, p2, n_steps=10):
# 在两个点之间进行插值,生成插值比率
ratios = linspace(0, 1, num=n_steps)
# 线性插值向量
vectors = list()
for ratio in ratios:
v = (1.0 - ratio) * p1 + ratio * p2
vectors.append(v)
return asarray(vectors)
# 生成两个潜在空间的点
pts = generate_latent_points(100, 2)
# 在两个潜在空间点之间进行插值
interpolated = interpolate_points(pts[0], pts[1])
# 将数据转换为torch张量并将其移至GPU(假设device已正确声明为GPU)
interpolated = torch.tensor(interpolated).to(device).type(torch.float32)
output = None
# 对于三个类别的循环,分别进行插值和生成图片
for label in range(3):
# 创建包含相同类别标签的张量
labels = torch.ones(10) * label
labels = labels.to(device)
labels = labels.unsqueeze(1).long()
print(labels.size())
# 使用生成器生成插值结果
predictions = generator((interpolated, labels))
predictions = predictions.permute(0,2,3,1)
pred = predictions.detach().cpu()
if output is None:
output = pred
else:
output = np.concatenate((output,pred))
torch.Size([10, 1])
torch.Size([10, 1])
torch.Size([10, 1])
output.shape
(30, 128, 128, 3)
nrow = 3
ncol = 10
fig = plt.figure(figsize=(15,4))
gs = gridspec.GridSpec(nrow, ncol)
k = 0
for i in range(nrow):
for j in range(ncol):
pred = (output[k, :, :, :] + 1 ) * 127.5
pred = np.array(pred)
ax= plt.subplot(gs[i,j])
ax.imshow(pred.astype(np.uint8))
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.axis('off')
k += 1
plt.show()