You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
face_generation_gan/dlnd_face_generation.ipynb

797 lines
237 KiB
Plaintext

7 years ago
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Face Generation\n",
"In this project, you'll use generative adversarial networks to generate new images of faces.\n",
"### Get the Data\n",
"You'll be using two datasets in this project:\n",
"- MNIST\n",
"- CelebA\n",
"\n",
"Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner.\n",
"\n",
"If you're using [FloydHub](https://www.floydhub.com/), set `data_dir` to \"/input\" and use the [FloydHub data ID](http://docs.floydhub.com/home/using_datasets/) \"R5KrjnANiKVhLWAkpXhNBe\"."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
7 years ago
"Found mnist Data\n",
"Found celeba Data\n"
7 years ago
]
}
],
"source": [
"data_dir = './data'\n",
"\n",
"# FloydHub - Use with data ID \"R5KrjnANiKVhLWAkpXhNBe\"\n",
"#data_dir = '/input'\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"import helper\n",
"\n",
"helper.download_extract('mnist', data_dir)\n",
"helper.download_extract('celeba', data_dir)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Explore the Data\n",
"### MNIST\n",
"As you're aware, the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset contains images of handwritten digits. You can view the first number of examples by changing `show_n_images`. "
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
7 years ago
"<matplotlib.image.AxesImage at 0x7f6293d214a8>"
7 years ago
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAQQAAAD/CAYAAAAXKqhkA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1FR6PJ8fP4sGa3cp2oKMUpFSr1XA4HDh27Bi+/e1vY2pqCgDwxRdfsGgH78LQ93iCTyqV\ngslkQmVlJc6dO4fz58/jyJEj2NzcxOjoKFZXVxEMBvdlcW337PmINLQzl5WV4fjx4zh06BDq6uoA\nALOzs7h9+zbu3r2LycnJHDLQdsIzN/O1QWrV8SArAYMEqlGoN5vNIhgMYmRkBNeuXUMymURxcTF8\nPh/Gx8fx0UcfwePxwOVy4ciRI5DL5Tk4D4/i71byhcX5jUylUsFiscDlcqG5uRltbW1wu90s8iEI\nQs6Ov7y8jM3NTUbAI9fT5XLh9OnTMBgMUKlU6Ovr2xN4+1IphKcRiLRaLcrLy2EwGACA+ee84tiO\n4LMT7S8FA3mhgSGMw2Qy4ezZs2hra4NcLofb7UZ1dTWSySRzERQKBXueeDzOXuNxEbfbjTfffBPf\n/va30draCpVKhQcPHuC3v/0tPvjgA3g8HmbKFlop8KxJWmTEiuMnuEKhgMFgQH19Pd566y3U1tYy\nhTY+Po5PPvkEs7OzzCp6Fk5DFpI0LCnFCPi+krabFgl/v1gshsXFRfzyl7/EBx98ALPZjGg0Cp/P\nh0gkAovFAqPRCK1WmxPeI3eIQnk76TepQuK5EDQnaVd3Op145ZVXcPz4cZw8eRIlJSVIp9Ms5Dk7\nOwuv14uNjQ2Ew2GmEGj+kIV58eJFHDp0CDabDW63G2VlZZienkYgENjFqL9kCgHIZbvxMedsNsvY\nZsRDIFO8EMIrAmmYkLc
"text/plain": [
7 years ago
"<matplotlib.figure.Figure at 0x7f6293da3748>"
7 years ago
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"show_n_images = 25\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"%matplotlib inline\n",
"import os\n",
"from glob import glob\n",
"from matplotlib import pyplot\n",
"\n",
"mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')\n",
"pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### CelebA\n",
"The [CelebFaces Attributes Dataset (CelebA)](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing `show_n_images`."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
7 years ago
"<matplotlib.image.AxesImage at 0x7f6293c4b518>"
7 years ago
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAQQAAAD/CAYAAAAXKqhkAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsvcmOZFmSpvfJme69Otnk7uERkUNldpKFZoMDuCAaBFck\nF9wQ5LL5DtzzAfo5uOcjEHyFWhEgwEY3UJ2sITPCwwcz0+EOZxAu5KpFVKMyuhcViFq4ABrm5qGm\nqnbvOf8R+f9fxEVV+Ryf43N8DgD3c3+Az/E5Psc/nvgMCJ/jc3yOl/gMCJ/jc3yOl/gMCJ/jc3yO\nl/gMCJ/jc3yOl/gMCJ/jc3yOl/jJAEFE/gcR+Vci8q9F5H/7qd7nc3yOz/EPF/JT+BBExAH/Gvjv\ngD8AfwH8C1X9V//gb/Y5Psfn+AeLnypD+K+Af6Oq/5+qZuD/AP6nn+i9Psfn+Bz/QPFTAcLXwF//\n4Pu/Wf/uc3yOz/GPOMJP9Lry9/zd36lNROSzZ/pzfI6fKVT179ujPxkg/A3wqx98/wuMS/g78T//\n9/8N/+N/+88ZNgPiPPNc+eO3H3g+jexu7ni+THzz7gPfffMt5+cTVEVCwIUAIVAVSoMQAikIQ4Su\ni3R9R+x65mnhdLpwHhfm3KjN0XAgDvGOP/7h3/Ln//S/ZJxmzpeR82Wki5EUAwKkmOj7jhgjW3n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kAI4tFaeXy+8O7DM++fzzjx\nBHF4zcRNx8O252HfcbOLdIMjdnbxxEcQI8ymcWaZFvKU0dLQaulrzgvTMnM/9Nz0HZsQ+NsPT3zz\nfOZpKdRlYnSOeS7UDK7
"text/plain": [
7 years ago
"<matplotlib.figure.Figure at 0x7f62dc1a4780>"
7 years ago
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"show_n_images = 25\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')\n",
"pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Preprocess the Data\n",
"Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.\n",
"\n",
"The MNIST images are black and white images with a single [color channel](https://en.wikipedia.org/wiki/Channel_(digital_image%29) while the CelebA images have [3 color channels (RGB color channel)](https://en.wikipedia.org/wiki/Channel_(digital_image%29#RGB_Images).\n",
"## Build the Neural Network\n",
"You'll build the components necessary to build a GANs by implementing the following functions below:\n",
"- `model_inputs`\n",
"- `discriminator`\n",
"- `generator`\n",
"- `model_loss`\n",
"- `model_opt`\n",
"- `train`\n",
"\n",
"### Check the Version of TensorFlow and Access to GPU\n",
"This will check to make sure you have the correct version of TensorFlow and access to a GPU"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"TensorFlow Version: 1.3.0\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel_launcher.py:14: UserWarning: No GPU found. Please use a GPU to train your neural network.\n",
" \n"
]
}
],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"from distutils.version import LooseVersion\n",
"import warnings\n",
"import tensorflow as tf\n",
"\n",
"# Check TensorFlow Version\n",
"assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)\n",
"print('TensorFlow Version: {}'.format(tf.__version__))\n",
"\n",
"# Check for a GPU\n",
"if not tf.test.gpu_device_name():\n",
" warnings.warn('No GPU found. Please use a GPU to train your neural network.')\n",
"else:\n",
" print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Input\n",
"Implement the `model_inputs` function to create TF Placeholders for the Neural Network. It should create the following placeholders:\n",
"- Real input images placeholder with rank 4 using `image_width`, `image_height`, and `image_channels`.\n",
"- Z input placeholder with rank 2 using `z_dim`.\n",
"- Learning rate placeholder with rank 0.\n",
"\n",
"Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)"
]
},
{
"cell_type": "code",
7 years ago
"execution_count": 5,
"metadata": {
"scrolled": true
},
7 years ago
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ERROR:tensorflow:==================================\n",
"Object was never used (type <class 'tensorflow.python.framework.ops.Operation'>):\n",
"<tf.Operation 'assert_rank_2/Assert/Assert' type=Assert>\n",
"If you want to mark it as used call its \"mark_used()\" method.\n",
"It was originally created here:\n",
7 years ago
"['File \"/home/spike/.pyenv/versions/3.5.1/lib/python3.5/runpy.py\", line 170, in _run_module_as_main\\n \"__main__\", mod_spec)', 'File \"/home/spike/.pyenv/versions/3.5.1/lib/python3.5/runpy.py\", line 85, in _run_code\\n exec(code, run_globals)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel_launcher.py\", line 16, in <module>\\n app.launch_new_instance()', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/traitlets/config/application.py\", line 658, in launch_instance\\n app.start()', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel/kernelapp.py\", line 477, in start\\n ioloop.IOLoop.instance().start()', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/zmq/eventloop/ioloop.py\", line 177, in start\\n super(ZMQIOLoop, self).start()', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/tornado/ioloop.py\", line 888, in start\\n handler_func(fd_obj, events)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/tornado/stack_context.py\", line 277, in null_wrapper\\n return fn(*args, **kwargs)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py\", line 440, in _handle_events\\n self._handle_recv()', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py\", line 472, in _handle_recv\\n self._run_callback(callback, msg)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py\", line 414, in _run_callback\\n callback(*args, **kwargs)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/tornado/stack_context.py\", line 277, in null_wrapper\\n return fn(*args, **kwargs)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel/kernelbase.py\", line 283, in dispatcher\\n return self.dispatch_shell(stream, msg)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel/kernelbase.py\", line 235, in dispatch_shell\\n handler(stream, idents, msg)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel/kernelbase.py\", line 399, in execute_request\\n user_expressions, allow_stdin)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel/ipkernel.py\", line 196, in do_execute\\n res = shell.run_cell(code, store_history=store_history, silent=silent)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel/zmqshell.py\", line 533, in run_cell\\n return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/IPython/core/interactiveshell.py\", line 2683, in run_cell\\n interactivity=interactivity, compiler=compiler, result=result)', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/IPython/core/interactiveshell.py\", line 2793, in run_ast_nodes\\n if self.run_code(code, result):', 'File \"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/IPython/core/interactiveshell.py\", line 2847, in run_code\\n exec(code_obj, self.user_global_ns, self.user_ns)', 'File \"<ipython-input-5-60e8f0e9d266>\", line 22, in <module>\\n tests.test_model_inputs(model_inputs)', 'File \"/home/spike/ml/udacity/nd101/project5/problem_unittests.py\", line 12, in func_wrapper\\n result = func(*args)', 'File \"/home/spike/ml/udacity/nd101/project5/problem_unittests.py\", line 68, in test_model_inputs\\n _check_input(learn_rate, [], \\'Learning Rate\\')', 'File \"/home/spike/ml/udacity/nd101/project5/problem_unittests.py\", line 34, in _check_input\\n _assert_tensor_shape(tensor, shape, \\'Real Input\\')', 'File \"/home/spike/ml/udacity/nd101/project5/problem_unittests.py\", line 20, in _assert_tensor_shape\\n assert tf.assert_ran
7 years ago
"==================================\n",
"Tests Passed\n"
]
}
],
"source": [
"import problem_unittests as tests\n",
"\n",
"def model_inputs(image_width, image_height, image_channels, z_dim):\n",
" \"\"\"\n",
" Create the model inputs\n",
" :param image_width: The input image width\n",
" :param image_height: The input image height\n",
" :param image_channels: The number of image channels\n",
" :param z_dim: The dimension of Z\n",
" :return: Tuple of (tensor of real input images, tensor of z data, learning rate)\n",
" \"\"\"\n",
" inputs_real = tf.placeholder(tf.float32, (None, image_width, image_height, image_channels), name='inputs_real')\n",
7 years ago
" inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='inputs_z')\n",
" learn_r = tf.placeholder(tf.float32, name='lr')\n",
7 years ago
"\n",
" return inputs_real, inputs_z, learn_r\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_model_inputs(model_inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Hyperparameters"
]
},
{
"cell_type": "code",
7 years ago
"execution_count": 6,
7 years ago
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
7 years ago
"alpha = 0.2 # for leaky relu\n",
"print_every = 10\n",
"show_every = 10 #change to 100"
7 years ago
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Discriminator\n",
"Implement `discriminator` to create a discriminator neural network that discriminates on `images`. This function should be able to reuse the variables in the neural network. Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of \"discriminator\" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator)."
]
},
{
"cell_type": "code",
7 years ago
"execution_count": 7,
7 years ago
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def discriminator(images, reuse=False):\n",
" \"\"\"\n",
" Create the discriminator network\n",
" :param images: Tensor of input image(s)\n",
" :param reuse: Boolean if the weights should be reused\n",
" :return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)\n",
" \"\"\"\n",
" with tf.variable_scope('discriminator', reuse=reuse):\n",
" \n",
" # Input layer is 28x28x3\n",
" x1 = tf.layers.conv2d(images, 32, 5, strides=1, padding='valid')\n",
" relu1 = tf.maximum(alpha * x1, x1)\n",
" #print(relu1)\n",
" # 24x24x32\n",
" \n",
" x2 = tf.layers.conv2d(relu1, 64, 7, strides=1, padding='valid')\n",
" bn2 = tf.layers.batch_normalization(x2, training=True)\n",
" relu2 = tf.maximum(alpha * bn2, bn2)\n",
" #print(relu2)\n",
" # 18x18x64\n",
" \n",
" x3 = tf.layers.conv2d(relu2, 128, 7, strides=1, padding='valid')\n",
" bn3 = tf.layers.batch_normalization(x3, training=True)\n",
" relu3 = tf.maximum(alpha * bn3, bn3)\n",
" #print(relu3)\n",
" # 12x12x128\n",
" \n",
" x4 = tf.layers.conv2d(relu3, 256, 5, strides=2, padding='valid')\n",
" bn4 = tf.layers.batch_normalization(x4, training=True)\n",
" relu4 = tf.maximum(alpha * bn4, bn4)\n",
" #print(relu4)\n",
" # 4x4x256\n",
"\n",
" # Flatten it\n",
" flat = tf.reshape(relu4, (-1, 4*4*256))\n",
" logits = tf.layers.dense(flat, 1)\n",
" out = tf.sigmoid(logits)\n",
" \n",
" \n",
"\n",
" return out, logits\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_discriminator(discriminator, tf)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Generator\n",
"Implement `generator` to generate an image using `z`. This function should be able to reuse the variables in the neural network. Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of \"generator\" to allow the variables to be reused. The function should return the generated 28 x 28 x `out_channel_dim` images."
]
},
{
"cell_type": "code",
7 years ago
"execution_count": 8,
7 years ago
"metadata": {},
7 years ago
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
7 years ago
"source": [
"def generator(z, out_channel_dim, is_train=True):\n",
" \"\"\"\n",
" Create the generator network\n",
" :param z: Input z\n",
" :param out_channel_dim: The number of channels in the output image\n",
" :param is_train: Boolean if generator is being used for training\n",
" :return: The tensor output of the generator\n",
" \"\"\"\n",
" \n",
7 years ago
" \n",
" with tf.variable_scope('generator', reuse=not is_train):\n",
" \n",
" # First fully connected layer\n",
" x1 = tf.layers.dense(z, 4*4*512)\n",
" \n",
" # Reshape it to start the convolutional stack\n",
" x1 = tf.reshape(x1, (-1, 4, 4, 512))\n",
" x1 = tf.layers.batch_normalization(x1, training=is_train)\n",
" x1 = tf.maximum(alpha * x1, x1)\n",
" #print(x1)\n",
" # 4x4x512 now\n",
" \n",
" x2 = tf.layers.conv2d_transpose(x1, 256, 5, strides=2, padding='same')\n",
" x2 = tf.layers.batch_normalization(x2, training=is_train)\n",
" x2 = tf.maximum(alpha * x2, x2)\n",
" #print(x2)\n",
" # 8x8x256 now\n",
" \n",
" x3 = tf.layers.conv2d_transpose(x2, 128, 5, strides=2, padding='same')\n",
" x3 = tf.layers.batch_normalization(x3, training=is_train)\n",
" x3 = tf.maximum(alpha * x3, x3)\n",
" #print(x3)\n",
" # 16x16x128 now\n",
" \n",
" # Output layer\n",
" logits = tf.layers.conv2d_transpose(x3, out_channel_dim, 13, strides=1, padding='valid')\n",
" #print(logits)\n",
" # 28x28x(channels) now\n",
" \n",
" out = tf.tanh(logits)\n",
" \n",
" return out\n",
7 years ago
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_generator(generator, tf)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Loss\n",
"Implement `model_loss` to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:\n",
"- `discriminator(images, reuse=False)`\n",
"- `generator(z, out_channel_dim, is_train=True)`"
]
},
{
"cell_type": "code",
7 years ago
"execution_count": 9,
7 years ago
"metadata": {},
7 years ago
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
7 years ago
"source": [
"def model_loss(input_real, input_z, out_channel_dim):\n",
" \"\"\"\n",
" Get the loss for the discriminator and generator\n",
" :param input_real: Images from the real dataset\n",
" :param input_z: Z input\n",
" :param out_channel_dim: The number of channels in the output image\n",
" :return: A tuple of (discriminator loss, generator loss)\n",
" \"\"\"\n",
7 years ago
" g_model = generator(input_z, out_channel_dim)\n",
" d_model_real, d_logits_real = discriminator(input_real)\n",
" d_model_fake, d_logits_fake = discriminator(g_model, reuse=True)\n",
"\n",
" d_loss_real = tf.reduce_mean(\n",
" tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_model_real)))\n",
" d_loss_fake = tf.reduce_mean(\n",
" tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_model_fake)))\n",
" g_loss = tf.reduce_mean(\n",
" tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_model_fake)))\n",
"\n",
" d_loss = d_loss_real + d_loss_fake\n",
7 years ago
" \n",
7 years ago
" return d_loss, g_loss\n",
7 years ago
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_model_loss(model_loss)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Optimization\n",
"Implement `model_opt` to create the optimization operations for the GANs. Use [`tf.trainable_variables`](https://www.tensorflow.org/api_docs/python/tf/trainable_variables) to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation)."
]
},
{
"cell_type": "code",
7 years ago
"execution_count": 10,
7 years ago
"metadata": {},
7 years ago
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
7 years ago
"source": [
"def model_opt(d_loss, g_loss, learning_rate, beta1):\n",
" \"\"\"\n",
" Get optimization operations\n",
" :param d_loss: Discriminator loss Tensor\n",
" :param g_loss: Generator loss Tensor\n",
" :param learning_rate: Learning Rate Placeholder\n",
" :param beta1: The exponential decay rate for the 1st moment in the optimizer\n",
" :return: A tuple of (discriminator training operation, generator training operation)\n",
" \"\"\"\n",
" \n",
7 years ago
" # Get weights and bias to update\n",
" t_vars = tf.trainable_variables()\n",
" d_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n",
" g_vars = [var for var in t_vars if var.name.startswith('generator')]\n",
"\n",
" # Optimize\n",
" with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n",
" d_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars)\n",
" g_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(g_loss, var_list=g_vars)\n",
"\n",
" \n",
" return d_train_opt, g_train_opt\n",
7 years ago
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_model_opt(model_opt, tf)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Neural Network Training\n",
"### Show Output\n",
"Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training."
]
},
{
"cell_type": "code",
7 years ago
"execution_count": 11,
7 years ago
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"import numpy as np\n",
"\n",
"def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):\n",
" \"\"\"\n",
" Show example output for the generator\n",
" :param sess: TensorFlow session\n",
" :param n_images: Number of Images to display\n",
" :param input_z: Input Z Tensor\n",
" :param out_channel_dim: The number of channels in the output image\n",
" :param image_mode: The mode to use for images (\"RGB\" or \"L\")\n",
" \"\"\"\n",
" cmap = None if image_mode == 'RGB' else 'gray'\n",
" z_dim = input_z.get_shape().as_list()[-1]\n",
" example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])\n",
"\n",
" samples = sess.run(\n",
" generator(input_z, out_channel_dim, False),\n",
" feed_dict={input_z: example_z})\n",
"\n",
" images_grid = helper.images_square_grid(samples, image_mode)\n",
" pyplot.imshow(images_grid, cmap=cmap)\n",
" pyplot.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Train\n",
"Implement `train` to build and train the GANs. Use the following functions you implemented:\n",
"- `model_inputs(image_width, image_height, image_channels, z_dim)`\n",
"- `model_loss(input_real, input_z, out_channel_dim)`\n",
"- `model_opt(d_loss, g_loss, learning_rate, beta1)`\n",
"\n",
"Use the `show_generator_output` to show `generator` output while you train. Running `show_generator_output` for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the `generator` output every 100 batches."
]
},
{
"cell_type": "code",
7 years ago
"execution_count": 15,
7 years ago
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
7 years ago
"from IPython.core.debugger import Tracer\n",
"\n",
7 years ago
"def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):\n",
" \"\"\"\n",
" Train the GAN\n",
" :param epoch_count: Number of epochs\n",
" :param batch_size: Batch Size\n",
" :param z_dim: Z dimension\n",
" :param learning_rate: Learning Rate\n",
" :param beta1: The exponential decay rate for the 1st moment in the optimizer\n",
" :param get_batches: Function to get batches\n",
" :param data_shape: Shape of the data\n",
" :param data_image_mode: The image mode to use for images (\"RGB\" or \"L\")\n",
" \"\"\"\n",
" \n",
7 years ago
" # create input placeholders\n",
" #print(data_shape)\n",
" image_shape = data_shape[1:]\n",
" #print(image_shape)\n",
" out_channel_dim = image_shape[-1]\n",
" #print(out_channel_dim)\n",
" \n",
" inputs_real, inputs_z, lr_rate = model_inputs(*image_shape, z_dim)\n",
" print(inputs_real)\n",
" d_loss, g_loss = model_loss(inputs_real, inputs_z, out_channel_dim)\n",
" d_train_opt, g_train_opt = model_opt(d_loss, g_loss, lr_rate, beta1)\n",
" #print(inputs_real)\n",
" \n",
" #t_vars = tf.trainable_variables()\n",
" #g_vars = [var for var in t_vars if var.name.startswith('generator')]\n",
" #saver = tf.train.Saver(var_list=g_vars)\n",
" \n",
" def scale(x, target_range=(-1,1)):\n",
" min, max = target_range\n",
" \n",
" # One liner, but too expensive \n",
" #x = (x - x.min()) * (max - min) / (x.max() - x.min()) + min\n",
" \n",
" # First scale to [0,1]\n",
" x = ((x - x.min())/(x.max() - x.min()))\n",
7 years ago
" \n",
7 years ago
" # Then scale to target_range\n",
" min, max = target_range\n",
" x = x * (max - min) + min\n",
" return x\n",
" \n",
" \n",
" steps = 0\n",
7 years ago
" with tf.Session() as sess:\n",
" sess.run(tf.global_variables_initializer())\n",
" for epoch_i in range(epoch_count):\n",
" for batch_images in get_batches(batch_size):\n",
7 years ago
" steps += 1\n",
" \n",
" #1 Scale real images to [-1,1] range since that is also the generator output scale\n",
" batch_images = scale(batch_images, target_range=(-1,1))\n",
" \n",
" \n",
" #3 Sample random noise for generator\n",
" batch_z = np.random.uniform(-1,1, size=(batch_size, z_dim))\n",
" \n",
" \n",
" #3 Run optimizers\n",
" print(batch_images.shape)\n",
" \n",
" #Tracer()() #this one triggers the debugger\n",
" \n",
" # Optimize discriminator\n",
" _ = sess.run(d_train_opt, feed_dict={inputs_real: batch_images,\n",
" inputs_z: batch_z,\n",
" lr_rate: learning_rate})\n",
" \n",
" \n",
7 years ago
" \n",
7 years ago
" # Optimize generator\n",
" _ = sess.run(g_train_opt, feed_dict={inputs_z: batch_z,\n",
" lr_rate: learning_rate})\n",
" \n",
" \n",
" if steps % print_every == 0:\n",
" \n",
" d_train_loss = sess.run(d_train_opt, feed_dict={inputs_real: batch_images,\n",
" inputs_z: batch_z,\n",
" lr_rate: learning_rate})\n",
" \n",
" # Optimize generator\n",
" g_train_loss = sess.run(g_train_opt, feed_dict={inputs_z: batch_z,\n",
" lr_rate: learning_rate})\n",
" \n",
" print(\"Epoch {}/{}...\".format(epoch_i+1, epoch_count),\n",
" \"Discriminator Loss: {:.4f}...\".format(d_train_loss),\n",
" \"Generator Loss: {:.4f}\".format(g_train_loss))\n",
" \n",
" if steps % show_every == 0:\n",
" show_generator_output(sess, 10, inputs_z, out_channel_dim, data_image_mode)\n",
" \n",
" \n",
" break\n",
7 years ago
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### MNIST\n",
"Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
7 years ago
"scrolled": false
7 years ago
},
"outputs": [],
"source": [
7 years ago
"batch_size = 10\n",
"z_dim = 100\n",
"learning_rate = 0.002\n",
"beta1 = 0.9\n",
7 years ago
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"epochs = 2\n",
"\n",
"mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))\n",
"with tf.Graph().as_default():\n",
" train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,\n",
" mnist_dataset.shape, mnist_dataset.image_mode)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### CelebA\n",
"Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
7 years ago
"collapsed": true,
7 years ago
"scrolled": true
},
"outputs": [],
"source": [
"batch_size = None\n",
"z_dim = None\n",
"learning_rate = None\n",
"beta1 = None\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"epochs = 1\n",
"\n",
"celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))\n",
"with tf.Graph().as_default():\n",
" train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,\n",
" celeba_dataset.shape, celeba_dataset.image_mode)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Submitting This Project\n",
"When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_face_generation.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission."
]
}
],
"metadata": {
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 1
}