Advertisement
UF6

Step III: Synthetic Data Generation with GANs

UF6
Aug 5th, 2024
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.86 KB | Source Code | 0 0
  1. import tensorflow as tf
  2. from tensorflow.keras import layers
  3.  
  4. # Define the generator model
  5. def make_generator_model():
  6.     model = tf.keras.Sequential()
  7.     model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
  8.     model.add(layers.BatchNormalization())
  9.     model.add(layers.LeakyReLU())
  10.     model.add(layers.Reshape((7, 7, 256)))
  11.     model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
  12.     model.add(layers.BatchNormalization())
  13.     model.add(layers.LeakyReLU())
  14.     model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
  15.     model.add(layers.BatchNormalization())
  16.     model.add(layers.LeakyReLU())
  17.     model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
  18.     return model
  19.  
  20. # Define the discriminator model
  21. def make_discriminator_model():
  22.     model = tf.keras.Sequential()
  23.     model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[28, 28, 1]))
  24.     model.add(layers.LeakyReLU())
  25.     model.add(layers.Dropout(0.3))
  26.     model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
  27.     model.add(layers.LeakyReLU())
  28.     model.add(layers.Dropout(0.3))
  29.     model.add(layers.Flatten())
  30.     model.add(layers.Dense(1))
  31.     return model
  32.  
  33. # Loss and optimizer
  34. cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
  35.  
  36. def discriminator_loss(real_output, fake_output):
  37.     real_loss = cross_entropy(tf.ones_like(real_output), real_output)
  38.     fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
  39.     total_loss = real_loss + fake_loss
  40.     return total_loss
  41.  
  42. def generator_loss(fake_output):
  43.     return cross_entropy(tf.ones_like(fake_output), fake_output)
  44.  
  45. generator = make_generator_model()
  46. discriminator = make_discriminator_model()
  47.  
  48. generator_optimizer = tf.keras.optimizers.Adam(1e-4)
  49. discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
  50.  
  51. # Training loop for GAN
  52. @tf.function
  53. def train_step(images):
  54.     noise = tf.random.normal([BATCH_SIZE, noise_dim])
  55.  
  56.     with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
  57.         generated_images = generator(noise, training=True)
  58.  
  59.         real_output = discriminator(images, training=True)
  60.         fake_output = discriminator(generated_images, training=True)
  61.  
  62.         gen_loss = generator_loss(fake_output)
  63.         disc_loss = discriminator_loss(real_output, fake_output)
  64.  
  65.     gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
  66.     gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
  67.  
  68.     generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
  69.     discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
  70.  
  71. # Train the GAN
  72. import glob
  73. import imageio
  74.  
  75. def train(dataset, epochs):
  76.     for epoch in range(epochs):
  77.         for image_batch in dataset:
  78.             train_step(image_batch)
  79.  
  80. # Load and preprocess the single image
  81. img = tf.keras.preprocessing.image.load_img(img_path, color_mode='grayscale', target_size=(28, 28))
  82. img_array = tf.keras.preprocessing.image.img_to_array(img)
  83. img_array = (img_array - 127.5) / 127.5
  84. img_array = img_array.reshape((1, 28, 28, 1))
  85.  
  86. # Create a dataset from the single image
  87. dataset = tf.data.Dataset.from_tensors(img_array).batch(1)
  88.  
  89. # Train the GAN
  90. EPOCHS = 10000
  91. train(dataset, EPOCHS)
  92.  
  93. # Generate synthetic images
  94. noise = tf.random.normal([16, 100])
  95. generated_images = generator(noise, training=False)
  96.  
  97. # Visualize the generated images
  98. import matplotlib.pyplot as plt
  99. fig = plt.figure(figsize=(4, 4))
  100. for i in range(generated_images.shape[0]):
  101.     plt.subplot(4, 4, i+1)
  102.     plt.imshow(generated_images[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
  103.     plt.axis('off')
  104. plt.show()
  105.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement