第G9周:ACGAN理论与实战

本文为365天深度学习训练营 中的学习记录博客
原作者:K同学啊

可参考论文:《Conditional Image Synthesis With Auxiliary Classifier GANs》

一、理论基础
ACGAN的全称Auxiliary Classifier Generative Adversarial Network,翻译成汉语的意思就是带辅助分类器的GAN,ACGAN的原理GAN(CGAN)相似。对于CGAN和ACGAN,生成器输入均为潜在矢量及其标签,输出是属于输入类标签的伪造图像。
对于CGAN,判别器的输入是图像(包含假的或真实的图像)及其标签, 输出是图像属于真实图像的概率。对于ACGAN,判别器的输入是一幅图像,而输出是该图像属于真实图像的概率以及其类别。

图1:
在这里插入图片描述
图1是ACGAN的网络结构,可以发现该结构其 实和之前的CGAN和SGAN都非常接近,可以说是两者的结合体。但这样的修改可以有效生成高质量的生成结果,并且使得训练更加稳定
本质上,在CGAN中,向网络提供了标签。在ACGAN中,使用辅助解码器网络重建辅助信息。ACGAN理论认为,强制网络执行其他任务可以提高原始任务的性能。在这种情况下,辅助任务是图像分类。原始任务是生成伪造图像。

二、代码实现

1.导入第三方库


from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable

import torch.nn as nn
import torch

# 创建用于存储生成图像的目录
os.makedirs("images", exist_ok=True)

# 解析命令行参数
parser = argparse.ArgumentParser()
parser.add_argument("--n_epochs", type=int, default=200, 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("--n_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="图像通道数")
parser.add_argument("--sample_interval", type=int, default=400, help="图像采样间隔")
opt = parser.parse_args()
print(opt)

# 检查是否支持GPU加速
cuda = True if torch.cuda.is_available() else False

2.初始化权重

# 初始化神经网络权重的函数
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("BatchNorm2d") != -1:
        torch.nn.init.normal_(m.weight.data, 1.0, 0.02)
        torch.nn.init.constant_(m.bias.data, 0.0)

3.构建网络模型

# 生成器网络类
class Generator(nn.Module):
    def __init__(self):
        super(Generator, self).__init__()

        # 为类别标签创建嵌入层
        self.label_emb = nn.Embedding(opt.n_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, labels):
        # 将标签嵌入到噪声中
        gen_input = torch.mul(self.label_emb(labels), noise)

        # 通过第一层线性层
        out = self.l1(gen_input)

        # 重新整形为合适的形状
        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.n_classes), 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.模型初始化

# 损失函数
adversarial_loss = torch.nn.BCELoss()
auxiliary_loss = torch.nn.CrossEntropyLoss()

# 初始化生成器和判别器
generator = Generator()
discriminator = Discriminator()

if cuda:
    generator.cuda()
    discriminator.cuda()
    adversarial_loss.cuda()
    auxiliary_loss.cuda()

# 初始化权重
generator.apply(weights_init_normal)
discriminator.apply(weights_init_normal)

5.配置数据集

# 配置数据加载器
os.makedirs("../../data/mnist", exist_ok=True)
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,
)

6.模型训练

# 优化器
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))

FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor
LongTensor  = torch.cuda.LongTensor if cuda else torch.LongTensor

# 保存生成图像的函数
def sample_image(n_row, batches_done):
    """保存从0到n_classes的生成数字的图像网格"""
    # 采样噪声
    z = Variable(FloatTensor(np.random.normal(0, 1, (n_row ** 2, opt.latent_dim))))
    # 为n行生成标签从0到n_classes
    labels = np.array([num for _ in range(n_row) for num in range(n_row)])
    labels = Variable(LongTensor(labels))
    gen_imgs = generator(z, labels)
    save_image(gen_imgs.data, "images2/%d.png" % batches_done, nrow=n_row, normalize=True)

# ----------
# 训练
# ----------

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)

        # 配置输入
        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_labels = Variable(LongTensor(np.random.randint(0, opt.n_classes, batch_size)))

        # 生成一批图像
        gen_imgs = generator(z, gen_labels)

        # 损失度量生成器的欺骗判别器的能力
        validity, pred_label = discriminator(gen_imgs)
        g_loss = 0.5 * (adversarial_loss(validity, valid) + auxiliary_loss(pred_label, gen_labels))

        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, gen_labels)) / 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(), gen_labels.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], "images2/%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())
        )

上面的代码不适合在jupyter notebook中运行,要在jupyter notebook中运行,把
“1.导入第三方库”的一行代码“opt = parser.parse_args()”修改为“opt = parser.parse_args([])”,就是在小括号中加了“[]”。
根据我的电脑配置,我在“1.导入第三方库”的代码中将一些参数进行了修改,如下:

parser.add_argument("--n_epochs", type=int, default=50, help="训练的总轮数")

将训练的总轮数从200修改为50。

parser.add_argument("--batch_size", type=int, default=20, help="每个批次的大小")

将每个批次的大小从64修改为20。

parser.add_argument("--n_cpu", type=int, default=2, help="用于批次生成的CPU线程数")

将批次生成的CPU线程数从8修改为2。

7.训练结果:

[Epoch 0/50] [Batch 2999/3000] [D loss: 1.072988, acc: 85%] [G loss: 1.414592]
[Epoch 1/50] [Batch 2999/3000] [D loss: 1.065568, acc: 90%] [G loss: 1.227923]
[Epoch 2/50] [Batch 2999/3000] [D loss: 1.116059, acc: 95%] [G loss: 1.155359]
[Epoch 3/50] [Batch 2999/3000] [D loss: 1.154156, acc: 95%] [G loss: 1.079546]
[Epoch 4/50] [Batch 2999/3000] [D loss: 1.139272, acc: 100%] [G loss: 1.060603]
[Epoch 5/50] [Batch 2999/3000] [D loss: 1.074320, acc: 100%] [G loss: 0.997669]
[Epoch 6/50] [Batch 2999/3000] [D loss: 1.057753, acc: 97%] [G loss: 1.068776]
[Epoch 7/50] [Batch 2999/3000] [D loss: 1.105349, acc: 97%] [G loss: 1.074723]
[Epoch 8/50] [Batch 2999/3000] [D loss: 1.077433, acc: 100%] [G loss: 1.086036]
[Epoch 9/50] [Batch 2999/3000] [D loss: 1.090628, acc: 100%] [G loss: 1.090216]
[Epoch 10/50] [Batch 2999/3000] [D loss: 1.098849, acc: 95%] [G loss: 1.142725]
[Epoch 11/50] [Batch 2999/3000] [D loss: 1.052643, acc: 100%] [G loss: 1.104990]
[Epoch 12/50] [Batch 2999/3000] [D loss: 1.110375, acc: 97%] [G loss: 1.081588]
[Epoch 13/50] [Batch 2999/3000] [D loss: 1.107622, acc: 92%] [G loss: 1.075341]
[Epoch 14/50] [Batch 2999/3000] [D loss: 1.055770, acc: 100%] [G loss: 1.153219]
[Epoch 15/50] [Batch 2999/3000] [D loss: 1.051611, acc: 100%] [G loss: 1.089553]
[Epoch 16/50] [Batch 2999/3000] [D loss: 1.069481, acc: 100%] [G loss: 1.112475]
[Epoch 17/50] [Batch 2999/3000] [D loss: 1.082967, acc: 97%] [G loss: 1.142165]
[Epoch 18/50] [Batch 2999/3000] [D loss: 1.091758, acc: 97%] [G loss: 1.201067]
[Epoch 19/50] [Batch 2999/3000] [D loss: 1.033089, acc: 100%] [G loss: 1.038574]
[Epoch 20/50] [Batch 2999/3000] [D loss: 1.070976, acc: 97%] [G loss: 1.162846]
[Epoch 21/50] [Batch 2999/3000] [D loss: 1.049556, acc: 100%] [G loss: 1.079130]
[Epoch 22/50] [Batch 2999/3000] [D loss: 1.010474, acc: 100%] [G loss: 1.068803]
[Epoch 23/50] [Batch 2999/3000] [D loss: 1.127480, acc: 100%] [G loss: 1.048088]
[Epoch 24/50] [Batch 2999/3000] [D loss: 1.065602, acc: 100%] [G loss: 1.074875]
[Epoch 25/50] [Batch 2999/3000] [D loss: 1.054212, acc: 100%] [G loss: 1.081155]
[Epoch 26/50] [Batch 2999/3000] [D loss: 1.042196, acc: 100%] [G loss: 1.066349]
[Epoch 27/50] [Batch 2999/3000] [D loss: 1.056745, acc: 97%] [G loss: 1.140276]
[Epoch 28/50] [Batch 2999/3000] [D loss: 1.115287, acc: 100%] [G loss: 1.119715]
[Epoch 29/50] [Batch 2999/3000] [D loss: 1.072425, acc: 97%] [G loss: 1.102239]
[Epoch 30/50] [Batch 2999/3000] [D loss: 1.083690, acc: 97%] [G loss: 1.196178]
[Epoch 31/50] [Batch 2999/3000] [D loss: 1.125161, acc: 100%] [G loss: 1.079550]
[Epoch 32/50] [Batch 2999/3000] [D loss: 1.052037, acc: 95%] [G loss: 1.157050]
[Epoch 33/50] [Batch 2999/3000] [D loss: 1.071909, acc: 100%] [G loss: 1.041467]
[Epoch 34/50] [Batch 2999/3000] [D loss: 1.091363, acc: 100%] [G loss: 1.067523]
[Epoch 35/50] [Batch 2999/3000] [D loss: 1.052701, acc: 95%] [G loss: 1.097858]
[Epoch 36/50] [Batch 2999/3000] [D loss: 1.157273, acc: 97%] [G loss: 1.075618]
[Epoch 37/50] [Batch 2999/3000] [D loss: 1.014944, acc: 100%] [G loss: 1.053541]
[Epoch 38/50] [Batch 2999/3000] [D loss: 1.079770, acc: 100%] [G loss: 1.157935]
[Epoch 39/50] [Batch 2999/3000] [D loss: 1.065137, acc: 95%] [G loss: 1.137993]
[Epoch 40/50] [Batch 2999/3000] [D loss: 1.023423, acc: 95%] [G loss: 1.241156]
[Epoch 41/50] [Batch 2999/3000] [D loss: 1.090357, acc: 92%] [G loss: 1.019959]
[Epoch 42/50] [Batch 2999/3000] [D loss: 1.068307, acc: 97%] [G loss: 1.081773]
[Epoch 43/50] [Batch 2999/3000] [D loss: 1.166806, acc: 95%] [G loss: 0.991141]
[Epoch 44/50] [Batch 2999/3000] [D loss: 1.039831, acc: 100%] [G loss: 0.997956]
[Epoch 45/50] [Batch 2999/3000] [D loss: 1.057083, acc: 100%] [G loss: 1.030259]
[Epoch 46/50] [Batch 2999/3000] [D loss: 1.045938, acc: 97%] [G loss: 1.118669]
[Epoch 47/50] [Batch 2999/3000] [D loss: 1.104797, acc: 97%] [G loss: 0.981442]
[Epoch 48/50] [Batch 2999/3000] [D loss: 1.081195, acc: 95%] [G loss: 0.944901]
[Epoch 49/50] [Batch 2999/3000] [D loss: 1.124357, acc: 100%] [G loss: 1.170258]

从上面的结果来看,D loss、G loss稍微有点高,不过还算稳定,就是acc太高了,好多次都达到了100%,大部分的acc值都在90%以上。
acc的值最好在50%上下,那么就需要调整学习率、优化器、训练批次或者是模型网络。初步判断应该是生成器性能没跟上,可以考虑优化其网络结构。
目测生成的图像,效果还是不错的,请看下面生成的图像。

生成的第一张图像:
在这里插入图片描述

生成的第150张图像:
在这里插入图片描述

生成的第375张图像(也是最后一张图像):
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值