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 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
|
import paddle import paddle.fluid as fluid from paddle.fluid.dygraph import Conv2D, Pool2D, Linear, Conv2DTranspose import numpy as np import matplotlib.pyplot as plt
Z_DIM = 100 BATCH_SIZE = 128
def z_reader(): while True: yield np.random.normal(0.0, 1.0, (Z_DIM, 1, 1)).astype('float32')
mnist_generator = paddle.batch( paddle.reader.shuffle(paddle.dataset.mnist.train(), 30000), batch_size=BATCH_SIZE)
z_generator = paddle.batch(z_reader, batch_size=BATCH_SIZE)
%matplotlib inline
data_tmp = next(mnist_generator()) print('一个batch图片数据的形状:batch_size =', len(data_tmp), ', data_shape =', data_tmp[0][0].shape, ', num = ', data_tmp[0][1])
plt.imshow(data_tmp[0][0].reshape(28, 28)) plt.show()
z_tmp = next(z_generator()) print('一个batch噪声z的形状:batch_size =', len(z_tmp), ', data_shape =', z_tmp[0].shape)
def conv_concatenate(x, y): if len(x.shape) == 2: y = fluid.layers.reshape(y, shape=[x.shape[0], 1]) ones = fluid.layers.fill_constant(y.shape, dtype='float32', value=1.0) elif len(x.shape) == 4: y = fluid.layers.reshape(y, shape=[x.shape[0], 1, 1, 1]) ones = fluid.layers.fill_constant(x.shape, dtype='float32', value=1.0) x = fluid.layers.concat([x, ones * y], axis=1)
return x
class G(fluid.dygraph.Layer): def __init__(self, name_scope): super(G, self).__init__(name_scope) name_scope = self.full_name() self.fc1 = Linear(input_dim=100+1, output_dim=1024) self.bn1 = fluid.dygraph.BatchNorm(num_channels=1024, act='relu') self.fc2 = Linear(input_dim=1024+1, output_dim=128*7*7) self.bn2 = fluid.dygraph.BatchNorm(num_channels=128*7*7, act='relu') self.convtrans1 = Conv2DTranspose(256, 64, 4, stride=2, padding=1) self.bn3 = fluid.dygraph.BatchNorm(64, act='relu') self.convtrans2 = Conv2DTranspose(128, 1, 4, stride=2, padding=1, act='relu') def forward(self, z, label): z = fluid.layers.reshape(z, shape=[-1, 100]) z = conv_concatenate(z, label) y = self.fc1(z) y = self.bn1(y) y = conv_concatenate(y, label) y = self.fc2(y) y = self.bn2(y) y = fluid.layers.reshape(y, shape=[-1, 128, 7, 7]) y = conv_concatenate(y, label) y = self.convtrans1(y) y = self.bn3(y) y = conv_concatenate(y, label) y = self.convtrans2(y) return y
class D(fluid.dygraph.Layer): def __init__(self, name_scope): super(D, self).__init__(name_scope) name_scope = self.full_name() self.conv1 = Conv2D(num_channels=2, num_filters=64, filter_size=3) self.bn1 = fluid.dygraph.BatchNorm(num_channels=64, act='leaky_relu') self.pool1 = Pool2D(pool_size=2, pool_stride=2) self.conv2 = Conv2D(num_channels=128, num_filters=128, filter_size=3) self.bn2 = fluid.dygraph.BatchNorm(num_channels=128, act='leaky_relu') self.pool2 = Pool2D(pool_size=2, pool_stride=2) self.fc1 = Linear(input_dim=128*5*5+1, output_dim=1024) self.bnfc1 = fluid.dygraph.BatchNorm(num_channels=1024, act='leaky_relu') self.fc2 = Linear(input_dim=1024+1, output_dim=1)
def forward(self, img, label): y = conv_concatenate(img, label) y = self.conv1(y) y = self.bn1(y) y = self.pool1(y) y = conv_concatenate(y, label) y = self.conv2(y) y = self.bn2(y) y = self.pool2(y) y = fluid.layers.reshape(y, shape=[-1, 128*5*5]) y = conv_concatenate(y, label) y = self.fc1(y) y = self.bnfc1(y) y = conv_concatenate(y, label) y = self.fc2(y)
return y
with fluid.dygraph.guard(): g_tmp = G('G') l_tmp = fluid.dygraph.to_variable(np.array([x[1] for x in data_tmp]).astype('float32')) tmp_g = g_tmp(fluid.dygraph.to_variable(np.array(z_tmp)), l_tmp).numpy() print('生成器G生成图片数据的形状:', tmp_g.shape) plt.imshow(tmp_g[0][0]) plt.show()
d_tmp = D('D') tmp_d = d_tmp(fluid.dygraph.to_variable(tmp_g), l_tmp).numpy() print('判别器D判别生成的图片的概率数据形状:', tmp_d.shape)
%matplotlib inline
def show_image_grid(images, batch_size=128, pass_id=None): fig = plt.figure(figsize=(8, batch_size/32)) fig.suptitle("Pass {}".format(pass_id)) gs = plt.GridSpec(int(batch_size/16), 16) gs.update(wspace=0.05, hspace=0.05)
for i, image in enumerate(images): ax = plt.subplot(gs[i]) plt.axis('off') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect('equal') plt.imshow(image[0], cmap='Greys_r') plt.show()
show_image_grid(tmp_g, BATCH_SIZE)
from visualdl import LogWriter import time import random
def train(mnist_generator, epoch_num=10, batch_size=128, use_gpu=True, load_model=False): place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace() with fluid.dygraph.guard(place): model_path = './work/home/aistudio/output/'
d = D('D') d.train() g = G('G') g.train()
g_optimizer = fluid.optimizer.SGDOptimizer(learning_rate=2e-4, parameter_list=g.parameters()) d_optimizer = fluid.optimizer.SGDOptimizer(learning_rate=2e-4, parameter_list=d.parameters()) if load_model == True: g_para, g_opt = fluid.load_dygraph(model_path+'g') d_para, d_opt = fluid.load_dygraph(model_path+'d') g.load_dict(g_para) g_optimizer.set_dict(g_opt) d.load_dict(d_para) d_optimizer.set_dict(d_opt)
iteration_num = 0 print('Start time :', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 'start step:', iteration_num + 1) for epoch in range(epoch_num): for i, real_data in enumerate(mnist_generator()): if(len(real_data) != BATCH_SIZE): continue iteration_num += 1 ''' 判别器d通过最小化输入真实图片时判别器d的输出与真值标签ones的交叉熵损失,来优化判别器的参数, 以增加判别器d识别真实图片real_image为真值标签ones的概率。 ''' ri = np.array([x[0] for x in real_data]).reshape(-1, 1, 28, 28) rl = np.array([x[1] for x in real_data]).astype('float32') real_image = fluid.dygraph.to_variable(np.array(ri)) real_label = fluid.dygraph.to_variable(rl) ones = fluid.dygraph.to_variable(np.ones([len(real_image), 1]).astype('float32')) p_real = d(real_image, real_label) real_cost = (p_real - ones) ** 2 real_avg_cost = fluid.layers.mean(real_cost)
''' 判别器d通过最小化输入生成器g生成的假图片g(z)时判别器的输出与假值标签zeros的交叉熵损失, 来优化判别器d的参数,以增加判别器d识别生成器g生成的假图片g(z)为假值标签zeros的概率。 ''' z = next(z_generator()) z = fluid.dygraph.to_variable(np.array(z)) zeros = fluid.dygraph.to_variable(np.zeros([len(real_image), 1]).astype('float32')) p_fake = d(g(z, real_label), real_label) fake_cost = (p_fake - zeros) ** 2 fake_avg_cost = fluid.layers.mean(fake_cost) d_loss = real_avg_cost + fake_avg_cost d_loss.backward() d_optimizer.minimize(d_loss) d.clear_gradients()
''' 生成器g通过最小化判别器d判别生成器生成的假图片g(z)为真的概率d(fake)与真值标签ones的交叉熵损失, 来优化生成器g的参数,以增加生成器g使判别器d判别其生成的假图片g(z)为真值标签ones的概率。 ''' fake = g(z, real_label) p_fake = d(fake, real_label) g_cost = (p_fake - ones) ** 2 g_avg_cost = fluid.layers.mean(g_cost) g_avg_cost.backward() g_optimizer.minimize(g_avg_cost) g.clear_gradients() if(iteration_num % 100 == 0): print('epoch =', epoch, ', batch =', i, ', d_loss =', d_loss.numpy(), 'g_loss =', g_avg_cost.numpy()) show_image_grid(fake.numpy(), BATCH_SIZE, epoch)
print('End time :', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 'End Step:', iteration_num) fluid.save_dygraph(g.state_dict(), model_path+'g') fluid.save_dygraph(g_optimizer.state_dict(), model_path+'g') fluid.save_dygraph(d.state_dict(), model_path+'d') fluid.save_dygraph(d_optimizer.state_dict(), model_path+'d')
train(mnist_generator, epoch_num=1, batch_size=BATCH_SIZE, use_gpu=True, load_model=True)
def infer(batch_size=128, num=0, use_gpu=True): place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace() with fluid.dygraph.guard(place): model_path = './work/home/aistudio/output/'
g = G('G') g.eval()
g_para, g_opt = fluid.load_dygraph(model_path+'g') g.load_dict(g_para)
z = next(z_generator()) z = fluid.dygraph.to_variable(np.array(z)) label = fluid.layers.fill_constant([batch_size], dtype='float32', value=float(num)) fake = g(z, label) show_image_grid(fake.numpy(), batch_size, -1)
for i in range(10): infer(batch_size=BATCH_SIZE, num=i)
|