Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tensorflow as tf
- from tensorflow.keras import layers
- # Define the generator model
- def make_generator_model():
- model = tf.keras.Sequential()
- model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
- model.add(layers.BatchNormalization())
- model.add(layers.LeakyReLU())
- model.add(layers.Reshape((7, 7, 256)))
- model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
- model.add(layers.BatchNormalization())
- model.add(layers.LeakyReLU())
- model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
- model.add(layers.BatchNormalization())
- model.add(layers.LeakyReLU())
- model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
- return model
- # Define the discriminator model
- def make_discriminator_model():
- model = tf.keras.Sequential()
- model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[28, 28, 1]))
- model.add(layers.LeakyReLU())
- model.add(layers.Dropout(0.3))
- model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
- model.add(layers.LeakyReLU())
- model.add(layers.Dropout(0.3))
- model.add(layers.Flatten())
- model.add(layers.Dense(1))
- return model
- # Loss and optimizer
- cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
- def discriminator_loss(real_output, fake_output):
- real_loss = cross_entropy(tf.ones_like(real_output), real_output)
- fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
- total_loss = real_loss + fake_loss
- return total_loss
- def generator_loss(fake_output):
- return cross_entropy(tf.ones_like(fake_output), fake_output)
- generator = make_generator_model()
- discriminator = make_discriminator_model()
- generator_optimizer = tf.keras.optimizers.Adam(1e-4)
- discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
- # Training loop for GAN
- @tf.function
- def train_step(images):
- noise = tf.random.normal([BATCH_SIZE, noise_dim])
- with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
- generated_images = generator(noise, training=True)
- real_output = discriminator(images, training=True)
- fake_output = discriminator(generated_images, training=True)
- gen_loss = generator_loss(fake_output)
- disc_loss = discriminator_loss(real_output, fake_output)
- gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
- gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
- generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
- discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
- # Train the GAN
- import glob
- import imageio
- def train(dataset, epochs):
- for epoch in range(epochs):
- for image_batch in dataset:
- train_step(image_batch)
- # Load and preprocess the single image
- img = tf.keras.preprocessing.image.load_img(img_path, color_mode='grayscale', target_size=(28, 28))
- img_array = tf.keras.preprocessing.image.img_to_array(img)
- img_array = (img_array - 127.5) / 127.5
- img_array = img_array.reshape((1, 28, 28, 1))
- # Create a dataset from the single image
- dataset = tf.data.Dataset.from_tensors(img_array).batch(1)
- # Train the GAN
- EPOCHS = 10000
- train(dataset, EPOCHS)
- # Generate synthetic images
- noise = tf.random.normal([16, 100])
- generated_images = generator(noise, training=False)
- # Visualize the generated images
- import matplotlib.pyplot as plt
- fig = plt.figure(figsize=(4, 4))
- for i in range(generated_images.shape[0]):
- plt.subplot(4, 4, i+1)
- plt.imshow(generated_images[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
- plt.axis('off')
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement