环境
系统:win10
cpu:i7-6700HQ
gpu:gtx965m
python : 3.6
pytorch :0.3
什么是GAN..
网上找的解答:
以竞争的方式达到以假乱真的,颇有遗传算法适者生存的意味(自己瞎琢磨的)。
GAN的分为两个部:第一部分为判别器,判别器只判断真伪,即 0(真)、1(假)。运作过程为两步走:1、向原作学习何为真, 2、对生成器生成的作品予以判别。也就是说,我只跟你说你的作品和原作像不像,而不跟你说原作是怎样的。
第二部分为生成器,用来生成作品,再输入到判别器里,判别器会给出判断,为真奖励、假惩罚,辅助生成器成长,但是判别器不会透露原作信息,故而生成器会随意发挥,生成原作没有的细节。这也是其生成的图像清晰度高于VAE的原因。
数据
依旧是已经用烂得mnist
dataset = datasets.MNIST('./mnist', True, transform=transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]))
dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)
# 加载一个batch数据
dataiter = iter(dataloader)
imgs, labels = dataiter.next()
# 可视化部分数据
viz.images(imgs[:64])
判别器网络(Discrimination):
self.ds = nn.Sequential(
nn.Linear(28*28, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 128),
nn.LeakyReLU(0.2),
nn.Linear(128, 1),
# sigmoid 数据归于(0,1)之间
nn.Sigmoid()
)
生成器网络(Generator):
self.gn = nn.Sequential(
# 初始一个多维向量用以储存特征
nn.Linear(fake_dim, 256),
nn.ReLU(True),
nn.Linear(256, 256),
nn.ReLU(True),
nn.Linear(256, 28*28),
nn.Tanh()
)
优化函数用Adam , learning-rate 0.0002 , 运行100 个 epoch ,每10 epoch 可视化一下:
虽然100个epochs下来已经有一些 数字的形态了,但是还是太模糊了,为了增强图片生成效果,于是我们结合CNN来写神经网络:
Discrimination:
self.conv1 = nn.Sequential(
nn.Conv2d(1, 32, 5, 1,2),
nn.LeakyReLU(0.2, True),
nn.MaxPool2d(2),
)
self.conv2 = nn.Sequential(
nn.Conv2d(32, 64, 5, 1,2),
nn.LeakyReLU(0.2, True),
nn.MaxPool2d(2)
)
self.fc = nn.Sequential(
nn.Linear(64 * 7 * 7, 1024),
nn.LeakyReLU(0.2, True),
nn.Linear(1024, 1),
nn.Sigmoid()
)
Generator:
self.fc = nn.Linear(fake_dim, 1*56*56)
self.br = nn.Sequential(
nn.BatchNorm2d(1),
nn.ReLU(True)
)
self.deconv1 = nn.Sequential(
nn.Conv2d(1, 50, 3, 1, 1),
nn.BatchNorm2d(50),
nn.ReLU(True)
)
self.deconv2 = nn.Sequential(
nn.Conv2d(50, 25, 3, 1, 1),
nn.BatchNorm2d(25),
nn.ReLU(True)
)
self.deconv3 = nn.Sequential(
nn.Conv2d(25, 1, 2, 2),
nn.Tanh()
)
对于 CNN 各种参数改变不是很清楚的看这里:我是连接。
由于神经网比价复杂(耗时),我们运行10个epochs:
结果很惊人啊,,第5个epoch就生成一些可以分辨的数字了,10个epoch下来生成的图像已经很好了,而且很清晰。
代码在这。这里写链接内容