当前位置:   article > 正文

循环生成对抗网络CycleGAN

循环生成对抗网络

图像到图像的转换的目标是使用配准的图像对训练集来学习输入图像和输出图像之间的映射,而CycleGAN中使用的方法是缺少配对训练集的情况下进行图像转换。

传统的图像转换如上图左,训练集是配对的x,y图像{xi,yi};如上图右,训练集是源域{xi},目标域{yi},但二者之间未给定配对关系。

网络结构

涉及4个网络,生成器A2B,生成器B2A,判别器A判别器B

4种损失函数:G网络(用MSELoss计算)、D网络(用MSELoss计算)、Cycle(原始输入和Cycl输出,用L1Loss计算)、identify(对于生成器A2B用B作为输入,用L1Loss计算;对于生成器B2A用A作为输入,用L1Loss计算)

self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B']

生成器网络结构:输入-->普通卷积-->图像越来越小,特征图越来越多-->反卷积-->图像越来越大,特征图越来越少-->输出(与输入相同大小)

判别器网络结构:输入-->普通卷积-->升维操作特征图越来越多-->假如得到MxNx512特征图,再经过卷积到得MxNx1的矩阵(后面需要针对每个像素点计算Loss)-->输出

 Cycle_gan_model.py

  1. import torch
  2. import itertools
  3. from util.image_pool import ImagePool
  4. from .base_model import BaseModel
  5. from . import networks
  6. class CycleGANModel(BaseModel):
  7. """
  8. This class implements the CycleGAN model, for learning image-to-image translation without paired data.
  9. The model training requires '--dataset_mode unaligned' dataset.
  10. By default, it uses a '--netG resnet_9blocks' ResNet generator,
  11. a '--netD basic' discriminator (PatchGAN introduced by pix2pix),
  12. and a least-square GANs objective ('--gan_mode lsgan').
  13. CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf
  14. """
  15. @staticmethod
  16. def modify_commandline_options(parser, is_train=True):
  17. """Add new dataset-specific options, and rewrite default values for existing options.
  18. Parameters:
  19. parser -- original option parser
  20. is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
  21. Returns:
  22. the modified parser.
  23. For CycleGAN, in addition to GAN losses, we introduce lambda_A, lambda_B, and lambda_identity for the following losses.
  24. A (source domain), B (target domain).
  25. Generators: G_A: A -> B; G_B: B -> A.
  26. Discriminators: D_A: G_A(A) vs. B; D_B: G_B(B) vs. A.
  27. Forward cycle loss: lambda_A * ||G_B(G_A(A)) - A|| (Eqn. (2) in the paper)
  28. Backward cycle loss: lambda_B * ||G_A(G_B(B)) - B|| (Eqn. (2) in the paper)
  29. Identity loss (optional): lambda_identity * (||G_A(B) - B|| * lambda_B + ||G_B(A) - A|| * lambda_A) (Sec 5.2 "Photo generation from paintings" in the paper)
  30. Dropout is not used in the original CycleGAN paper.
  31. """
  32. parser.set_defaults(no_dropout=True) # default CycleGAN did not use dropout
  33. if is_train:
  34. parser.add_argument('--lambda_A', type=float, default=10.0, help='weight for cycle loss (A -> B -> A)')
  35. parser.add_argument('--lambda_B', type=float, default=10.0, help='weight for cycle loss (B -> A -> B)')
  36. parser.add_argument('--lambda_identity', type=float, default=0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1')
  37. return parser
  38. def __init__(self, opt):
  39. """Initialize the CycleGAN class.
  40. Parameters:
  41. opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
  42. """
  43. BaseModel.__init__(self, opt)
  44. # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
  45. self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B']
  46. # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
  47. visual_names_A = ['real_A', 'fake_B', 'rec_A']
  48. visual_names_B = ['real_B', 'fake_A', 'rec_B']
  49. if self.isTrain and self.opt.lambda_identity > 0.0: # if identity loss is used, we also visualize idt_B=G_A(B) ad idt_A=G_A(B)
  50. visual_names_A.append('idt_B')
  51. visual_names_B.append('idt_A')
  52. self.visual_names = visual_names_A + visual_names_B # combine visualizations for A and B
  53. # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>.
  54. if self.isTrain:
  55. self.model_names = ['G_A', 'G_B', 'D_A', 'D_B']
  56. else: # during test time, only load Gs
  57. self.model_names = ['G_A', 'G_B']
  58. # define networks (both Generators and discriminators)
  59. # The naming is different from those used in the paper.
  60. # Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)
  61. self.netG_A = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm,
  62. not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
  63. self.netG_B = networks.define_G(opt.output_nc, opt.input_nc, opt.ngf, opt.netG, opt.norm,
  64. not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
  65. if self.isTrain: # define discriminators
  66. self.netD_A = networks.define_D(opt.output_nc, opt.ndf, opt.netD,
  67. opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)
  68. self.netD_B = networks.define_D(opt.input_nc, opt.ndf, opt.netD,
  69. opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)
  70. if self.isTrain:
  71. if opt.lambda_identity > 0.0: # only works when input and output images have the same number of channels
  72. assert(opt.input_nc == opt.output_nc)
  73. self.fake_A_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images
  74. self.fake_B_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images
  75. # define loss functions
  76. self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device) # define GAN loss.
  77. self.criterionCycle = torch.nn.L1Loss()
  78. self.criterionIdt = torch.nn.L1Loss()
  79. # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
  80. self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))
  81. self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(), self.netD_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))
  82. self.optimizers.append(self.optimizer_G)
  83. self.optimizers.append(self.optimizer_D)
  84. def set_input(self, input):
  85. """Unpack input data from the dataloader and perform necessary pre-processing steps.
  86. Parameters:
  87. input (dict): include the data itself and its metadata information.
  88. The option 'direction' can be used to swap domain A and domain B.
  89. """
  90. AtoB = self.opt.direction == 'AtoB'
  91. self.real_A = input['A' if AtoB else 'B'].to(self.device)
  92. self.real_B = input['B' if AtoB else 'A'].to(self.device)
  93. self.image_paths = input['A_paths' if AtoB else 'B_paths']
  94. def forward(self):
  95. """Run forward pass; called by both functions <optimize_parameters> and <test>."""
  96. self.fake_B = self.netG_A(self.real_A) # G_A(A)
  97. self.rec_A = self.netG_B(self.fake_B) # G_B(G_A(A))
  98. self.fake_A = self.netG_B(self.real_B) # G_B(B)
  99. self.rec_B = self.netG_A(self.fake_A) # G_A(G_B(B))
  100. def backward_D_basic(self, netD, real, fake):
  101. """Calculate GAN loss for the discriminator
  102. Parameters:
  103. netD (network) -- the discriminator D
  104. real (tensor array) -- real images
  105. fake (tensor array) -- images generated by a generator
  106. Return the discriminator loss.
  107. We also call loss_D.backward() to calculate the gradients.
  108. """
  109. # Real
  110. pred_real = netD(real)
  111. loss_D_real = self.criterionGAN(pred_real, True)
  112. # Fake
  113. pred_fake = netD(fake.detach())
  114. loss_D_fake = self.criterionGAN(pred_fake, False)
  115. # Combined loss and calculate gradients
  116. loss_D = (loss_D_real + loss_D_fake) * 0.5
  117. loss_D.backward()
  118. return loss_D
  119. def backward_D_A(self):
  120. """Calculate GAN loss for discriminator D_A"""
  121. fake_B = self.fake_B_pool.query(self.fake_B)
  122. self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_B, fake_B)
  123. def backward_D_B(self):
  124. """Calculate GAN loss for discriminator D_B"""
  125. fake_A = self.fake_A_pool.query(self.fake_A)
  126. self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_A, fake_A)
  127. def backward_G(self):
  128. """Calculate the loss for generators G_A and G_B"""
  129. lambda_idt = self.opt.lambda_identity
  130. lambda_A = self.opt.lambda_A
  131. lambda_B = self.opt.lambda_B
  132. # Identity loss
  133. if lambda_idt > 0:
  134. # G_A should be identity if real_B is fed: ||G_A(B) - B||
  135. self.idt_A = self.netG_A(self.real_B)
  136. self.loss_idt_A = self.criterionIdt(self.idt_A, self.real_B) * lambda_B * lambda_idt
  137. # G_B should be identity if real_A is fed: ||G_B(A) - A||
  138. self.idt_B = self.netG_B(self.real_A)
  139. self.loss_idt_B = self.criterionIdt(self.idt_B, self.real_A) * lambda_A * lambda_idt
  140. else:
  141. self.loss_idt_A = 0
  142. self.loss_idt_B = 0
  143. # GAN loss D_A(G_A(A))
  144. self.loss_G_A = self.criterionGAN(self.netD_A(self.fake_B), True)
  145. # GAN loss D_B(G_B(B))
  146. self.loss_G_B = self.criterionGAN(self.netD_B(self.fake_A), True)
  147. # Forward cycle loss || G_B(G_A(A)) - A||
  148. self.loss_cycle_A = self.criterionCycle(self.rec_A, self.real_A) * lambda_A
  149. # Backward cycle loss || G_A(G_B(B)) - B||
  150. self.loss_cycle_B = self.criterionCycle(self.rec_B, self.real_B) * lambda_B
  151. # combined loss and calculate gradients
  152. self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + self.loss_idt_B
  153. self.loss_G.backward()
  154. def optimize_parameters(self):
  155. """Calculate losses, gradients, and update network weights; called in every training iteration"""
  156. # forward
  157. self.forward() # compute fake images and reconstruction images.
  158. # G_A and G_B
  159. self.set_requires_grad([self.netD_A, self.netD_B], False) # Ds require no gradients when optimizing Gs
  160. self.optimizer_G.zero_grad() # set G_A and G_B's gradients to zero
  161. self.backward_G() # calculate gradients for G_A and G_B
  162. self.optimizer_G.step() # update G_A and G_B's weights
  163. # D_A and D_B
  164. self.set_requires_grad([self.netD_A, self.netD_B], True)
  165. self.optimizer_D.zero_grad() # set D_A and D_B's gradients to zero
  166. self.backward_D_A() # calculate gradients for D_A
  167. self.backward_D_B() # calculate graidents for D_B
  168. self.optimizer_D.step() # update D_A and D_B's weights

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/854161
推荐阅读
相关标签
  

闽ICP备14008679号