GAN网络简单应用——MNISTS数据集合2

impo

rt argparse import os import numpy as np import math import matplotlib.pyplot as plt 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("images1", exist_ok=True) # 解析命令行参数 parser = argparse.ArgumentParser() parser.add_argument("--n_epochs", type=int, default=100, help="number of epochs of training") parser.add_argument("--batch_size", type=int, default=128, 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("--img_size", type=int, default=28, 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 samples") opt = parser.parse_args() print(opt) img_shape = (opt.channels, opt.img_size, opt.img_size) # 检查是否有可用的 GPU #cuda = True if torch.cuda.is_available() else False device = 'cuda' if torch.cuda.is_available() else 'cpu' # ---------------- # 模型定义 # ---------------- # 生成器模型 class Generator(nn.Module): def __init__(self): super(Generator, self).__init__() def block(in_feat, out_feat, normalize=True): layers = [nn.Linear(in_feat, out_feat)] if normalize: layers.append(nn.BatchNorm1d(out_feat, 0.8)) layers.append(nn.LeakyReLU(0.2, inplace=True)) return layers self.model = nn.Sequential( *block(opt.latent_dim, 128, normalize=False), *block(128, 256), *block(256, 512), *block(512, 1024), nn.Linear(1024, int(np.prod(img_shape))), nn.Tanh() ) def forward(self, z): img = self.model(z) img = img.view(img.size(0), *img_shape) return img # 判别器模型 class Discriminator(nn.Module): def __init__(self): super(Discriminator, self).__init__() self.model = nn.Sequential( nn.Linear(int(np.prod(img_shape)), 512), nn.LeakyReLU(0.2, inplace=True), nn.Linear(512, 256), nn.LeakyReLU(0.2, inplace=True), nn.Linear(256, 1), nn.Sigmoid(), ) def forward(self, img): img_flat = img.view(img.size(0), -1) validity = self.model(img_flat) return validity # 二元交叉熵损失函数 adversarial_loss = torch.nn.BCELoss() # 初始化生成器和判别器 generator = Generator() discriminator = Discriminator() # 将模型移动到GPU上(如果可用) generator.to(device) discriminator.to(device) adversarial_loss.to(device) # 配置数据加载器 os.makedirs("./data/mnist", exist_ok=True) transform = transforms.Compose( [transforms.Resize(opt.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])] ) train_ds = datasets.MNIST("./data/mnist", train=True, transform=transform, download=False) dataloader = torch.utils.data.DataLoader( train_ds, 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或CPU)随机生成的输入张量 test_input = torch.randn([16, 100], device=device) #Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor def loss_show(D_loss, G_loss): plt.figure(figsize=(8, 8)) if len(D_loss) == len(G_loss): step = len(D_loss) else: print("Warning: Lengths of D_loss and G_loss are not equal.") exit() plt.plot(range(0, step), D_loss, label='Discriminator Loss', color='red') plt.plot(range(0, step), G_loss, label='Generator Loss', color='blue') plt.legend(['Discriminator Loss', 'Generator Loss']) plt.xlabel('step', fontsize=14) plt.ylabel('loss value', fontsize=14) # 在每个点的位置添加文本标签 #for i, (x, y_d, y_g) in enumerate(zip(range(0, step), D_loss, G_loss)): #plt.text(x, y_d, f'({y_d:.2f})', fontsize=8, color='red', ha='right', va='bottom') #plt.text(x, y_g, f'({y_g:.3f})', fontsize=8, color='red', ha='right', va='bottom') plt.title('Discriminator and Generator Loss Over Steps') plt.show() D_loss =[] G_loss =[] # --------- # 训练循环 # --------- for epoch in range(100): d_epoch_loss,g_epoch_loss=0,0 count = len(dataloader) for i, (imgs, _) in enumerate(dataloader): # Adversarial ground truths # 为真实样本和生成样本创建标签 valid = torch.full((imgs.size(0), 1), 1.0, dtype=torch.float32, requires_grad=False).to(device) fake = torch.full((imgs.size(0), 1), 0.0, dtype=torch.float32, requires_grad=False).to(device) # 配置输入 real_imgs = imgs.to(device) # ----------------- # 训练生成器 # ----------------- optimizer_G.zero_grad() # 生成潜在空间中的噪声向量 z = torch.randn((imgs.shape[0], opt.latent_dim)).to(device) # 生成图像 gen_imgs = generator(z) # 计算生成器的损失 g_loss = adversarial_loss(discriminator(gen_imgs), valid) g_loss.backward() optimizer_G.step() # --------------------- # 训练判别器 # --------------------- optimizer_D.zero_grad() # 计算判别器对真实样本的损失 real_loss = adversarial_loss(discriminator(real_imgs), valid) # 计算判别器对生成样本的损失,将生成器的输出张量分离以避免梯度传播到生成器模型 fake_loss = adversarial_loss(discriminator(gen_imgs.detach()), fake) # 判别器总体损失为真实样本损失和生成样本损失的平均值 d_loss = (real_loss + fake_loss) / 2 d_loss.backward() optimizer_D.step() # 一个epoch中总的loss with torch.no_grad(): d_epoch_loss += d_loss g_epoch_loss += g_loss batches_done = epoch * len(dataloader) + i # 每隔一定的迭代次数保存生成器生成的图像 if batches_done % opt.sample_interval == 0: save_image(gen_imgs.data[:25], "images1/%d.png" % batches_done, nrow=5, normalize=True) with torch.no_grad(): d_epoch_loss /= count g_epoch_loss /= count D_loss.append(d_epoch_loss.detach().cpu().numpy()) G_loss.append(g_epoch_loss.detach().cpu().numpy()) print(f'Epoch: {epoch},D_loss: {D_loss[epoch].item():.3f},G_loss: {G_loss[epoch].item():.3f}') loss_show(D_loss,G_loss)