You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_gpu_vae_gan.py 5.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """
  16. The VAE interface can be called to construct VAE-GAN network.
  17. """
  18. import os
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.vision.c_transforms as CV
  21. import mindspore.nn as nn
  22. from mindspore import context
  23. import mindspore.ops as ops
  24. from mindspore.nn.probability.dpn import VAE
  25. from mindspore.nn.probability.infer import ELBO, SVI
  26. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  27. IMAGE_SHAPE = (-1, 1, 32, 32)
  28. image_path = os.path.join('/home/workspace/mindspore_dataset/mnist', "train")
  29. class Encoder(nn.Cell):
  30. def __init__(self):
  31. super(Encoder, self).__init__()
  32. self.fc1 = nn.Dense(1024, 400)
  33. self.relu = nn.ReLU()
  34. self.flatten = nn.Flatten()
  35. def construct(self, x):
  36. x = self.flatten(x)
  37. x = self.fc1(x)
  38. x = self.relu(x)
  39. return x
  40. class Decoder(nn.Cell):
  41. def __init__(self):
  42. super(Decoder, self).__init__()
  43. self.fc1 = nn.Dense(400, 1024)
  44. self.relu = nn.ReLU()
  45. self.sigmoid = nn.Sigmoid()
  46. self.reshape = ops.Reshape()
  47. def construct(self, z):
  48. z = self.fc1(z)
  49. z = self.reshape(z, IMAGE_SHAPE)
  50. z = self.sigmoid(z)
  51. return z
  52. class Discriminator(nn.Cell):
  53. """
  54. The Discriminator of the GAN network.
  55. """
  56. def __init__(self):
  57. super(Discriminator, self).__init__()
  58. self.fc1 = nn.Dense(1024, 400)
  59. self.fc2 = nn.Dense(400, 720)
  60. self.fc3 = nn.Dense(720, 1024)
  61. self.relu = nn.ReLU()
  62. self.sigmoid = nn.Sigmoid()
  63. self.flatten = nn.Flatten()
  64. def construct(self, x):
  65. x = self.flatten(x)
  66. x = self.fc1(x)
  67. x = self.relu(x)
  68. x = self.fc2(x)
  69. x = self.relu(x)
  70. x = self.fc3(x)
  71. x = self.sigmoid(x)
  72. return x
  73. class VaeGan(nn.Cell):
  74. def __init__(self):
  75. super(VaeGan, self).__init__()
  76. self.E = Encoder()
  77. self.G = Decoder()
  78. self.D = Discriminator()
  79. self.dense = nn.Dense(20, 400)
  80. self.vae = VAE(self.E, self.G, 400, 20)
  81. self.shape = ops.Shape()
  82. self.normal = ops.normal
  83. self.to_tensor = ops.ScalarToArray()
  84. def construct(self, x):
  85. recon_x, x, mu, std = self.vae(x)
  86. z_p = self.normal(self.shape(mu), self.to_tensor(0.0), self.to_tensor(1.0), seed=0)
  87. z_p = self.dense(z_p)
  88. x_p = self.G(z_p)
  89. ld_real = self.D(x)
  90. ld_fake = self.D(recon_x)
  91. ld_p = self.D(x_p)
  92. return ld_real, ld_fake, ld_p, recon_x, x, mu, std
  93. class VaeGanLoss(ELBO):
  94. def __init__(self):
  95. super(VaeGanLoss, self).__init__()
  96. self.zeros = ops.ZerosLike()
  97. self.mse = nn.MSELoss(reduction='sum')
  98. def construct(self, data, label):
  99. ld_real, ld_fake, ld_p, recon_x, x, mu, std = data
  100. y_real = self.zeros(ld_real) + 1
  101. y_fake = self.zeros(ld_fake)
  102. loss_D = self.mse(ld_real, y_real)
  103. loss_GD = self.mse(ld_p, y_fake)
  104. loss_G = self.mse(ld_fake, y_real)
  105. reconstruct_loss = self.recon_loss(x, recon_x)
  106. kl_loss = self.posterior('kl_loss', 'Normal', self.zeros(mu), self.zeros(mu) + 1, mu, std)
  107. elbo_loss = reconstruct_loss + self.sum(kl_loss)
  108. return loss_D + loss_G + loss_GD + elbo_loss
  109. def create_dataset(data_path, batch_size=32, repeat_size=1,
  110. num_parallel_workers=1):
  111. """
  112. create dataset for train or test
  113. """
  114. # define dataset
  115. mnist_ds = ds.MnistDataset(data_path)
  116. resize_height, resize_width = 32, 32
  117. rescale = 1.0 / 255.0
  118. shift = 0.0
  119. # define map operations
  120. resize_op = CV.Resize((resize_height, resize_width)) # Bilinear mode
  121. rescale_op = CV.Rescale(rescale, shift)
  122. hwc2chw_op = CV.HWC2CHW()
  123. # apply map operations on images
  124. mnist_ds = mnist_ds.map(operations=resize_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  125. mnist_ds = mnist_ds.map(operations=rescale_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  126. mnist_ds = mnist_ds.map(operations=hwc2chw_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  127. # apply DatasetOps
  128. mnist_ds = mnist_ds.batch(batch_size)
  129. mnist_ds = mnist_ds.repeat(repeat_size)
  130. return mnist_ds
  131. def test_vae_gan():
  132. vae_gan = VaeGan()
  133. net_loss = VaeGanLoss()
  134. optimizer = nn.Adam(params=vae_gan.trainable_params(), learning_rate=0.001)
  135. ds_train = create_dataset(image_path, 128, 1)
  136. net_with_loss = nn.WithLossCell(vae_gan, net_loss)
  137. vi = SVI(net_with_loss=net_with_loss, optimizer=optimizer)
  138. vae_gan = vi.run(train_dataset=ds_train, epochs=5)