实现用LSGAN生成指定手写数字

LSGAN即最小二乘GAN,它的主要改进是替换了损失函数。

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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#-*- 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 = 2 # 每个周期内生成器训练次数
BATCH_SIZE = 100 # 批处理尺寸

z_dimension = 110 # 初始向量z_dimension之前用的是100维,由于MNIST有10类,Onehot以后一张图片的类标签是10维,所以将类标签放在后面z_dimension=100+10=110维

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

# 定义数据预处理方式
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.conv1 = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=4, stride=2, padding=1, bias=False),
# 卷积后图像尺寸 (28+1*2-4)/步长+1 = 14
nn.LeakyReLU(0.2)
)
self.conv2 = nn.Sequential(
nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1, bias=False),
# 卷积后图像尺寸 (14+1*2-4)/步长+1 = 7
nn.BatchNorm2d(128),
nn.LeakyReLU(0.2)
)
self.conv3 = nn.Sequential(
nn.Conv2d(128, 256, kernel_size=4, stride=1, bias=False),
# 卷积后图像尺寸 (7-4)/步长+1 = 4
nn.BatchNorm2d(256),
nn.LeakyReLU(0.2)
)
self.conv4 = nn.Sequential(
nn.Conv2d(256, 10, kernel_size=4, stride=1, bias=False),
# 卷积后图像尺寸 (4-4)/步长+1 = 1
nn.Sigmoid()
)

def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
return x

class generator(nn.Module):
'''
生成器网络
'''
def __init__(self, input_size):
super(generator, self).__init__()
self.deconv1 = nn.Sequential(
nn.ConvTranspose2d(input_size, 256, kernel_size=4, stride=1),
nn.BatchNorm2d(256),
nn.ReLU()
)
self.deconv2 = nn.Sequential(
nn.ConvTranspose2d(256, 128, kernel_size=4, stride=1),
nn.BatchNorm2d(128),
nn.ReLU()
)
self.deconv3 = nn.Sequential(
nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(64),
nn.ReLU()
)
self.deconv4 = nn.Sequential(
nn.ConvTranspose2d(64, 1, kernel_size=4, stride=2, padding=1),
nn.Tanh()
)

def forward(self, x):
x = self.deconv1(x)
x = self.deconv2(x)
x = self.deconv3(x)
x = self.deconv4(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.MSELoss()

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_LSGAN():
'''
交替训练的方式训练网络
先训练判别器网络D再训练生成器网络G
'''
for epoch in range(EPOCH):
for data in trainloader:
real_images, labels = data
# real_images = real_images.view(BATCH_SIZE, -1)
real_images = real_images.to(device)

labels_onehot = np.zeros((BATCH_SIZE, 10))
labels_onehot[np.arange(BATCH_SIZE), labels.numpy()] = 1

real_labels = torch.from_numpy(labels_onehot).float().to(device) # 真实label
fake_labels = torch.zeros(BATCH_SIZE, 10).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).view(-1, z_dimension, 1, 1).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, 100) # 随机生成向量
z = np.concatenate((z.numpy(), labels_onehot), axis=1)
z = torch.from_numpy(z).float().view(-1, z_dimension, 1, 1).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 >= 5:
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_LSGAN():
'''
测试LSGAN
'''
G.load_state_dict(torch.load("./model/G_best.pth")) # 加载模型参数
G.eval() # 设置模式为验证模式
z = torch.randn(BATCH_SIZE, 100) # 随机生成向量
z_onehot = np.zeros((BATCH_SIZE, 10))
z_onehot[:, 8] = 1
z = np.concatenate((z.numpy(), z_onehot), axis=1)
z = torch.from_numpy(z).float().view(-1, z_dimension, 1, 1).to(device)

fake_images = G(z)
showimg(fake_images)
plt.show()

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

if __name__ == "__main__":
train_LSGAN()
test_LSGAN()
0%