Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.81 KB | None | 0 0
  1. class GAN():
  2. def __init__(self):
  3. self.img_rows = 28
  4. self.img_cols = 28
  5. self.channels = 1
  6. self.img_shape = (self.img_rows, self.img_cols, self.channels)
  7.  
  8. optimizer = Adam(0.0002, 0.5)
  9.  
  10. # Build and compile the discriminator
  11. self.discriminator = self.build_discriminator()
  12. self.discriminator.compile(loss='binary_crossentropy',
  13. optimizer=optimizer,
  14. metrics=['accuracy'])
  15.  
  16. # Build and compile the generator
  17. self.generator = self.build_generator()
  18. self.generator.compile(loss='binary_crossentropy', optimizer=optimizer)
  19.  
  20. # The generator takes noise as input and generated imgs
  21. z = Input(shape=(100,))
  22. img = self.generator(z)
  23.  
  24. # For the combined model we will only train the generator
  25. self.discriminator.trainable = False
  26.  
  27. # The valid takes generated images as input and determines validity
  28. valid = self.discriminator(img)
  29.  
  30. # The combined model (stacked generator and discriminator) takes
  31. # noise as input => generates images => determines validity
  32. self.combined = Model(z, valid)
  33. self.combined.compile(loss='binary_crossentropy', optimizer=optimizer)
  34.  
  35. def build_generator(self):
  36.  
  37. noise_shape = (100,)
  38.  
  39. model = Sequential()
  40.  
  41. model.add(Dense(256, input_shape=noise_shape))
  42. model.add(LeakyReLU(alpha=0.2))
  43. model.add(BatchNormalization(momentum=0.8))
  44. model.add(Dense(512))
  45. model.add(LeakyReLU(alpha=0.2))
  46. model.add(BatchNormalization(momentum=0.8))
  47. model.add(Dense(1024))
  48. model.add(LeakyReLU(alpha=0.2))
  49. model.add(BatchNormalization(momentum=0.8))
  50. model.add(Dense(np.prod(self.img_shape), activation='tanh'))
  51. model.add(Reshape(self.img_shape))
  52.  
  53. model.summary()
  54.  
  55. noise = Input(shape=noise_shape)
  56. img = model(noise)
  57.  
  58. return Model(noise, img)
  59.  
  60. def build_discriminator(self):
  61.  
  62. img_shape = (self.img_rows, self.img_cols, self.channels)
  63.  
  64. model = Sequential()
  65.  
  66. model.add(Flatten(input_shape=img_shape))
  67. model.add(Dense(512))
  68. model.add(LeakyReLU(alpha=0.2))
  69. model.add(Dense(256))
  70. model.add(LeakyReLU(alpha=0.2))
  71. model.add(Dense(1, activation='sigmoid'))
  72. model.summary()
  73.  
  74. img = Input(shape=img_shape)
  75. validity = model(img)
  76.  
  77. return Model(img, validity)
  78.  
  79. def train(self, epochs, batch_size=128, save_interval=50):
  80.  
  81. # Load the dataset
  82. (X_train, _), (_, _) = mnist.load_data()
  83.  
  84. # Rescale -1 to 1
  85. X_train = (X_train.astype(np.float32) - 127.5) / 127.5
  86. X_train = np.expand_dims(X_train, axis=3)
  87.  
  88. half_batch = int(batch_size / 2)
  89.  
  90. for epoch in range(epochs):
  91.  
  92. # ---------------------
  93. # Train Discriminator
  94. # ---------------------
  95.  
  96. # Select a random half batch of images
  97. idx = np.random.randint(0, X_train.shape[0], half_batch)
  98. imgs = X_train[idx]
  99.  
  100. noise = np.random.normal(0, 1, (half_batch, 100))
  101.  
  102. # Generate a half batch of new images
  103. gen_imgs = self.generator.predict(noise)
  104.  
  105. # Train the discriminator
  106. d_loss_real = self.discriminator.train_on_batch(imgs, np.ones((half_batch, 1)))
  107. d_loss_fake = self.discriminator.train_on_batch(gen_imgs, np.zeros((half_batch, 1)))
  108. d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
  109.  
  110.  
  111. # ---------------------
  112. # Train Generator
  113. # ---------------------
  114.  
  115. noise = np.random.normal(0, 1, (batch_size, 100))
  116.  
  117. # The generator wants the discriminator to label the generated samples
  118. # as valid (ones)
  119. valid_y = np.array([1] * batch_size)
  120.  
  121. # Train the generator
  122. g_loss = self.combined.train_on_batch(noise, valid_y)
  123.  
  124. # Plot the progress
  125. print ("%d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (epoch, d_loss[0], 100*d_loss[1], g_loss))
  126.  
  127. # If at save interval => save generated image samples
  128. if epoch % save_interval == 0:
  129. self.save_imgs(epoch)
  130.  
  131. def save_imgs(self, epoch):
  132. r, c = 5, 5
  133. noise = np.random.normal(0, 1, (r * c, 100))
  134. gen_imgs = self.generator.predict(noise)
  135.  
  136. # Rescale images 0 - 1
  137. gen_imgs = 0.5 * gen_imgs + 0.5
  138.  
  139. fig, axs = plt.subplots(r, c)
  140. cnt = 0
  141. for i in range(r):
  142. for j in range(c):
  143. axs[i,j].imshow(gen_imgs[cnt, :,:,0], cmap='gray')
  144. axs[i,j].axis('off')
  145. cnt += 1
  146. fig.savefig("gan/images/mnist_%d.png" % epoch)
  147. plt.close()
  148.  
  149.  
  150. if __name__ == '__main__':
  151. gan = GAN()
  152. gan.train(epochs=30000, batch_size=32, save_interval=200)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement