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.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. from mindspore.ops import operations as P
  24. from mindspore.ops import composite as C
  25. from mindspore.nn.probability.dpn import VAE
  26. from mindspore.nn.probability.infer import ELBO, SVI
  27. context.set_context(mode=context.GRAPH_MODE, save_graphs=False, device_target="GPU")
  28. IMAGE_SHAPE = (-1, 1, 32, 32)
  29. image_path = os.path.join('/home/workspace/mindspore_dataset/mnist', "train")
  30. class Encoder(nn.Cell):
  31. def __init__(self):
  32. super(Encoder, self).__init__()
  33. self.fc1 = nn.Dense(1024, 400)
  34. self.relu = nn.ReLU()
  35. self.flatten = nn.Flatten()
  36. def construct(self, x):
  37. x = self.flatten(x)
  38. x = self.fc1(x)
  39. x = self.relu(x)
  40. return x
  41. class Decoder(nn.Cell):
  42. def __init__(self):
  43. super(Decoder, self).__init__()
  44. self.fc1 = nn.Dense(400, 1024)
  45. self.relu = nn.ReLU()
  46. self.sigmoid = nn.Sigmoid()
  47. self.reshape = P.Reshape()
  48. def construct(self, z):
  49. z = self.fc1(z)
  50. z = self.reshape(z, IMAGE_SHAPE)
  51. z = self.sigmoid(z)
  52. return z
  53. class Discriminator(nn.Cell):
  54. """
  55. The Discriminator of the GAN network.
  56. """
  57. def __init__(self):
  58. super(Discriminator, self).__init__()
  59. self.fc1 = nn.Dense(1024, 400)
  60. self.fc2 = nn.Dense(400, 720)
  61. self.fc3 = nn.Dense(720, 1024)
  62. self.relu = nn.ReLU()
  63. self.sigmoid = nn.Sigmoid()
  64. self.flatten = nn.Flatten()
  65. def construct(self, x):
  66. x = self.flatten(x)
  67. x = self.fc1(x)
  68. x = self.relu(x)
  69. x = self.fc2(x)
  70. x = self.relu(x)
  71. x = self.fc3(x)
  72. x = self.sigmoid(x)
  73. return x
  74. class VaeGan(nn.Cell):
  75. def __init__(self):
  76. super(VaeGan, self).__init__()
  77. self.E = Encoder()
  78. self.G = Decoder()
  79. self.D = Discriminator()
  80. self.dense = nn.Dense(20, 400)
  81. self.vae = VAE(self.E, self.G, 400, 20)
  82. self.shape = P.Shape()
  83. self.normal = C.normal
  84. self.to_tensor = P.ScalarToArray()
  85. def construct(self, x):
  86. recon_x, x, mu, std = self.vae(x)
  87. z_p = self.normal(self.shape(mu), self.to_tensor(0.0), self.to_tensor(1.0), seed=0)
  88. z_p = self.dense(z_p)
  89. x_p = self.G(z_p)
  90. ld_real = self.D(x)
  91. ld_fake = self.D(recon_x)
  92. ld_p = self.D(x_p)
  93. return ld_real, ld_fake, ld_p, recon_x, x, mu, std
  94. class VaeGanLoss(ELBO):
  95. def __init__(self):
  96. super(VaeGanLoss, self).__init__()
  97. self.zeros = P.ZerosLike()
  98. self.mse = nn.MSELoss(reduction='sum')
  99. def construct(self, data, label):
  100. ld_real, ld_fake, ld_p, recon_x, x, mu, std = data
  101. y_real = self.zeros(ld_real) + 1
  102. y_fake = self.zeros(ld_fake)
  103. loss_D = self.mse(ld_real, y_real)
  104. loss_GD = self.mse(ld_p, y_fake)
  105. loss_G = self.mse(ld_fake, y_real)
  106. reconstruct_loss = self.recon_loss(x, recon_x)
  107. kl_loss = self.posterior('kl_loss', 'Normal', self.zeros(mu), self.zeros(mu) + 1, mu, std)
  108. elbo_loss = reconstruct_loss + self.sum(kl_loss)
  109. return loss_D + loss_G + loss_GD + elbo_loss
  110. def create_dataset(data_path, batch_size=32, repeat_size=1,
  111. num_parallel_workers=1):
  112. """
  113. create dataset for train or test
  114. """
  115. # define dataset
  116. mnist_ds = ds.MnistDataset(data_path)
  117. resize_height, resize_width = 32, 32
  118. rescale = 1.0 / 255.0
  119. shift = 0.0
  120. # define map operations
  121. resize_op = CV.Resize((resize_height, resize_width)) # Bilinear mode
  122. rescale_op = CV.Rescale(rescale, shift)
  123. hwc2chw_op = CV.HWC2CHW()
  124. # apply map operations on images
  125. mnist_ds = mnist_ds.map(operations=resize_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  126. mnist_ds = mnist_ds.map(operations=rescale_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  127. mnist_ds = mnist_ds.map(operations=hwc2chw_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  128. # apply DatasetOps
  129. mnist_ds = mnist_ds.batch(batch_size)
  130. mnist_ds = mnist_ds.repeat(repeat_size)
  131. return mnist_ds
  132. def test_vae_gan():
  133. vae_gan = VaeGan()
  134. net_loss = VaeGanLoss()
  135. optimizer = nn.Adam(params=vae_gan.trainable_params(), learning_rate=0.001)
  136. ds_train = create_dataset(image_path, 128, 1)
  137. net_with_loss = nn.WithLossCell(vae_gan, net_loss)
  138. vi = SVI(net_with_loss=net_with_loss, optimizer=optimizer)
  139. vae_gan = vi.run(train_dataset=ds_train, epochs=5)