实现用GAN生成手写数字

我们会使用mnist手写数字来做数据集,通过生成对抗网络我们希望生成一些’以假乱真’的手写字体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#-*- coding:utf-8 -*-
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
import torch.optim as optim
import torchvision as tv
import torchvision.transforms as transforms
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec

#========================================================
# 超参数设置和类别配置
#========================================================

EPOCH = 3 # 遍历数据集次数
GEPOCH = 1 # 每个周期内生成器训练次数
BATCH_SIZE = 100 # 批处理尺寸

z_dimension = 100 # 生成器输入向量维数

#========================================================
# 数据加工
#========================================================

# 定义数据预处理方式
transform = transforms.Compose([
transforms.ToTensor(), # 将图片(Image)转化为Tensor, 归一化到[0,1]
transforms.Normalize(mean=[0.5], std=[0.5]) # 标准化到[-1,1]
])

# 定义训练数据集
trainset = tv.datasets.MNIST(
root='./data/',
train=True,
download=True,
transform=transform)

# 定义训练批处理数据
trainloader = torch.utils.data.DataLoader(
trainset,
batch_size=BATCH_SIZE,
shuffle=True
)

# 定义测试数据集
testset = tv.datasets.MNIST(
root='./data/',
train=False,
download=True,
transform=transform)

# 定义测试批处理数据
testloader = torch.utils.data.DataLoader(
testset,
batch_size=BATCH_SIZE,
shuffle=False
)

#========================================================
# 模型结构设计
#========================================================

class discriminator(nn.Module):
'''
判别器网络
'''
def __init__(self):
super(discriminator, self).__init__()
self.dis = nn.Sequential(
nn.Linear(784, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 1),
nn.Sigmoid()
)

def forward(self, x):
x = self.dis(x)
return x

class generator(nn.Module):
'''
生成器网络
'''
def __init__(self, input_size):
super(generator, self).__init__()
self.gen = nn.Sequential(
nn.Linear(input_size, 256),
nn.ReLU(True),
nn.Linear(256, 256),
nn.ReLU(True),
nn.Linear(256, 784),
nn.Tanh()
)

def forward(self, x):
x = self.gen(x)
return x

#========================================================
# 模型实例化
#========================================================

# 定义是否使用GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
D = discriminator().to(device)
G = generator(z_dimension).to(device)

# 定义损失函数loss function 和优化方式
criterion = nn.BCELoss()

d_optimizer = torch.optim.Adam(D.parameters(), lr=0.0005)
g_optimizer = torch.optim.Adam(G.parameters(), lr=0.0002)

#========================================================
# 训练模型
#========================================================

def showimg(images):
'''
生成图片的可视化
'''
images = images.to('cpu')
images = images.detach().numpy()
images = 255*(0.5*images+0.5)
images = images.astype(np.uint8)

grid_length = int(np.ceil(np.sqrt(images.shape[0])))
plt.figure(figsize=(grid_length, grid_length))
gs = gridspec.GridSpec(grid_length, grid_length, wspace=0, hspace=0)
for i, img in enumerate(images):
ax = plt.subplot(gs[i])
ax.set_aspect('equal')
plt.imshow(img.reshape(28, 28), cmap=plt.cm.gray)
plt.axis('off')

def train_GAN():
'''
交替训练的方式训练网络
先训练判别器网络D再训练生成器网络G
'''
for epoch in range(EPOCH):
for data in trainloader:
real_images, _ = data
real_images = real_images.view(BATCH_SIZE, -1) # 将图片展开成28x28=78
real_images = real_images.to(device)

real_labels = torch.ones(BATCH_SIZE).to(device) # 定义真实label为1
fake_labels = torch.zeros(BATCH_SIZE).to(device) # 定义假的label为0

############################################
# 先训练判别器D
############################################

# 计算真图片的loss
d_out_real = D(real_images) # 真实图片送入判别器D输出0~1
d_out_real = np.squeeze(d_out_real)
d_loss_real = criterion(d_out_real, real_labels)

# 计算假图片的loss
z = torch.randn(BATCH_SIZE, z_dimension).to(device) # 随机生成向量
fake_images = G(z) # 将向量放入生成器G生成图片
d_out_fake = D(fake_images) # 判别器D判断假的图片
d_out_fake = np.squeeze(d_out_fake)
d_loss_fake = criterion(d_out_fake, fake_labels)

d_loss = d_loss_real + d_loss_fake
d_optimizer.zero_grad() # 判别器D的梯度归零
d_loss.backward() # 反向传播
d_optimizer.step() # 更新判别器D参数

############################################
# 再训练生成器G
############################################

for j in range(GEPOCH):
z = torch.randn(BATCH_SIZE, z_dimension).to(device) # 随机生成向量
fake_images = G(z) # 将向量放入生成器G生成图片
d_out = D(fake_images) # 经过判别器得到结果
d_out = np.squeeze(d_out)
g_loss = criterion(d_out, real_labels)

g_optimizer.zero_grad() # 生成器G的梯度归零
g_loss.backward() # 反向传播
g_optimizer.step() # 更新生成器G参数

print('Epoch [{}/{}]'.format(epoch, EPOCH))
if epoch >= 2:
showimg(fake_images)
plt.show()
torch.save(D.state_dict(), '%s/D_best.pth' % ('./model/'))
torch.save(G.state_dict(), '%s/G_best.pth' % ('./model/'))

def test_GAN():
'''
测试GAN
'''
G.load_state_dict(torch.load("./model/G_best.pth")) # 加载模型参数
G.eval() # 设置模式为验证模式
z = torch.randn(BATCH_SIZE, z_dimension).to(device) # 随机生成向量
fake_images = G(z)
showimg(fake_images)
plt.show()

#========================================================
# 主程序
#========================================================

if __name__ == "__main__":
train_GAN()
test_GAN()

0%