{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "rF2x3qooyBTI" }, "source": [ "# Deep Convolutional Generative Adversarial Network" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ITZuApL56Mny" }, "source": [ "This tutorial demonstrates how to generate images of handwritten digits using a [Deep Convolutional Generative Adversarial Network](https://arxiv.org/pdf/1511.06434.pdf) (DCGAN). The code is written using the [Keras Sequential API](https://www.tensorflow.org/guide/keras) with a `tf.GradientTape` training loop." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "2MbKJY38Puy9" }, "source": [ "## What are GANs?\n", "[Generative Adversarial Networks](https://arxiv.org/abs/1406.2661) (GANs) are one of the most interesting ideas in computer science today. Two models are trained simultaneously by an adversarial process. A *generator* (\"the artist\") learns to create images that look real, while a *discriminator* (\"the art critic\") learns to tell real images apart from fakes. \n", "\n", "![A diagram of a generator and discriminator](https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/generative/images/gan1.png?raw=1)\n", "\n", "During training, the *generator* progressively becomes better at creating images that look real, while the *discriminator* becomes better at telling them apart. The process reaches equilibrium when the *discriminator* can no longer distinguish real images from fakes.\n", "\n", "![A second diagram of a generator and discriminator](https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/generative/images/gan2.png?raw=1)\n", "\n", "This notebook demonstrate this process on the MNIST dataset. The following animation shows a series of images produced by the *generator* as it was trained for 50 epochs. The images begin as random noise, and increasingly resemble hand written digits over time.\n", "\n", "To learn more about GANs, we recommend MIT's [Intro to Deep Learning](http://introtodeeplearning.com/) course." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "e1_Y75QXJS6h" }, "source": [ "### Import TensorFlow and other libraries" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "colab": {}, "colab_type": "code", "id": "YfIk2es3hJEd" }, "outputs": [], "source": [ "import glob\n", "import imageio\n", "import tensorflow as tf\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import os\n", "import PIL\n", "import time\n", "\n", "from IPython import display" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "iYn4MdZnKCey" }, "source": [ "### Load and prepare the dataset\n", "\n", "You will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "colab_type": "code", "id": "a4fYMGxGhrna", "outputId": "56f4d4f7-50c9-421a-ed36-3680d06cb01c" }, "outputs": [], "source": [ "BUFFER_SIZE = 60000\n", "BATCH_SIZE = 256\n", "\n", "(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()\n", "train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')\n", "train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]\n", "# Batch and shuffle the data\n", "train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "THY-sZMiQ4UV" }, "source": [ "## Create the models\n", "\n", "Both the generator and discriminator are defined using the [Keras Sequential API](https://www.tensorflow.org/guide/keras#sequential_model)." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "-tEyxE-GMC48" }, "source": [ "### The Generator\n", "\n", "The generator uses `tf.keras.layers.Conv2DTranspose` (upsampling) layers to produce an image from a seed (random noise). Start with a `Dense` layer that takes this seed as input, then upsample several times until you reach the desired image size of 28x28x1. Notice the `tf.keras.layers.LeakyReLU` activation for each layer, except the output layer which uses tanh." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": {}, "colab_type": "code", "id": "6bpTcDqoLWjY" }, "outputs": [], "source": [ "def make_generator_model():\n", " \n", " model = tf.keras.Sequential()\n", " model.add(tf.keras.layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))\n", " model.add(tf.keras.layers.BatchNormalization())\n", " model.add(tf.keras.layers.LeakyReLU())\n", " \n", " model.add(tf.keras.layers.Reshape((7, 7, 256)))\n", " assert model.output_shape == (None, 7, 7, 256) # Note: None is the batch size\n", " \n", " model.add(tf.keras.layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))\n", " assert model.output_shape == (None, 7, 7, 128) \n", " model.add(tf.keras.layers.BatchNormalization())\n", " model.add(tf.keras.layers.LeakyReLU())\n", "\n", " model.add(tf.keras.layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))\n", " assert model.output_shape == (None, 14, 14, 64) \n", " model.add(tf.keras.layers.BatchNormalization())\n", " model.add(tf.keras.layers.LeakyReLU())\n", "\n", " model.add(tf.keras.layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))\n", " assert model.output_shape == (None, 28, 28, 1)\n", " \n", " return model" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "GyWgG09LCSJl" }, "source": [ "Use the (as yet untrained) generator to create an image." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 286 }, "colab_type": "code", "id": "gl7jcC7TdPTG", "outputId": "21b5dd97-d906-4488-fa22-d8d0f8dae144" }, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAP8AAAD8CAYAAAC4nHJkAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvOIA7rQAAGLhJREFUeJztnX9w1OW1xp9DQH6LJCCEX1IpRcBB0WBB6AUURVqUAlNHOlXulBapOqNOO3Nb/OM6dabTdrS3ndY6xasFr1i8CkVGKAgoyA9LCRoQUEExQtIQlN8IgoFz/8jSiZb3edMk7K73fT4zTDb77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jK3S/PXPdLAAfc/eeZP5wd3f0/8mRtDwI4luvJzZmBMsV1J0sD+CaAf0cOjx1Z163IwXHLxTv/NQDedfdd7n4KwDwAvCNEorj7qwAOfO7qCQDmZC7PQe2LJ+sE1pYXuHuVu7+euXwUwNnJ0jk9dmRdOSEX5u8OYE+d3yuQXyO/HcBLZrbJzKbnejHnoEudyUh7AfA2QtknOrk5m3xusnTeHLuGTLxuanTC758Z4e5XARgH4O7Mx9u8xGu/s+VTuqZek5uzxTkmS/+DXB67hk68bmpyYf5KAHUboPXIXJcXuHtl5uc+AH9G/k0frj47JDXzc1+O1/MP8mly87kmSyMPjl0+TbzOhfk3AuhrZl8yswsA3AZgUQ7W8U+YWdvMiRiYWVsANyL/pg8vAjA1c3kqgBdyuJbPkC+Tm0OTpZHjY5d3E6/dPev/AHwdtWf83wPwQC7WEFjXpQA2Z/5ty/XaAPwJtR8DP0XtuZFpAIoArASwE8AKAIV5tLb/Qe005y2oNVpxjtY2ArUf6bcAKMv8+3qujx1ZV06Om3b4CZEoOuEnRKLI/EIkiswvRKLI/EIkiswvRKLI/EIkiswvRKLI/EIkyv8BrjTCDMrPa2MAAAAASUVORK5CYII=\n", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "generator = make_generator_model()\n", "\n", "noise = tf.random.normal([1, 100])\n", "generated_image = generator(noise, training=False)\n", "\n", "plt.imshow(generated_image[0, :, :, 0], cmap='gray')" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "D0IKnaCtg6WE" }, "source": [ "### The Discriminator\n", "\n", "The discriminator is a CNN-based image classifier." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "colab": {}, "colab_type": "code", "id": "dw2tPLmk2pEP" }, "outputs": [], "source": [ "def make_discriminator_model():\n", " \n", " model = tf.keras.Sequential()\n", " model.add(tf.keras.layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[28, 28, 1]))\n", " model.add(tf.keras.layers.LeakyReLU())\n", " model.add(tf.keras.layers.Dropout(0.3))\n", " \n", " model.add(tf.keras.layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))\n", " model.add(tf.keras.layers.LeakyReLU())\n", " model.add(tf.keras.layers.Dropout(0.3))\n", " \n", " model.add(tf.keras.layers.Flatten())\n", " model.add(tf.keras.layers.Dense(1))\n", " \n", " return model" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "QhPneagzCaQv" }, "source": [ "Use the (as yet untrained) discriminator to classify the generated images as real or fake. The model will be trained to output positive values for real images, and negative values for fake images." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "gDkA05NE6QMs", "outputId": "4357cefa-a354-476f-f6f9-24c42788d8c1" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tf.Tensor([[0.00057575]], shape=(1, 1), dtype=float32)\n" ] } ], "source": [ "discriminator = make_discriminator_model()\n", "decision = discriminator(generated_image)\n", "print (decision)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "0FMYgY_mPfTi" }, "source": [ "## Define the loss and optimizers\n", "\n", "Define loss functions and optimizers for both models.\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "colab": {}, "colab_type": "code", "id": "psQfmXxYKU3X" }, "outputs": [], "source": [ "# This method returns a helper function to compute cross entropy loss\n", "cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "PKY_iPSPNWoj" }, "source": [ "### Discriminator loss\n", "\n", "This method quantifies how well the discriminator is able to distinguish real images from fakes. It compares the disciminator's predictions on real images to an array of 1s, and the disciminator's predictions on fake (generated) images to an array of 0s." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "colab": {}, "colab_type": "code", "id": "wkMNfBWlT-PV" }, "outputs": [], "source": [ "def discriminator_loss(real_output, fake_output):\n", " \n", " real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n", " fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n", " total_loss = real_loss + fake_loss\n", " \n", " return total_loss" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Jd-3GCUEiKtv" }, "source": [ "### Generator loss\n", "The generator's loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, we will compare the disciminators decisions on the generated images to an array of 1s." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "colab": {}, "colab_type": "code", "id": "90BIcCKcDMxz" }, "outputs": [], "source": [ "def generator_loss(fake_output):\n", " return cross_entropy(tf.ones_like(fake_output), fake_output)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "MgIc7i0th_Iu" }, "source": [ "The discriminator and the generator optimizers are different since we will train two networks separately." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "colab": {}, "colab_type": "code", "id": "iWCn_PVdEJZ7" }, "outputs": [], "source": [ "generator_optimizer = tf.keras.optimizers.Adam(1e-4)\n", "discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "mWtinsGDPJlV" }, "source": [ "### Save checkpoints\n", "This notebook also demonstrates how to save and restore models, which can be helpful in case a long running training task is interrupted." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "colab": {}, "colab_type": "code", "id": "CA1w-7s2POEy" }, "outputs": [], "source": [ "checkpoint_dir = './training_checkpoints'\n", "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n", "checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n", " discriminator_optimizer=discriminator_optimizer,\n", " generator=generator,\n", " discriminator=discriminator)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Rw1fkAczTQYh" }, "source": [ "## Define the training loop\n", "\n" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "colab": {}, "colab_type": "code", "id": "NS2GWywBbAWo" }, "outputs": [], "source": [ "EPOCHS = 50\n", "noise_dim = 100\n", "num_examples_to_generate = 16\n", "\n", "# We will reuse this seed overtime (so it's easier)\n", "# to visualize progress in the animated GIF)\n", "seed = tf.random.normal([num_examples_to_generate, noise_dim])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "jylSonrqSWfi" }, "source": [ "The training loop begins with generator receiving a random seed as input. That seed is used to produce an image. The discriminator is then used to classify real images (drawn from the training set) and fakes images (produced by the generator). The loss is calculated for each of these models, and the gradients are used to update the generator and discriminator." ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "colab": {}, "colab_type": "code", "id": "3t5ibNo05jCB" }, "outputs": [], "source": [ "# Notice the use of `tf.function`\n", "# This annotation causes the function to be \"compiled\".\n", "@tf.function\n", "def train_step(images):\n", " \n", " noise = tf.random.normal([BATCH_SIZE, noise_dim])\n", "\n", " with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n", " generated_images = generator(noise, training=True)\n", " real_output = discriminator(images, training=True)\n", " fake_output = discriminator(generated_images, training=True)\n", " gen_loss = generator_loss(fake_output)\n", " disc_loss = discriminator_loss(real_output, fake_output)\n", "\n", " gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)\n", " gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)\n", "\n", " generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))\n", " discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "colab": {}, "colab_type": "code", "id": "2M7LmLtGEMQJ" }, "outputs": [], "source": [ "def train(dataset, epochs): \n", " \n", " for epoch in range(epochs):\n", " start = time.time()\n", " for image_batch in dataset:\n", " train_step(image_batch)\n", " \n", " # Produce images for the GIF as we go\n", " display.clear_output(wait=True)\n", " generate_and_save_images(generator, epoch + 1, seed)\n", " \n", " # Save the model every 15 epochs\n", " if (epoch + 1) % 15 == 0:\n", " checkpoint.save(file_prefix = checkpoint_prefix)\n", " \n", " print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))\n", " # Generate after the final epoch\n", " display.clear_output(wait=True)\n", " generate_and_save_images(generator, epochs, seed)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "2aFF7Hk3XdeW" }, "source": [ "**Generate and save images**\n", "\n" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "colab": {}, "colab_type": "code", "id": "RmdVsmvhPxyy" }, "outputs": [], "source": [ "def generate_and_save_images(model, epoch, test_input):\n", " # Notice `training` is set to False. \n", " # This is so all layers run in inference mode (batchnorm).\n", " predictions = model(test_input, training=False)\n", " \n", " fig = plt.figure(figsize=(4,4))\n", " for i in range(predictions.shape[0]):\n", " plt.subplot(4, 4, i+1)\n", " plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')\n", " plt.axis('off')\n", " plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))\n", " plt.show()" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "dZrd4CdjR-Fp" }, "source": [ "## Train the model\n", "Call the `train()` method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It's important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).\n", "\n", "At the beginning of the training, the generated images look like random noise. As training progresses, the generated digits will look increasingly real. After about 50 epochs, they resemble MNIST digits. This may take about one minute / epoch with the default settings on Colab." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 302 }, "colab_type": "code", "id": "Ly3UN0SLLY2l", "outputId": "c81addbf-5710-4c91-fb74-5a6c49128920" }, "outputs": [], "source": [ "%%time\n", "train(train_dataset, EPOCHS)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "rfM4YcPVPkNO" }, "source": [ "Restore the latest checkpoint." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "XhXsd0srPo8c", "outputId": "e6faab30-5dcc-4eeb-96bc-a4df9da93d01" }, "outputs": [], "source": [ "checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "P4M_vIbUi7c0" }, "source": [ "## Create a GIF\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "WfO5wCdclHGL" }, "outputs": [], "source": [ "# Display a single image using the epoch number\n", "def display_image(epoch_no):\n", " return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 305 }, "colab_type": "code", "id": "5x3q9_Oe5q0A", "outputId": "be237f86-94b8-4a7d-8e5f-c5813797605f" }, "outputs": [], "source": [ "display_image(EPOCHS)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "NywiH3nL8guF" }, "source": [ "Use `imageio` to create an animated gif using the images saved during training." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "IGKQgENQ8lEI" }, "outputs": [], "source": [ "with imageio.get_writer('dcgan.gif', mode='I') as writer:\n", " filenames = glob.glob('image*.png')\n", " filenames = sorted(filenames)\n", " last = -1\n", " for i,filename in enumerate(filenames):\n", " frame = 2*(i**0.5)\n", " if round(frame) > round(last):\n", " last = frame\n", " else:\n", " continue\n", " image = imageio.imread(filename)\n", " writer.append_data(image)\n", " image = imageio.imread(filename)\n", " writer.append_data(image)\n", " \n", "# A hack to display the GIF inside this notebook\n", "os.rename('dcgan.gif', 'dcgan.gif.png')" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "cGhC3-fMWSwl" }, "source": [ "Display the animated gif with all the mages generated during the training of GANs." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 305 }, "colab_type": "code", "id": "uV0yiKpzNP1b", "outputId": "b67591f5-8ee0-4a4d-811f-ef47a3e867a4" }, "outputs": [], "source": [ "display.Image(filename=\"dcgan.gif.png\")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "k6qC-SbjK0yW" }, "source": [ "## Next steps\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "xjjkT9KAK6H7" }, "source": [ "This tutorial has shown the complete code necessary to write and train a GAN. As a next step, you might like to experiment with a different dataset, for example the Large-scale Celeb Faces Attributes (CelebA) dataset [available on Kaggle](https://www.kaggle.com/jessicali9530/celeba-dataset/home). To learn more about GANs we recommend the [NIPS 2016 Tutorial: Generative Adversarial Networks](https://arxiv.org/abs/1701.00160).\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [], "name": "dcgan.ipynb", "provenance": [], "toc_visible": true, "version": "0.3.2" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 1 }