首先介绍一下MNIST数据集,MNIST是个手写数字图片集,每张图片都做了归一化处理,大小是28x28,并且是灰度图像,所以shape是1x28x28
官方网址:http://yann.lecun.com/exdb/mnist/,来到数据集下载页面,可以看到:
主要包括四个文件:
类别 | 文件名 | 描述 |
---|---|---|
训练集图片 | train-images-idx3-ubyte.gz(9.9M) | 包含60000个样本 |
训练集标签 | train-labels-idx1-ubyte.gz(29KB) | 包含60000个标签 |
测试集图片 | t10k-images-idx3-ubyte.gz(1.6M) | 包含10000个样本 |
测试集标签 | t10k-labels-idx1-ubyte.gz(5KB) | 包含10000个样本 |
解压后,得到的并不是标准的图像格式,想深入了解的可以去看官网的描述。要把数据读取出来也得按照文件数据结构来,可以参考这篇博客的代码。
在torchvison.datasets
中已经为我们封装好了MNIST数据集(解压+读取)
在论文Gradient-Based Learning Applied to Document Recognition,作者首次提出了LeNet-5 网络,利用上述数据集实现了手写字体的识别,网络模型如下:
用GAN生成MNIST图片
0.1 导入相关包
import os
import numpy as np
import math
# 命令行参数解析包
import argparse
# 导入pytorch相关包
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
0.2 命令行参数配置
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("--latent_dim", type=int, default=100, help="dimensionality of the latent space")
parser.add_argument("--sample_interval", type=int, default=400, help="interval between image samples")
opt = parser.parse_args()
print(opt)
img_shape = (1, 28, 28) # 图像的尺寸
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
输出:
# output:
Namespace(b1=0.5, b2=0.999, batch_size=64, latent_dim=100, lr=0.0002, n_epochs=200, sample_interval=400)
cuda
tfm = transforms.Compose([transforms.Resize(28),
transforms.ToTensor(),
transforms.Normalize([0.5],[0.5])])
data_loader = torch.utils.data.DataLoader(
datasets.MNIST("./data", train=True, download=True, transform=tfm),
batch_size=opt.batch_size,
shuffle=True)
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
# 定义一个block,每个block的操作就是线性层,正则化(可选),再激活层
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
if __name__ == '__main__':
# Initialize generator and discriminator
generator = Generator().to(device)
discriminator = Discriminator().to(device)
# Loss function
adversarial_loss = torch.nn.BCELoss().to(device)
# 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))
Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
# 创建存储生成图片的目录
os.makedirs("images", exist_ok=True)
for epoch in range(opt.n_epochs):
for i, (imgs, _) in enumerate(data_loader):
# Adversarial ground truths,valid:64x1的全1向量,fake:64x1的全零向量
valid = Variable(Tensor(imgs.size(0), 1).fill_(1.0), requires_grad=False)
fake = Variable(Tensor(imgs.size(0), 1).fill_(0.0), requires_grad=False)
# Configure input ,让输入图像适应网络
real_imgs = Variable(imgs.type(Tensor))
# -----------------
# Train Generator
# -----------------
optimizer_G.zero_grad()
# Sample noise as generator input,z是有标准正态分布采样得到的64x100向量
z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim))))
# Generate a batch of images,64x1x28x28
gen_imgs = generator(z)
# Loss measures generator's ability to fool the discriminator
"""生成器损失函数:让生成的图像通过判别器后与valid相比较,越靠近越好"""
g_loss = adversarial_loss(discriminator(gen_imgs), valid)
g_loss.backward()
optimizer_G.step()
# ---------------------
# Train Discriminator
# ---------------------
optimizer_D.zero_grad()
# Measure discriminator's ability to classify real from generated samples
"""
判别器损失函数:一方面让真实图片通过判别器与valid越接近,
另一方面让生成的图片通过判别器与fake越接近(正好与生成器相矛盾,这样才能提高判别能力)
"""
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()
print(
"[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]"
% (epoch, opt.n_epochs, i, len(data_loader), d_loss.item(), g_loss.item())
)
batches_done = epoch * len(data_loader) + i
if batches_done % opt.sample_interval == 0:
save_image(gen_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True)
输出:
# output:
[Epoch 0/200] [Batch 0/938] [D loss: 0.712640] [G loss: 0.712526]
[Epoch 0/200] [Batch 1/938] [D loss: 0.622424] [G loss: 0.709658]
[Epoch 0/200] [Batch 2/938] [D loss: 0.554259] [G loss: 0.707226]
[Epoch 0/200] [Batch 3/938] [D loss: 0.495899] [G loss: 0.704608]
[Epoch 0/200] [Batch 4/938] [D loss: 0.452283] [G loss: 0.701480]
[Epoch 0/200] [Batch 5/938] [D loss: 0.419015] [G loss: 0.696898]
[Epoch 0/200] [Batch 6/938] [D loss: 0.396711] [G loss: 0.692087]
[Epoch 0/200] [Batch 7/938] [D loss: 0.384795] [G loss: 0.685381]
[Epoch 0/200] [Batch 8/938] [D loss: 0.378744] [G loss: 0.675533]
[Epoch 0/200] [Batch 9/938] [D loss: 0.378815] [G loss: 0.665169]
[Epoch 0/200] [Batch 10/938] [D loss: 0.382517] [G loss: 0.653243]
…………
在images/目录下,会看到生成的图片逐渐趋向真实的MNIST数据集……