pytorch生成对抗网络编程:-PyTorch计算机视觉——cWGAN-GP实现可控图像生成 - Adam(G
/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */
#content_views .toc,
/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */
#content_views.markdown_views > p:empty:has(+ .toc),
#content_views.markdown_views > .toc + p:empty,
/* 富文本旧版目录标记 */
#content_views.htmledit_views #main-toc,
#content_views.htmledit_views #hr-toc,
#content_views.htmledit_views p[id*="-toc"] {
display: none !important;
}
/* 目录去掉后,紧跟的首个标题不再多出一块上边距 */
#content_views.markdown_views > .toc + h1,
#content_views.markdown_views > .toc + h2,
#content_views.markdown_views > .toc + h3,
#content_views.markdown_views > .toc + h4,
#content_views.markdown_views > .toc + p:empty + h1,
#content_views.markdown_views > .toc + p:empty + h2,
#content_views.markdown_views > .toc + p:empty + h3,
#content_views.markdown_views > .toc + p:empty + h4 {
margin-top: 0 !important;
}
PyTorch计算机视觉——cWGAN-GP实现可控图像生成
0. 前言1. cWGAN-GP 的核心思想2. 数据集2.1 数据集介绍2.2 数据集加载与预处理
3. 模型架构3.1 条件生成器3.2 条件判别器3.3 梯度惩罚函数
4. 模型训练小结相关链接
0. 前言
我们已经学习了 WGAN-GP (Wasserstein GAN with Gradient Penalty) 在 CelebA 和动漫面孔数据集上的应用,展示了其生成高质量随机图像的能力。然而,在实际应用中,我们往往需要更有针对性的图像生成——例如,我们希望生成特定类别的图像,而不是完全随机的样本。这就引出了条件生成对抗网络 (Conditional GAN, cGAN) 的概念。 本节将详细介绍条件 WGAN-GP (cWGAN-GP) 的实现与应用,以"石头剪刀布"彩色图像数据集为例,展示如何通过引入类别标签信息,实现对生成图像类别的精确控制。
1. cWGAN-GP 的核心思想
传统的 GAN 只能从随机噪声中生成图像,无法控制生成图像的具体类别。cWGAN-GP 通过在生成器和判别器中同时输入类别标签信息,实现了条件生成的能力。cWGAN-GP 的核心创新点包括:
条件嵌入:将类别标签转换为向量表示,与噪声或图像特征进行拼接可控生成:通过指定不同的标签,生成对应类别的图像保持优势:继承了 WGAN-GP 的训练稳定性和高质量生成能力
2. 数据集
2.1 数据集介绍
本节选择使用"石头剪刀布"数据集,主要考虑以下因素:
小型数据集:仅 2520张 图像,适合快速实验和演示三类明确:石头 (rock)、剪刀 (scissors)、布 (paper),类别清晰彩色图像:128x128 分辨率,包含丰富的视觉特征
2.2 数据集加载与预处理
将图像调整为 128x128 像素并进行归一化,确保输入数据在 [-1,1] 范围内,这有利于模型的训练收敛:
import torch; import torch.nn as nn
from torch.utils.data import DataLoader
import torchvision.transforms as T 拼多多帮助力入口
from torchvision.utils import make_grid
from torchvision.datasets import ImageFolder
from tqdm import trange
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
n_epochs = 100
batch_size=32
z_dim = 100
lr = 4e-4
n_critic = 1
lamda_gp = 10
img_size = 128
img_channels = 3
n_class = 3
fixed_latent = torch.randn(48, z_dim).cuda() # noises.shape = 48 x z_dim
fixed_labels = torch.LongTensor([i for i in range(3) for j in range(16)]).cuda()
train_dataset = ImageFolder('./data/RockPaperScissors/train',
transform=T.Compose([T.Resize(img_size),
T.ToTensor(),
T.Normalize([0.5,0.5,0.5], [0.5,0.5,0.5])]))
n_samples = len(train_dataset)
train_dataloader = DataLoader(train_dataset, batch_size=batch_size,
shuffle=True,num_workers=4, pin_memory=True)
n_batch = len(train_dataloader) #n_batch=79
for imgs, labels in train_dataloader:
print("imgs.shape=", imgs.shape)
print('labels=', '\n', labels.view(-1,16))
break
def denorm(img_tensors): # Shift image pixel values to [0,1]
return img_tensors * 0.5 + 0.5
def show_imgs(images):
fig, ax = plt.subplots(figsize=(16,10))
inputs = make_grid(denorm(images), nrow=16)
#inputs = make_grid(images, nrow=16)
ax.imshow(inputs.permute(1,2,0))
ax.set(xticks=[], yticks=[])
plt.show()
show_imgs(imgs)
3. 模型架构
3.1 条件生成器
定义函数 weights_init(),用于模型参数初始化:
def weights_init(m):
if(type(m) == nn.ConvTranspose2d or type(m) == nn.Conv2d):
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif(type(m) == nn.BatchNorm2d):
nn.init.normal_(m.weight.data, 0.0, 0.02)
nn.init.constant_(m.bias.data, 0)
生成器需要接收两个输入,随机噪声向量 z 和类别标签 labels:
# Generator Class
def basic_G(in_channels):
return nn.Sequential(
nn.ConvTranspose2d(in_channels, int(in_channels/2), 4, 2, 1, bias=False),
nn.BatchNorm2d(int(in_channels/2)),
nn.ReLU(True)
)
class Generator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
basic_G(512),
basic_G(256),
basic_G(128),
basic_G(64),
nn.ConvTranspose2d(32, 3, kernel_size=4, stride=2, padding=1),
nn.Tanh()
)
self.label_emb = nn.Embedding(n_class, 4*4)
self.latent = nn.Linear(z_dim, 511*4*4)
def forward(self, z, labels):
y = self.latent(z)
c = self.label_emb(labels)
y_c = torch.cat([y, c], dim=1)
input = y_c.view(-1, 512, 4, 4)
output = self.net(input)
return output
G = Generator().cuda()
G.apply(weights_init)
在以上代码中,使用 nn.Embedding 将类别标签 (0,1,2) 映射为 16 维向量 (4x4),通过 nn.Linear 将 100 维噪声扩展为 8176 维 (511x4x4),将标签嵌入与噪声特征拼接,形成 512x4x4 的初始特征图,通过 5 层转置卷积逐步上采样至 128x128x3。
3.2 条件判别器
判别器同样接收两个输入,图像和对应的标签:
# Discriminator class
def basic_D(in_channels):
return nn.Sequential(
nn.Conv2d(in_channels, 2*in_channels, 4, 2, 1, bias=False),
nn.InstanceNorm2d(2*in_channels),
nn.LeakyReLU(0.2, inplace=True)
)
class Discriminator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(img_channels+1, 64, 4, 2, 1),
nn.LeakyReLU(0.2, inplace=True),
basic_D(64),
basic_D(128),
basic_D(256),
basic_D(512),
nn.Conv2d(1024, 1, kernel_size=4, stride=1, padding=0),
nn.Flatten()
)
self.label_code = nn.Embedding(n_class, 1*img_size*img_size)
def forward(self, images, labels):
x = images.view(-1, img_channels*img_size*img_size)
c = self.label_code(labels)
x_c = torch.cat([x, c], dim=1)
input = x_c.view(-1, img_channels+1, img_size, img_size)
out = self.net(input)
return out
D = Discriminator().cuda()
D.apply(weights_init)
在判别器中,使用 InstanceNorm2d 替代 BatchNorm2d,提高了训练稳定性,通过 nn.Embedding 将标签编码为 16384 维 (128x128) 的向量,将编码后的标签与展平的图像特征拼接,形成 4 通道输入 (RGB + 标签信息)。
3.3 梯度惩罚函数
在 cWGAN-GP 中,梯度惩罚函数需要特别注意标签的使用:
# CGradient-Penalty function
def gradient_penalty(D, real_data, fake_data, fake_labels):
batch_size = real_data.size(0) #real_data.shape = batch_size x 3 x128^2
# Sample Epsilon from uniform distribution
eps = torch.rand(batch_size, 1, 1, 1).cuda()
eps = eps.expand_as(real_data) #eps.shape=batch_size x 3 x 128^2
# Interpolation between real data and fake data.
interpolation = eps * real_data + (1 - eps) * fake_data
# get logits for interpolated images
logits = D(interpolation, fake_labels) #shape = batch_size x 1
gradients = torch.autograd.grad(outputs=logits,
inputs=interpolation,
grad_outputs=torch.ones_like(logits),
create_graph=True,
retain_graph=True
)[0] # Gradients
gradients = gradients.view(batch_size, -1)
grad_norm = gradients.norm(2, 1)
gradient_penalty = torch.mean((grad_norm - 1) ** 2)
return gradient_penalty # Compute and return the gradient norm
在计算梯度惩罚时,必须使用伪造标签而非真实标签。这是因为:
梯度惩罚旨在约束判别器在真实数据分布和生成数据分布之间的行为使用伪造标签更符合实际生成场景实验表明,使用真实标签会导致模型崩溃
4. 模型训练
定义模型优化器:
optimizer_D = torch.optim.Adam(D.parameters(), lr=lr, betas=(0.0, 0.9))
optimizer_G = torch.optim.Adam(G.parameters(), lr=lr, betas=(0.0, 0.9))
定义生成器和判别器训练函数:
def train_D(inputs, labels, optimizer_D):
for _ in range(n_critic):
real_preds = D(inputs, labels)
real_score = torch.mean(real_preds)
# create fake images and labels with random numbers
latent = torch.randn(inputs.shape[0], z_dim).cuda()
fake_labels = torch.LongTensor(
torch.randint(0, n_class, (inputs.shape[0],))).cuda()
fake_images = G(latent, fake_labels)
fake_preds = D(fake_images.detach(), fake_labels.detach())
fake_score = torch.mean(fake_preds)
# Train the optimizer_D with real_loss and fake_loss
gp = gradient_penalty(D, inputs, fake_images, fake_labels)
loss = fake_score - real_score + lamda_gp*gp
optimizer_D.zero_grad()
loss.backward()
optimizer_D.step()
return loss.item(), real_score.item(), fake_score.item()
def train_G(optimizer_G):
# Create fake images and labels
latent = torch.randn(batch_size, z_dim).cuda()
fake_labels = torch.LongTensor(
torch.randint(0, n_class, (batch_size,))).cuda()
fake_images = G(latent, fake_labels)
# Try to fool the discriminator
preds = D(fake_images, fake_labels)
loss = -torch.mean(preds)
optimizer_G.zero_grad()
loss.backward()
optimizer_G.step()
return loss.item()
训练过程的核心是交替更新判别器和生成器:
def fit(epochs):
torch.cuda.empty_cache()
# The DataFrame df is a recorder of the training history
df = pd.DataFrame(np.empty([epochs, 4]),
index = np.arange(epochs),
columns=['Loss_G', 'Loss_D', 'D(X)', 'D(G(Z))'])
for i in trange(epochs):
loss_G = 0.0; loss_D = 0.0; real_sc = 0.0; fake_sc = 0.0
for real_images, labels in train_dataloader:
inputs = real_images.cuda()
labels = labels.cuda()
loss_d, real_score, fake_score = train_D(inputs, labels, optimizer_D)
loss_D += loss_d; real_sc += real_score; fake_sc += fake_score
loss_g = train_G(optimizer_G)
loss_G += loss_g
# Record losses & scores
df.iloc[i, 0] = loss_G/n_batch
df.iloc[i, 1] = loss_D/n_batch
df.iloc[i, 2] = real_sc/n_batch
df.iloc[i, 3] = fake_sc/n_batch
if i==0 or (i+1)%5==0:
print(
"Epoch={:2}, Ls_G={:.2f}, Ls_D={:.2f}, D(X)={:.2f}, D(G(Z))={:.2f}"
.format(i+1, df.iloc[i,0], df.iloc[i,1], df.iloc[i,2], df.iloc[i,3]))
fake_images = G(fixed_latent, fixed_labels)
show_imgs(fake_images.detach().cpu())
return df
history = fit(n_epochs)
查看模型训练过程性能变化曲线:
# Show the training history
df = history
fig, ax = plt.subplots(1,2, figsize=(9,4), sharex=True)
df.plot(ax=ax[0], y=[0,1], style=['r+', 'b:'])
gp = df.iloc[:,1] - df.iloc[:,3] + df.iloc[:,2]
ax[0].plot(gp, label='Gradient Penalty', color='k', linestyle='-')
ax[0].set(ylabel='loss')
ax[0].legend()
df.plot(ax=ax[1], y=[2,3], style=['r-', 'b:'])
for i in range(2):
ax[i].grid(which='major', axis='both', color='g', linestyle=':')
ax[i].set(xlabel='epoch')
plt.show()
通过指定不同的标签,我们可以精确控制生成图像的类别:
def generate_image(G, digital):
z = torch.randn(1, 100).cuda()
N = len(train_dataset.classes)-1
if digital <= N:
label = torch.LongTensor([digital]).cuda()
img = G(z, label).data.cpu()
show_imgs(img)
else:
print("Your label is bigger than ", N)
generate_image(G, 0)
小结
本节详细介绍了 cWGAN-GP 在"石头剪刀布"数据集上的实现与应用,展示了条件 GAN 在可控图像生成方面的强大能力。通过引入类别标签信息,我们能够精确控制生成图像的类别,同时保持了 WGAN-GP 的训练稳定性和高质量生成能力。
相关链接
PyTorch计算机视觉(1)——计算机视觉的数学工具 PyTorch计算机视觉(2)——神经网络模型训练与PyTorch基础 PyTorch计算机视觉(3)——卷积神经网络(CNN)详解与实现 PyTorch计算机视觉(4)——迁移学习(Transfer Learning)详解与实现 PyTorch计算机视觉(5)——生成对抗网络(Generative Adversarial Network,GAN) PyTorch计算机视觉(6)——深度卷积对抗神经网络(DCGAN) PyTorch计算机视觉(7)——条件生成对抗网络(cGAN) PyTorch计算机视觉(8)——WGAN及其变体WGAN-GP,pytorch生成对抗网络编程