欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ACGAN代码——阅读记录

程序员文章站 2022-03-09 13:32:37
...

步骤

定义初始化参数
定义生成器网络(标签 尺寸)-将标签和噪声作为输入-全连接层-重排数据-卷积块-生成图片
定义判别器网络 -将生成图片输入卷积块-重排数据—1.输出真伪2.输出分类
初始化参数
数据加载
定义优化器
定义采样
训练: G用随机噪声和标签生成图片——用D打分——定义g_loss 优化G

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)

parser = argparse.ArgumentParser()
parser.add_argument("--n_epochs", type=int, default=200, help="number of epochs of training")
parser.add_argument("--batch_size", type=int, default=64, help="size of the batches")
parser.add_argument("--lr", type=float, default=0.0002, help="adam: learning rate")
parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient")
parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient")
parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation")
parser.add_argument("--latent_dim", type=int, default=100, help="dimensionality of the latent space")
parser.add_argument("--n_classes", type=int, default=10, help="number of classes for dataset")  #类别数量
parser.add_argument("--img_size", type=int, default=32, help="size of each image dimension")        #图片尺寸
parser.add_argument("--channels", type=int, default=1, help="number of image channels")             #彩色/黑白
parser.add_argument("--sample_interval", type=int, default=400, help="interval between image sampling") #采样频率
opt = parser.parse_args()
print(opt)

cuda = True if torch.cuda.is_available() else False


def weights_init_normal(m):     #定义参数初始化函数,解析:https://www.lizenghai.com/archives/28867.html
    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)


class Generator(nn.Module):
    def __init__(self):
        super(Generator, self).__init__()

        self.label_emb = nn.Embedding(opt.n_classes, opt.latent_dim)    #词嵌入(类别数,维度)  ACGAN的条件信息

        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))   #输入100维噪声  全连接层

        self.conv_blocks = nn.Sequential(       #CNN用于GAN中要变动
            nn.BatchNorm2d(128),    #卷积的输出通道数 128  (理解为128个卷积核 128片)
            nn.Upsample(scale_factor=2),    #上采样  指定输出为输入的多少倍数
            nn.Conv2d(128, 128, 3, stride=1, padding=1),    #nn.Conv2d(in_channel, out_channel, 3, stride, 1, bias=False)
            nn.BatchNorm2d(128, 0.8),  #0.8为使数值稳定而加到分母上的值
            nn.LeakyReLU(0.2, inplace=True),    #0.2=控制负斜率的角度,inplace-选择是否进行覆盖运算
            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)    #torch.mul(input, value, out=None)
        out = self.l1(gen_input)        #经过l1网络全连接层
        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):
            """Returns layers of each discriminator block"""
            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在81*discriminator_block(16, 32),
            *discriminator_block(32, 64),
            *discriminator_block(64, 128),
        )

        # The height and width of downsampled image
        ds_size = opt.img_size // 2 ** 4

        # Output layers
        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


# Loss functions
adversarial_loss = torch.nn.BCELoss()
auxiliary_loss = torch.nn.CrossEntropyLoss()

# Initialize generator and discriminator
generator = Generator()
discriminator = Discriminator()

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

# Initialize weights
generator.apply(weights_init_normal)
discriminator.apply(weights_init_normal)

# Configure data loader
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,
)

# Optimizers
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):
    """Saves a grid of generated digits ranging from 0 to n_classes"""
    # Sample noise
    z = FloatTensor(np.random.normal(0, 1, (n_row ** 2, opt.latent_dim)))
    # Get labels ranging from 0 to n_classes for n rows
    labels = np.array([num for _ in range(n_row) for num in range(n_row)])
    labels = LongTensor(labels)#放入GPU
    gen_imgs = generator(z, labels) #生成图像有标签
    save_image(gen_imgs.data, "images/%d.png" % batches_done, nrow=n_row, normalize=True)   #保存到文件夹


# ----------
#  Training
# ----------

for epoch in range(opt.n_epochs):
    for i, (imgs, labels) in enumerate(dataloader):

        batch_size = imgs.shape[0]

        # Adversarial ground truths   放入cuda
        valid = Variable(FloatTensor(batch_size, 1).fill_(1.0), requires_grad=False)
        fake = Variable(FloatTensor(batch_size, 1).fill_(0.0), requires_grad=False)
        #valid和fake代表不同的值 训练D时让真实数据值和valid接近  伪造数据值和fake接近
        # Configure input
        real_imgs = imgs.type(FloatTensor)
        labels = labels.type(LongTensor)

        # -----------------
        #  Train Generator 先训练生成器 得到标签
        # -----------------

        optimizer_G.zero_grad()

        # Sample noise and labels as generator input
        z = Variable(FloatTensor(np.random.normal(0, 1, (batch_size, opt.latent_dim)))) #均值、标准差、shape(一批多少个z 一个z多少维)
        gen_labels = Variable(LongTensor(np.random.randint(0, opt.n_classes, batch_size)))# 返回随机整数[low,high),多少个

        # Generate a batch of images
        gen_imgs = generator(z, gen_labels)

        # Loss measures generator's ability to fool the discriminator
        validity, pred_label = discriminator(gen_imgs)
        g_loss = 0.5 * (adversarial_loss(validity, valid) + auxiliary_loss(pred_label, gen_labels))
        # 判别器给gen_img的得分和预标签为validity, pred_label    生成器的输入为z,gen_labels    希望真实数据的值为valid
        g_loss.backward()
        optimizer_G.step()

        # ---------------------
        #  Train Discriminator
        # ---------------------

        optimizer_D.zero_grad()
        #鉴别器loss得定义
        # Loss for real images
        real_pred, real_aux = discriminator(real_imgs)  #真实数据评分和标签
        d_real_loss = (adversarial_loss(real_pred, valid) + auxiliary_loss(real_aux, labels)) / 2
                            #要让valid和real_pred接近    并且让label(直接取得)和判别的aux一致
        # Loss for fake images
        fake_pred, fake_aux = discriminator(gen_imgs.detach())
        d_fake_loss = (adversarial_loss(fake_pred, fake) + auxiliary_loss(fake_aux, gen_labels)) / 2
                            # 要让fake和fake_pred接近    并且让gen_label(直接取得)和判别的aux一致
        # Total discriminator loss
        d_loss = (d_real_loss + d_fake_loss) / 2

        # Calculate discriminator accuracy   concatenate数组拼接
        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()

        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())
        )
        batches_done = epoch * len(dataloader) + i
        if batches_done % opt.sample_interval == 0:
            sample_image(n_row=10, batches_done=batches_done)

相关标签: GAN