本文为365天深度学习训练营 中的学习记录博客
原作者:K同学啊
可参考论文:《Semi-Supervised Learning with Generative Adversarial Networks》
在学习GAN的时候有没有想过这样一个问题呢,如果我们生成的图像是带有标签的,例如数字 0 ~ 9,那为什么要鉴别器判断输入图像为真假,而不直接判断图像是 0 ~ 9 中的哪一个数字呢,这样的鉴别效果不是更好吗?现在要讲解的SGAN将解答这个疑惑。
一、理论知识讲解
该算法将产生式对抗网络(GAN)拓展到半监督学习,通过强制判别器D来输出类别标签。我们在一个数据集上训练一个生成器G 以及 一个判别器D,输入是N类当中的一个。在训练的时候,判别器D被用于预测输入是属于 N+1类中的哪一个,这个 N+1 是对应了生成器G的输出,这里的判别器D同时也充当起了分类器C的效果。这种方法可以用于训练效果更好的判别器D,并且可以比普通的GAN 产生更加高质量的样本。Semi-Supervised GAN有如下优点:
●1. 作者对GANs做了一个新的扩展,允许它同时学习一个生成模型和一个分类器。我们把这个扩展叫做半监督GAN或SGAN。
●2. 论文实验结果表明,SGAN在有限数据集上比没有生成部分的基准分类器提升了分类性能。
●3. 论文实验结果表明,SGAN可以显著地提升生成样本的质量并降低生成器的训练时间。
通过生成的效果图可以明显发现普通DCGAN算法与SGAN算法性能优劣
DCGAN 如下所示:
SGAN 如下所示:
二、代码实现
1.配置代码
python
import argparse
import os
import numpy as np
import math
import torchvision.transforms as transforms
from torchvision.utils import save_image
from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch
# 创建保存生成图像的文件夹
os.makedirs("images", exist_ok=True)
# 使用 argparse 解析命令行参数
parser = argparse.ArgumentParser()
parser.add_argument("--n_epochs", type=int, default=50, help="训练的轮数")
parser.add_argument("--batch_size", type=int, default=64, help="每个批次的样本数量")
parser.add_argument("--lr", type=float, default=0.0002, help="Adam 优化器的学习率")
parser.add_argument("--b1", type=float, default=0.5, help="Adam 优化器的第一个动量衰减参数")
parser.add_argument("--b2", type=float, default=0.999, help="Adam 优化器的第二个动量衰减参数")
parser.add_argument("--n_cpu", type=int, default=8, help="用于批次生成的 CPU 线程数")
parser.add_argument("--latent_dim", type=int, default=100, help="潜在空间的维度")
parser.add_argument("--num_classes", type=int, default=10, help="数据集的类别数")
parser.add_argument("--img_size", type=int, default=32, help="每个图像的尺寸(高度和宽度相等)")
parser.add_argument("--channels", type=int, default=1, help="图像的通道数(灰度图像通道数为 1)")
parser.add_argument("--sample_interval", type=int, default=400, help="图像采样间隔")
# opt = parser.parse_args() #如果有这行代码,项目不适合用jupyter notebook运行
opt = parser.parse_args([]) #有这行代码,项目才适合在jupyter notebook运行,就是多加了'[]'
print(opt)
# 如果 GPU 可用,则使用 CUDA 加速
cuda = True if torch.cuda.is_available() else False
2.初始化权重
python
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find("BatchNorm") != -1:
torch.nn.init.normal_(m.weight.data, 1.0, 0.02)
torch.nn.init.constant_(m.bias.data, 0.0)
3.定义算法模型
python
import torch.nn as nn
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
# 创建一个标签嵌入层,用于将条件标签映射到潜在空间
self.label_emb = nn.Embedding(opt.num_classes, opt.latent_dim)
# 初始化图像尺寸,用于上采样之前
self.init_size = opt.img_size // 4 # Initial size before upsampling
# 第一个全连接层,将随机噪声映射到合适的维度
self.l1 = nn.Sequential(nn.Linear(opt.latent_dim, 128 * self.init_size ** 2))
# 生成器的卷积块
self.conv_blocks = nn.Sequential(
nn.BatchNorm2d(128),
nn.Upsample(scale_factor=2),
nn.Conv2d(128, 128, 3, stride=1, padding=1),
nn.BatchNorm2d(128, 0.8),
nn.LeakyReLU(0.2, inplace=True),
nn.Upsample(scale_factor=2),
nn.Conv2d(128, 64, 3, stride=1, padding=1),
nn.BatchNorm2d(64, 0.8),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(64, opt.channels, 3, stride=1, padding=1),
nn.Tanh(),
)
def forward(self, noise):
out = self.l1(noise)
out = out.view(out.shape[0], 128, self.init_size, self.init_size)
img = self.conv_blocks(out)
return img
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
def discriminator_block(in_filters, out_filters, bn=True):
"""返回每个鉴别器块的层"""
block = [nn.Conv2d(in_filters, out_filters, 3, 2, 1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0.25)]
if bn:
block.append(nn.BatchNorm2d(out_filters, 0.8))
return block
# 鉴别器的卷积块
self.conv_blocks = nn.Sequential(
*discriminator_block(opt.channels, 16, bn=False),
*discriminator_block(16, 32),
*discriminator_block(32, 64),
*discriminator_block(64, 128),
)
# 下采样图像的高度和宽度
ds_size = opt.img_size // 2 ** 4
# 输出层
self.adv_layer = nn.Sequential(nn.Linear(128 * ds_size ** 2, 1), nn.Sigmoid()) # 用于鉴别真假的输出层
self.aux_layer = nn.Sequential(nn.Linear(128 * ds_size ** 2, opt.num_classes + 1), nn.Softmax()) # 用于鉴别类别的输出层
def forward(self, img):
out = self.conv_blocks(img)
out = out.view(out.shape[0], -1)
validity = self.adv_layer(out)
label = self.aux_layer(out)
return validity, label
4.配置模型
python
# 定义损失函数
adversarial_loss = torch.nn.BCELoss() # 二元交叉熵损失,用于对抗训练
auxiliary_loss = torch.nn.CrossEntropyLoss() # 交叉熵损失,用于辅助分类
# 初始化生成器和鉴别器
generator = Generator() # 创建生成器实例
discriminator = Discriminator() # 创建鉴别器实例
# 如果使用GPU,将模型和损失函数移至GPU上
if cuda:
generator.cuda()
discriminator.cuda()
adversarial_loss.cuda()
auxiliary_loss.cuda()
# 初始化模型权重
generator.apply(weights_init_normal) # 初始化生成器的权重
discriminator.apply(weights_init_normal) # 初始化鉴别器的权重
# 配置数据加载器
os.makedirs("../../data/mnist", exist_ok=True) # 创建存储MNIST数据集的文件夹
dataloader = torch.utils.data.DataLoader(
datasets.MNIST(
"../../data/mnist",
train=True,
download=True,
transform=transforms.Compose(
[transforms.Resize(opt.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]
),
),
batch_size=opt.batch_size,
shuffle=True,
)
# 优化器
optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) # 生成器的优化器
optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) # 鉴别器的优化器
# 根据是否使用GPU选择数据类型
FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor
LongTensor = torch.cuda.LongTensor if cuda else torch.LongTensor
5.训练模型
python
for epoch in range(opt.n_epochs):
for i, (imgs, labels) in enumerate(dataloader):
batch_size = imgs.shape[0]
# 定义对抗训练的标签
valid = Variable(FloatTensor(batch_size, 1).fill_(1.0), requires_grad=False) # 用于真实样本
fake = Variable(FloatTensor(batch_size, 1).fill_(0.0), requires_grad=False) # 用于生成样本
fake_aux_gt = Variable(LongTensor(batch_size).fill_(opt.num_classes), requires_grad=False) # 用于生成样本的类别标签
# 配置输入数据
real_imgs = Variable(imgs.type(FloatTensor)) # 真实图像
labels = Variable(labels.type(LongTensor)) # 真实类别标签
# -----------------
# 训练生成器
# -----------------
optimizer_G.zero_grad()
# 采样噪声和类别标签作为生成器的输入
z = Variable(FloatTensor(np.random.normal(0, 1, (batch_size, opt.latent_dim))))
# 生成一批图像
gen_imgs = generator(z)
# 计算生成器的损失,衡量生成器欺骗鉴别器的能力
validity, _ = discriminator(gen_imgs)
g_loss = adversarial_loss(validity, valid)
g_loss.backward()
optimizer_G.step()
# ---------------------
# 训练鉴别器
# ---------------------
optimizer_D.zero_grad()
# 真实图像的损失
real_pred, real_aux = discriminator(real_imgs)
d_real_loss = (adversarial_loss(real_pred, valid) + auxiliary_loss(real_aux, labels)) / 2
# 生成图像的损失
fake_pred, fake_aux = discriminator(gen_imgs.detach())
d_fake_loss = (adversarial_loss(fake_pred, fake) + auxiliary_loss(fake_aux, fake_aux_gt)) / 2
# 总的鉴别器损失
d_loss = (d_real_loss + d_fake_loss) / 2
# 计算鉴别器准确率
pred = np.concatenate([real_aux.data.cpu().numpy(), fake_aux.data.cpu().numpy()], axis=0)
gt = np.concatenate([labels.data.cpu().numpy(), fake_aux_gt.data.cpu().numpy()], axis=0)
d_acc = np.mean(np.argmax(pred, axis=1) == gt)
d_loss.backward()
optimizer_D.step()
batches_done = epoch * len(dataloader) + i
if batches_done % opt.sample_interval == 0:
save_image(gen_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True)
print(
"[Epoch %d/%d] [Batch %d/%d] [D loss: %f, acc: %d%%] [G loss: %f]"
% (epoch, opt.n_epochs, i, len(dataloader), d_loss.item(), 100 * d_acc, g_loss.item())
)
代码输出结果:
python
[Epoch 0/50] [Batch 937/938] [D loss: 1.370634, acc: 50%] [G loss: 0.726519]
[Epoch 1/50] [Batch 937/938] [D loss: 1.367375, acc: 50%] [G loss: 0.736427]
[Epoch 2/50] [Batch 937/938] [D loss: 1.370820, acc: 50%] [G loss: 0.701901]
[Epoch 3/50] [Batch 937/938] [D loss: 1.344976, acc: 51%] [G loss: 0.693297]
[Epoch 4/50] [Batch 937/938] [D loss: 1.312281, acc: 53%] [G loss: 1.003043]
[Epoch 5/50] [Batch 937/938] [D loss: 1.304581, acc: 54%] [G loss: 0.830410]
[Epoch 6/50] [Batch 937/938] [D loss: 1.337524, acc: 46%] [G loss: 0.885213]
[Epoch 7/50] [Batch 937/938] [D loss: 1.332608, acc: 53%] [G loss: 0.699805]
[Epoch 8/50] [Batch 937/938] [D loss: 1.294668, acc: 56%] [G loss: 1.095098]
[Epoch 9/50] [Batch 937/938] [D loss: 1.338896, acc: 50%] [G loss: 0.687774]
[Epoch 10/50] [Batch 937/938] [D loss: 1.356837, acc: 53%] [G loss: 0.979516]
[Epoch 11/50] [Batch 937/938] [D loss: 1.367788, acc: 46%] [G loss: 0.700279]
[Epoch 12/50] [Batch 937/938] [D loss: 1.257018, acc: 54%] [G loss: 1.176208]
[Epoch 13/50] [Batch 937/938] [D loss: 1.282979, acc: 54%] [G loss: 0.638599]
[Epoch 14/50] [Batch 937/938] [D loss: 1.284479, acc: 54%] [G loss: 1.413885]
[Epoch 15/50] [Batch 937/938] [D loss: 1.246834, acc: 54%] [G loss: 0.843728]
[Epoch 16/50] [Batch 937/938] [D loss: 1.255569, acc: 56%] [G loss: 0.884720]
[Epoch 17/50] [Batch 937/938] [D loss: 1.205555, acc: 54%] [G loss: 1.276188]
[Epoch 18/50] [Batch 937/938] [D loss: 1.240098, acc: 53%] [G loss: 1.133690]
[Epoch 19/50] [Batch 937/938] [D loss: 1.335942, acc: 50%] [G loss: 0.437380]
[Epoch 20/50] [Batch 937/938] [D loss: 1.279104, acc: 53%] [G loss: 0.788724]
[Epoch 21/50] [Batch 937/938] [D loss: 1.460971, acc: 51%] [G loss: 1.312856]
[Epoch 22/50] [Batch 937/938] [D loss: 1.311382, acc: 53%] [G loss: 1.370934]
[Epoch 23/50] [Batch 937/938] [D loss: 1.455373, acc: 50%] [G loss: 0.703406]
[Epoch 24/50] [Batch 937/938] [D loss: 1.582422, acc: 37%] [G loss: 1.693318]
[Epoch 25/50] [Batch 937/938] [D loss: 1.320866, acc: 54%] [G loss: 1.237430]
[Epoch 26/50] [Batch 937/938] [D loss: 1.280675, acc: 54%] [G loss: 2.025781]
[Epoch 27/50] [Batch 937/938] [D loss: 1.274172, acc: 56%] [G loss: 1.015904]
[Epoch 28/50] [Batch 937/938] [D loss: 1.288667, acc: 59%] [G loss: 1.203646]
[Epoch 29/50] [Batch 937/938] [D loss: 1.205220, acc: 59%] [G loss: 1.437130]
[Epoch 30/50] [Batch 937/938] [D loss: 1.097047, acc: 59%] [G loss: 1.121767]
[Epoch 31/50] [Batch 937/938] [D loss: 1.231415, acc: 62%] [G loss: 1.601083]
[Epoch 32/50] [Batch 937/938] [D loss: 1.264821, acc: 54%] [G loss: 1.326173]
[Epoch 33/50] [Batch 937/938] [D loss: 1.070387, acc: 68%] [G loss: 1.790723]
[Epoch 34/50] [Batch 937/938] [D loss: 1.287652, acc: 57%] [G loss: 1.497779]
[Epoch 35/50] [Batch 937/938] [D loss: 1.220142, acc: 60%] [G loss: 2.005124]
[Epoch 36/50] [Batch 937/938] [D loss: 1.354741, acc: 51%] [G loss: 2.340380]
[Epoch 37/50] [Batch 937/938] [D loss: 1.213522, acc: 54%] [G loss: 1.668633]
[Epoch 38/50] [Batch 937/938] [D loss: 1.170664, acc: 57%] [G loss: 1.041644]
[Epoch 39/50] [Batch 937/938] [D loss: 1.621943, acc: 40%] [G loss: 0.984611]
[Epoch 40/50] [Batch 937/938] [D loss: 1.235269, acc: 60%] [G loss: 0.924814]
[Epoch 41/50] [Batch 937/938] [D loss: 1.185314, acc: 64%] [G loss: 1.278665]
[Epoch 42/50] [Batch 937/938] [D loss: 1.174278, acc: 65%] [G loss: 0.871092]
[Epoch 43/50] [Batch 937/938] [D loss: 1.201611, acc: 54%] [G loss: 2.311854]
[Epoch 44/50] [Batch 937/938] [D loss: 1.546480, acc: 46%] [G loss: 1.745579]
[Epoch 45/50] [Batch 937/938] [D loss: 1.300673, acc: 59%] [G loss: 1.790518]
[Epoch 46/50] [Batch 937/938] [D loss: 1.268232, acc: 60%] [G loss: 2.638740]
[Epoch 47/50] [Batch 937/938] [D loss: 1.415018, acc: 45%] [G loss: 1.051125]
[Epoch 48/50] [Batch 937/938] [D loss: 0.974980, acc: 75%] [G loss: 2.183139]
[Epoch 49/50] [Batch 937/938] [D loss: 1.038189, acc: 68%] [G loss: 1.226219]
6.部分训练成果展示:
第一次输出的图像:
第36次输出的图像:
最后一次输出的图像:
三、总结
从代码的输出结果可知,训练出来的acc在50%上下浮动,最高也才75%,而损失则是比较低,要提高acc就要调试下相关参数,就是配置代码那部分。