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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
| import torch import torch.nn as nn import torchvision.datasets as datasets import torchvision.transforms as transforms from torch.autograd import Variable import torch.backends.cudnn as cudnn
import argparse
from network import G, D
parser = argparse.ArgumentParser (description='GAN')
parser.add_argument ('--batch_size', type=int, default=12, help='训练batch-size大小 (default: 64)') parser.add_argument ('--imageSize', type=int, default=5, help='图片尺寸') parser.add_argument ('--max_epoch', type=int, default=5, help='最大迭代数 (default: 5)')
parser.add_argument ('--lr_g', type=float, default=2e-4, help='生成器学习率 (default: 2e-4)') parser.add_argument ('--lr_d', type=float, default=2e-4, help='判别器学习率 (default: 2e-4)') parser.add_argument ('--ngf', type=int, default=32, help='生成器feature map数') parser.add_argument ('--ndf', type=int, default=32, help='判别器feature map数') parser.add_argument ('--d_every', type=int, default=1, help='每几个batch训练一次判别器') parser.add_argument ('--g_every', type=int, default=2, help='每几个batch训练一次生成器') parser.add_argument ('--nz', type=int, default=5, help='噪声维度')
parser.add_argument ('--beta1', type=int, default=0.5, help='Adam优化器的beta1参数')
parser.add_argument ('--dataset', default='data/', help='数据集路径')
parser.add_argument ('--save_data', default='save/', help='保存路径')
parser.add_argument ('--vis', action='store_true', help='是否使用visdom可视化') parser.add_argument ('--plot_every', type=int, default=1, help='每间隔_batch,visdom画图一次')
parser.add_argument ('--cuda', action='store_true', help='开启cuda训练') parser.add_argument ('--plt', action='store_true', help='开启画图') parser.add_argument ('--test', action='store_true', help='开启测试生成') parser.add_argument ('--save_every', type=int, default=3, help='几个epoch保存一次模型 (default: 3)') parser.add_argument ('--seed', type=int, default=1, help='随机种子 (default: 1)') args = parser.parse_args ()
def train(): device = torch.device ('cuda') if args.cuda else torch.device ('cpu') torch.manual_seed (args.seed) if args.cuda: torch.cuda.manual_seed (args.seed) cudnn.benchmark = True if args.vis: vis = Visualizer ('GANs') data_transforms = transforms.Compose ([transforms.Scale (args.imageSize), transforms.CenterCrop (args.imageSize), transforms.ToTensor (), transforms.Normalize ((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) train_dataset = datasets.ImageFolder (root=args.dataset, transform=data_transforms) train_loader = torch.utils.data.DataLoader (dataset=train_dataset, batch_size=args.batch_size, shuffle=True) netG ,netD= G (args),D (args) netG.to (device) netD.to (device) print (netD, netG) optimizerD = torch.optim.Adam (netD.parameters (), lr=args.lr_d,betas=(0.5, 0.999)) optimizerG = torch.optim.Adam (netG.parameters (), lr=args.lr_g,betas=(0.5, 0.999)) G_losses = [] D_losses = [] img_list = [] import tqdm for epoch in range (args.max_epoch): for i, (images, labels) in tqdm.tqdm(enumerate (train_loader)): images = images.to (device) images = Variable (images) noises=Variable(torch.randn(args.batch_size, args.nz, 1, 1).to(device)) if i % args.d_every==0: optimizerD.zero_grad () output_r = netD (images) noises.data.copy_ (torch.randn (args.batch_size, args.nz, 1, 1)) fake = netG (noises).detach () output_f = netD (fake) D_loss = - torch.mean (torch.log (output_r) + torch.log (1. - output_f)) D_loss.backward () D_x = output_r.mean ().item () D_G_z1 = output_f.mean ().item () optimizerD.step () if i % args.g_every==0: optimizerG.zero_grad () fake = netG (noises) output_f = netD (fake) G_loss = torch.mean (torch.log (1. - output_f)) G_loss.backward () D_G_z2 = output_f.mean ().item () optimizerG.step () if args.vis and i % args.plot_every == args.plot_every - 1: fake = netG (noises) vis.images (fake.detach ().cpu ().numpy () [:64] * 0.5 + 0.5, win='fixfake') vis.images (images.data.cpu ().numpy () [:64] * 0.5 + 0.5, win='real') vis.plot ('errord', D_loss.item ()) vis.plot ('errorg', G_loss.item ()) if i % 1== 0: print ('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f' % (epoch, args.max_epoch, i, len (train_loader), D_loss.item (), G_loss.item (), D_x, D_G_z1, D_G_z2)) G_losses.append (G_loss.item ()) D_losses.append (D_loss.item ()) with torch.no_grad (): noises = torch.randn (args.batch_size, args.nz, 1, 1).to (device) fake = netG (noises).detach ().cpu () import torchvision.utils as vutils img_list.append (vutils.make_grid (fake, padding=2, normalize=True))
if (epoch + 1) % args.save_every == 0: import torchvision as tv tv.utils.save_image (fake.data [:64], '%s/%s.png' % (args.save_data, epoch), normalize=True,range=(-1, 1)) torch.save (netD.state_dict (), 'checkpoints/netd_%s.pth' % epoch) torch.save (netG.state_dict (), 'checkpoints/netg_%s.pth' % epoch) print('完成%s的模型保存'%epoch)
if args.plt: import matplotlib.pyplot as plt import numpy as np import torchvision.utils as vutils plt.figure (figsize=(10, 5)) plt.title ("GAN") plt.plot (G_losses, label="G") plt.plot (D_losses, label="D") plt.xlabel ("迭代次数") plt.ylabel ("损失") plt.legend () plt.show () real_batch = next (iter (train_dataset)) plt.figure (figsize=(15, 10)) plt.subplot (1, 2, 1) plt.axis ("off") plt.title ("真图") plt.imshow (np.transpose ( vutils.make_grid (real_batch [0].to (device) [:64], padding=5, normalize=True).cpu (), (1, 2, 0))) plt.subplot (1, 2, 2) plt.axis ("off") plt.title ("假图") plt.imshow (np.transpose (img_list [-1], (1, 2, 0))) plt.show ()
@torch.no_grad() def test(): device = torch.device ('cuda') if args.cuda else torch.device ('cpu') netg, netd = netG (args).eval (), netD (args).eval () noises = torch.randn (args.batch_size, args.nz, 1, 1).to (device) netd.load_state_dict (torch.load ('checkpoints/netd_%s.pth'%args.max_epoch)) netg.load_state_dict (torch.load ('checkpoints/netg_%s.pth'%args.max_epoch)) netd.to (device) netg.to (device) fake_img = netg (noises) scores = netd (fake_img).detach () indexs = scores.topk (5) [1] result = [] for i in indexs: result.append (fake_img.data [i]) import torchvision as tv tv.utils.save_image (torch.stack (result), 5, normalize=True, range=(-1, 1))
import visdom import time import torchvision as tv import numpy as np
class Visualizer (): """ 封装了visdom的基本操作,但是你仍然可以通过`self.vis.function` 调用原生的visdom接口 """ def __init__ (self, env='default', **kwargs): import visdom self.vis = visdom.Visdom (env=env, use_incoming_socket=False, **kwargs) self.index = {} self.log_text = '' def reinit (self, env='default', **kwargs): """ 修改visdom的配置 """ self.vis = visdom.Visdom (env=env, use_incoming_socket=False, **kwargs) return self def plot_many (self, d): """ 一次plot多个 @params d: dict (name,value) i.e. ('loss',0.11) """ for k, v in d.items (): self.plot (k, v) def img_many (self, d): for k, v in d.items (): self.img (k, v) def plot (self, name, y): """ self.plot('loss',1.00) """ x = self.index.get (name, 0) self.vis.line (Y=np.array ([y]), X=np.array ([x]), win=(name), opts=dict (title=name), update=None if x == 0 else 'append' ) self.index [name] = x + 1 def img (self, name, img_): """ self.img('input_img',t.Tensor(64,64)) """ if len (img_.size ()) < 3: img_ = img_.cpu ().unsqueeze (0) self.vis.image (img_.cpu (), win=(name), opts=dict (title=name) ) def img_grid_many (self, d): for k, v in d.items (): self.img_grid (k, v) def img_grid (self, name, input_3d): """ 一个batch的图片转成一个网格图,i.e. input(36,64,64) 会变成 6*6 的网格图,每个格子大小64*64 """ self.img (name, tv.utils.make_grid ( input_3d.cpu () [0].unsqueeze (1).clamp (max=1, min=0))) def log (self, info, win='log_text'): """ self.log({'loss':1,'lr':0.0001}) """ self.log_text += ('[{time}] {info} <br>'.format ( time=time.strftime ('%m%d_%H%M%S'), info=info)) self.vis.text (self.log_text, win=win) def __getattr__ (self, name): return getattr (self.vis, name) if __name__ == '__main__': if args.test: test() else: train()
|