{"id":18268444,"url":"https://github.com/coreyjs/face-generation-gan","last_synced_at":"2026-02-26T12:01:03.372Z","repository":{"id":73449850,"uuid":"352169556","full_name":"coreyjs/face-generation-GAN","owner":"coreyjs","description":"A GAN to generate human faces.","archived":false,"fork":false,"pushed_at":"2021-03-27T20:26:39.000Z","size":1333,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-08-05T23:28:46.948Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/coreyjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-27T20:23:23.000Z","updated_at":"2022-02-07T13:36:35.000Z","dependencies_parsed_at":"2023-02-24T04:15:32.031Z","dependency_job_id":null,"html_url":"https://github.com/coreyjs/face-generation-GAN","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/coreyjs/face-generation-GAN","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fface-generation-GAN","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fface-generation-GAN/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fface-generation-GAN/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fface-generation-GAN/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/coreyjs","download_url":"https://codeload.github.com/coreyjs/face-generation-GAN/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fface-generation-GAN/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29858461,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-26T08:51:08.701Z","status":"ssl_error","status_checked_at":"2026-02-26T08:50:19.607Z","response_time":89,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-05T11:31:36.254Z","updated_at":"2026-02-26T12:01:03.356Z","avatar_url":"https://github.com/coreyjs.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# face-generation-GAN\nA GAN to generate human faces.\n\n\n\n# Face Generation\n\nIn this project, you'll define and train a DCGAN on a dataset of faces. Your goal is to get a generator network to generate *new* images of faces that look as realistic as possible!\n\nThe project will be broken down into a series of tasks from **loading in data to defining and training adversarial networks**. At the end of the notebook, you'll be able to visualize the results of your trained Generator to see how it performs; your generated samples should look like fairly realistic faces with small amounts of noise.\n\n### Get the Data\n\nYou'll be using the [CelebFaces Attributes Dataset (CelebA)](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) to train your adversarial networks.\n\nThis dataset is more complex than the number datasets (like MNIST or SVHN) you've been working with, and so, you should prepare to define deeper networks and train them for a longer time to get good results. It is suggested that you utilize a GPU for training.\n\n### Pre-processed Data\n\nSince the project's main focus is on building the GANs, we've done *some* of the pre-processing for you. Each of the CelebA images has been cropped to remove parts of the image that don't include a face, then resized down to 64x64x3 NumPy images. Some sample data is show below.\n\n\u003cimg src='assets/processed_face_data.png' width=60% /\u003e\n\n\u003e If you are working locally, you can download this data [by clicking here](https://s3.amazonaws.com/video.udacity-data.com/topher/2018/November/5be7eb6f_processed-celeba-small/processed-celeba-small.zip)\n\nThis is a zip file that you'll need to extract in the home directory of this notebook for further loading and processing. After extracting the data, you should be left with a directory of data `processed_celeba_small/`\n\n\n```python\n# can comment out after executing\n!unzip processed_celeba_small.zip\n```\n\n    'unzip' is not recognized as an internal or external command,\n    operable program or batch file.\n    \n\n\n```python\ndata_dir = 'processed_celeba_small/'\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport pickle as pkl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport problem_unittests as tests\n#import helper\n\n%matplotlib inline\n```\n\n## Visualize the CelebA Data\n\nThe [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'll only need the images. Note that these are color images with [3 color channels (RGB)](https://en.wikipedia.org/wiki/Channel_(digital_image)#RGB_Images) each.\n\n### Pre-process and Load the Data\n\nSince the project's main focus is on building the GANs, we've done *some* of the pre-processing for you. Each of the CelebA images has been cropped to remove parts of the image that don't include a face, then resized down to 64x64x3 NumPy images. This *pre-processed* dataset is a smaller subset of the very large CelebA data.\n\n\u003e There are a few other steps that you'll need to **transform** this data and create a **DataLoader**.\n\n#### Exercise: Complete the following `get_dataloader` function, such that it satisfies these requirements:\n\n* Your images should be square, Tensor images of size `image_size x image_size` in the x and y dimension.\n* Your function should return a DataLoader that shuffles and batches these Tensor images.\n\n#### ImageFolder\n\nTo create a dataset given a directory of images, it's recommended that you use PyTorch's [ImageFolder](https://pytorch.org/docs/stable/torchvision/datasets.html#imagefolder) wrapper, with a root directory `processed_celeba_small/` and data transformation passed in.\n\n\n```python\n# necessary imports\nimport torch\nimport os\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\n```\n\n\n```python\ndef get_dataloader(batch_size, image_size, data_dir='processed_celeba_small/') -\u003e DataLoader:\n    \"\"\"\n    Batch the neural network data using DataLoader\n    :param batch_size: The size of each batch; the number of images in a batch\n    :param img_size: The square size of the image data (x, y)\n    :param data_dir: Directory where image data is located\n    :return: DataLoader with batched data\n    \"\"\"\n    \n    # TODO: Implement function and return a dataloader\n    \n    # resize and normalize the images (variation of code found in CycleGAN notebook)\n    t = transforms.Compose([\n        transforms.Resize(image_size),\n        transforms.ToTensor()\n    ])\n    \n    dataset = datasets.ImageFolder(data_dir, transform=t)\n    \n    loader = DataLoader(\n        dataset=dataset,\n        batch_size=batch_size,\n        shuffle=True\n    )\n    \n    return loader\n```\n\n## Create a DataLoader\n\n#### Exercise: Create a DataLoader `celeba_train_loader` with appropriate hyperparameters.\n\nCall the above function and create a dataloader to view images. \n* You can decide on any reasonable `batch_size` parameter\n* Your `image_size` **must be** `32`. Resizing the data to a smaller size will make for faster training, while still creating convincing images of faces!\n\n\n```python\n# Define function hyperparameters\nbatch_size = 128\nimg_size = 32\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n# Call your function and get a dataloader\nceleba_train_loader = get_dataloader(batch_size, img_size)\n\n```\n\nNext, you can view some images! You should seen square images of somewhat-centered faces.\n\nNote: You'll need to convert the Tensor images into a NumPy type and transpose the dimensions to correctly display an image, suggested `imshow` code is below, but it may not be perfect.\n\n\n```python\n# helper display function\ndef imshow(img):\n    npimg = img.numpy()\n    plt.imshow(np.transpose(npimg, (1, 2, 0)))\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n# obtain one batch of training images\ndataiter = iter(celeba_train_loader)\nimages, _ = dataiter.next() # _ for no labels\n\n# plot the images in the batch, along with the corresponding labels\nfig = plt.figure(figsize=(20, 4))\nplot_size=20\nfor idx in np.arange(plot_size):\n    ax = fig.add_subplot(2, plot_size/2, idx+1, xticks=[], yticks=[])\n    imshow(images[idx])\n```\n\n    C:\\Users\\cscha\\anaconda3\\envs\\u-deep-learning\\lib\\site-packages\\ipykernel_launcher.py:17: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later.\n    \n\n\n![png](output_9_1.png)\n\n\n#### Exercise: Pre-process your image data and scale it to a pixel range of -1 to 1\n\nYou need to do a bit of pre-processing; you know that the output of a `tanh` activated generator will contain pixel values in a range from -1 to 1, and so, we need to rescale our training images to a range of -1 to 1. (Right now, they are in a range from 0-1.)\n\n\n```python\n# TODO: Complete the scale function\ndef scale(x, feature_range=(-1, 1)):\n    ''' Scale takes in an image x and returns that image, scaled\n       with a feature_range of pixel values from -1 to 1. \n       This function assumes that the input x is already scaled from 0-1.'''\n    # assume x is scaled to (0, 1)\n    # scale to feature_range and return scaled x\n    \n    # unpack tuple\n    min, max = feature_range\n    \n    x = x * (max - min) + min\n    \n    return x\n\n```\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n# check scaled range\n# should be close to -1 to 1\nimg = images[0]\n\nprint('Orig Min: ', img.min())\nprint('Orig Max: ', img.max())\n\nscaled_img = scale(img)\n\nprint('Min: ', scaled_img.min())\nprint('Max: ', scaled_img.max())\n```\n\n    Orig Min:  tensor(0.0784)\n    Orig Max:  tensor(1.)\n    Min:  tensor(-0.8431)\n    Max:  tensor(1.)\n    \n\n---\n# Define the Model\n\nA GAN is comprised of two adversarial networks, a discriminator and a generator.\n\n## Discriminator\n\nYour first task will be to define the discriminator. This is a convolutional classifier like you've built before, only without any maxpooling layers. To deal with this complex data, it's suggested you use a deep network with **normalization**. You are also allowed to create any helper functions that may be useful.\n\n#### Exercise: Complete the Discriminator class\n* The inputs to the discriminator are 32x32x3 tensor images\n* The output should be a single value that will indicate whether a given image is real or fake\n\n\n\n```python\nimport torch.nn as nn\nimport torch.nn.functional as F\n```\n\n\n```python\n# Helper Functions\n# Similar to those in chapter 5\n\ndef get_conv_layers(in_channels, out_channels, kernel_size, stride=2, padding=1, batch_norm=True):\n    \"\"\"\n    This will create a conv layer with optional batch norm applied\n    \"\"\"\n    layers = []\n    layers.append(\n        nn.Conv2d(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=kernel_size,\n            stride=stride,\n            padding=padding,\n            bias=False\n        )\n    )\n    \n    if batch_norm:\n        layers.append(nn.BatchNorm2d(out_channels))\n    \n    return nn.Sequential(*layers)\n    \n```\n\n\n```python\nclass Discriminator(nn.Module):\n\n    def __init__(self, conv_dim):\n        \"\"\"\n        Initialize the Discriminator Module\n        :param conv_dim: The depth of the first convolutional layer\n        \"\"\"\n        super(Discriminator, self).__init__()\n\n        # complete init function\n        # we will define a 4 layer network due to the small input size of our images\n        \n        self.conv_dim = conv_dim\n        \n        # x, y = 32, depth 32\n        # Note, first layer does not have batch normilization\n        self.conv1 = get_conv_layers(\n            in_channels=3, #rgb \n            out_channels=conv_dim,\n            kernel_size=4,\n            batch_norm=False\n        )\n        \n        # (16, 16, 64)\n        self.conv2 = get_conv_layers(\n            in_channels=conv_dim,\n            out_channels=conv_dim*2,\n            kernel_size=4\n        )\n        \n        # (8, 8, 128)\n        self.conv3 = get_conv_layers(\n            in_channels=conv_dim * 2,\n            out_channels=conv_dim * 4,\n            kernel_size=4\n        )\n        \n        self.fc = nn.Linear(conv_dim * 4 * 4 * 4, 1)\n        \n\n    def forward(self, x):\n        \"\"\"\n        Forward propagation of the neural network\n        :param x: The input to the neural network     \n        :return: Discriminator logits; the output of the neural network\n        \"\"\"\n        # define feedforward behavior\n        \n        out = F.leaky_relu(self.conv1(x), 0.2)\n        out = F.leaky_relu(self.conv2(out), 0.2)\n        out = F.leaky_relu(self.conv3(out), 0.2)\n        \n        # flatten image\n        out = out.view(-1, self.conv_dim*4*4*4)\n        \n        #final output layer\n        out = self.fc(out)\n        \n        return out\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_discriminator(Discriminator)\n```\n\n    Tests Passed\n    \n\n## Generator\n\nThe generator should upsample an input and generate a *new* image of the same size as our training data `32x32x3`. This should be mostly transpose convolutional layers with normalization applied to the outputs.\n\n#### Exercise: Complete the Generator class\n* The inputs to the generator are vectors of some length `z_size`\n* The output should be a image of shape `32x32x3`\n\n![image.png](attachment:image.png)\n\n\n```python\n# helper method\ndef get_deconv_layers(in_channels, out_channels, kernel_size, stride=2, padding=1, batch_norm=True):\n    \"\"\"\n    This will create a transposed convultional layer, with optional batch normilization.\n    \"\"\"\n    layers = []\n    \n    layers.append(\n        nn.ConvTranspose2d(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=kernel_size,\n            stride=stride,\n            padding=padding,\n            bias=False\n        )\n    )\n    \n    if batch_norm:\n        layers.append(nn.BatchNorm2d(out_channels))\n        \n    return nn.Sequential(*layers)\n```\n\n\n```python\nclass Generator(nn.Module):\n    \n    def __init__(self, z_size, conv_dim):\n        \"\"\"\n        Initialize the Generator Module\n        :param z_size: The length of the input latent vector, z\n        :param conv_dim: The depth of the inputs to the *last* transpose convolutional layer\n        \"\"\"\n        super(Generator, self).__init__()\n\n        # complete init function\n        \n        self.conv_dim = conv_dim\n        \n        # following previous generator examples, we will start with a\n        # fullconnected (fc) layer, followed by 3 transpose conv layers\n        # and finally out outputed, generated image\n        self.fc = nn.Linear(z_size, conv_dim*4*4*4)\n        \n        self.t_conv1 = get_deconv_layers(\n            in_channels=conv_dim * 4,\n            out_channels=conv_dim *2,\n            kernel_size=4\n        )\n        self.t_conv2 = get_deconv_layers(\n            in_channels=conv_dim *2,\n            out_channels=conv_dim,\n            kernel_size=4\n        )\n        self.t_conv3 = get_deconv_layers(\n            in_channels=conv_dim,\n            out_channels=3,\n            kernel_size=4,\n            batch_norm=False\n        )\n        \n        \n\n    def forward(self, x):\n        \"\"\"\n        Forward propagation of the neural network\n        :param x: The input to the neural network     \n        :return: A 32x32x3 Tensor image as output\n        \"\"\"\n        # define feedforward behavior\n        out = self.fc(x)\n        \n        # reshape\n        out = out.view(-1, self.conv_dim*4, 4, 4) # (batchsize, depth, 4, 4)\n        \n        out = F.relu(self.t_conv1(out))\n        out = F.relu(self.t_conv2(out))\n        \n        # final layert and activation\n        out = self.t_conv3(out)\n        out = F.tanh(out) # F.tanh is deprecated\n        \n        return out\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_generator(Generator)\n```\n\n    Tests Passed\n    \n\n    C:\\Users\\cscha\\anaconda3\\envs\\u-deep-learning\\lib\\site-packages\\torch\\nn\\functional.py:1628: UserWarning: nn.functional.tanh is deprecated. Use torch.tanh instead.\n      warnings.warn(\"nn.functional.tanh is deprecated. Use torch.tanh instead.\")\n    \n\n## Initialize the weights of your networks\n\nTo help your models converge, you should initialize the weights of the convolutional and linear layers in your model. From reading the [original DCGAN paper](https://arxiv.org/pdf/1511.06434.pdf), they say:\n\u003e All weights were initialized from a zero-centered Normal distribution with standard deviation 0.02.\n\nSo, your next task will be to define a weight initialization function that does just this!\n\nYou can refer back to the lesson on weight initialization or even consult existing model code, such as that from [the `networks.py` file in CycleGAN Github repository](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py) to help you complete this function.\n\n#### Exercise: Complete the weight initialization function\n\n* This should initialize only **convolutional** and **linear** layers\n* Initialize the weights to a normal distribution, centered around 0, with a standard deviation of 0.02.\n* The bias terms, if they exist, may be left alone or set to 0.\n\n\n```python\ndef weights_init_normal(m):\n    \"\"\"\n    Applies initial weights to certain layers in a model .\n    The weights are taken from a normal distribution \n    with mean = 0, std dev = 0.02.\n    :param m: A module or layer in a network    \n    \"\"\"\n    # classname will be something like:\n    # `Conv`, `BatchNorm2d`, `Linear`, etc.\n    classname = m.__class__.__name__\n    # referenced from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py\n    if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n        m.weight.data.normal_(0.0, 0.02)\n    \n        if hasattr(m, 'bias') and m.bias is not None:\n            m.bias.data.zero_()\n    \n```\n\n## Build complete network\n\nDefine your models' hyperparameters and instantiate the discriminator and generator from the classes defined above. Make sure you've passed in the correct input arguments.\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ndef build_network(d_conv_dim, g_conv_dim, z_size):\n    # define discriminator and generator\n    D = Discriminator(d_conv_dim)\n    G = Generator(z_size=z_size, conv_dim=g_conv_dim)\n\n    # initialize model weights\n    D.apply(weights_init_normal)\n    G.apply(weights_init_normal)\n\n    print(D)\n    print()\n    print(G)\n    \n    return D, G\n\n```\n\n#### Exercise: Define model hyperparameters\n\n\n```python\n# Define model hyperparams\nd_conv_dim = 64\ng_conv_dim = 64\nz_size = 100\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nD, G = build_network(d_conv_dim, g_conv_dim, z_size)\n```\n\n    Discriminator(\n      (conv1): Sequential(\n        (0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)\n      )\n      (conv2): Sequential(\n        (0): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)\n        (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n      )\n      (conv3): Sequential(\n        (0): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)\n        (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n      )\n      (fc): Linear(in_features=4096, out_features=1, bias=True)\n    )\n    \n    Generator(\n      (fc): Linear(in_features=100, out_features=4096, bias=True)\n      (t_conv1): Sequential(\n        (0): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)\n        (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n      )\n      (t_conv2): Sequential(\n        (0): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)\n        (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n      )\n      (t_conv3): Sequential(\n        (0): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)\n      )\n    )\n    \n\n### Training on GPU\n\nCheck if you can train on GPU. Here, we'll set this as a boolean variable `train_on_gpu`. Later, you'll be responsible for making sure that \n\u003e* Models,\n* Model inputs, and\n* Loss function arguments\n\nAre moved to GPU, where appropriate.\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\n\n# Check for a GPU\ntrain_on_gpu = torch.cuda.is_available()\nif not train_on_gpu:\n    print('No GPU found. Please use a GPU to train your neural network.')\nelse:\n    print('Training on GPU!')\n```\n\n    Training on GPU!\n    \n\n---\n## Discriminator and Generator Losses\n\nNow we need to calculate the losses for both types of adversarial networks.\n\n### Discriminator Losses\n\n\u003e * For the discriminator, the total loss is the sum of the losses for real and fake images, `d_loss = d_real_loss + d_fake_loss`. \n* Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that.\n\n\n### Generator Loss\n\nThe generator loss will look similar only with flipped labels. The generator's goal is to get the discriminator to *think* its generated images are *real*.\n\n#### Exercise: Complete real and fake loss functions\n\n**You may choose to use either cross entropy or a least squares error loss to complete the following `real_loss` and `fake_loss` functions.**\n\n\n```python\ndef real_loss(D_out):\n    '''Calculates how close discriminator outputs are to being real.\n       param, D_out: discriminator logits\n       return: real loss'''\n    batch_size = D_out.size(0)\n    labels = torch.ones(batch_size)\n    if train_on_gpu:\n        labels = labels.cuda()\n    \n    # binary cross entropy loss with logits loss\n    criterion = nn.BCEWithLogitsLoss()\n    \n    loss = criterion(D_out.squeeze(), labels)\n    \n    return loss\n\ndef fake_loss(D_out):\n    '''Calculates how close discriminator outputs are to being fake.\n       param, D_out: discriminator logits\n       return: fake loss'''\n    batch_size = D_out.size(0)\n    labels = torch.zeros(batch_size)\n    \n    if train_on_gpu:\n        labels = labels.cuda()\n    criterion = nn.BCEWithLogitsLoss()\n    loss = criterion(D_out.squeeze(), labels)\n    return loss\n```\n\n## Optimizers\n\n#### Exercise: Define optimizers for your Discriminator (D) and Generator (G)\n\nDefine optimizers for your models with appropriate hyperparameters.\n\n\n```python\nimport torch.optim as optim\n\nlr = 0.0002 #0.0002\nbeta1 = 0.5\nbeta2 = 0.999\n\n# Create optimizers for the discriminator D and generator G\nd_optimizer = optim.Adam(D.parameters(), lr, [beta1, beta2])\ng_optimizer = optim.Adam(G.parameters(), lr, [beta1, beta2])\n```\n\n---\n## Training\n\nTraining will involve alternating between training the discriminator and the generator. You'll use your functions `real_loss` and `fake_loss` to help you calculate the discriminator losses.\n\n* You should train the discriminator by alternating on real and fake images\n* Then the generator, which tries to trick the discriminator and should have an opposing loss function\n\n\n#### Saving Samples\n\nYou've been given some code to print out some loss statistics and save some generated \"fake\" samples.\n\n#### Exercise: Complete the training function\n\nKeep in mind that, if you've moved your models to GPU, you'll also have to move any model inputs to GPU.\n\n\n```python\ndef train(D, G, n_epochs, print_every=50):\n    '''Trains adversarial networks for some number of epochs\n       param, D: the discriminator network\n       param, G: the generator network\n       param, n_epochs: number of epochs to train for\n       param, print_every: when to print and record the models' losses\n       return: D and G losses'''\n    \n    # move models to GPU\n    if train_on_gpu:\n        D.cuda()\n        G.cuda()\n\n    # keep track of loss and generated, \"fake\" samples\n    samples = []\n    losses = []\n\n    # Get some fixed data for sampling. These are images that are held\n    # constant throughout training, and allow us to inspect the model's performance\n    sample_size=16\n    fixed_z = np.random.uniform(-1, 1, size=(sample_size, z_size))\n    fixed_z = torch.from_numpy(fixed_z).float()\n    # move z to GPU if available\n    if train_on_gpu:\n        fixed_z = fixed_z.cuda()\n\n    # epoch training loop\n    for epoch in range(n_epochs):\n\n        # batch training loop\n        for batch_i, (real_images, _) in enumerate(celeba_train_loader):\n\n            batch_size = real_images.size(0)\n            real_images = scale(real_images)\n            \n            if train_on_gpu:\n                real_images = real_images.cuda()\n\n            # ===============================================\n            #         YOUR CODE HERE: TRAIN THE NETWORKS\n            # ===============================================\n            \n            # 1. Train the discriminator on real and fake images\n            d_optimizer.zero_grad()\n            \n            # train with real images\n            d_real = D(real_images)\n            d_real_loss = real_loss(d_real)\n            \n            # train with fake images\n            # referenced on DCGAN udacity notebook\n            z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n            z = torch.from_numpy(z).float()\n            \n            # move x to GPU, if available\n            if train_on_gpu:\n                z = z.cuda()\n            fake_images = G(z)\n            \n            d_fake = D(fake_images)\n            d_fake_loss = fake_loss(d_fake)\n            \n            # add up loss and do backprop\n            d_loss = d_real_loss + d_fake_loss\n            d_loss.backward()\n            d_optimizer.step()\n\n            # 2. Train the generator with an adversarial loss\n            g_optimizer.zero_grad()\n            \n            #train with fake images and flipped labels\n            #gen fake images\n            z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n            z = torch.from_numpy(z).float()\n            if train_on_gpu:\n                z = z.cuda()\n            fake_images = G(z)\n            \n            # compute discrim losses on fake images\n            D_fake = D(fake_images)\n            g_loss = real_loss(D_fake)\n            \n            #backprop\n            g_loss.backward()\n            g_optimizer.step()\n            \n            \n            # ===============================================\n            #              END OF YOUR CODE\n            # ===============================================\n\n            # Print some loss stats\n            if batch_i % print_every == 0:\n                # append discriminator loss and generator loss\n                losses.append((d_loss.item(), g_loss.item()))\n                # print discriminator and generator loss\n                print('Epoch [{:5d}/{:5d}] | d_loss: {:6.4f} | g_loss: {:6.4f}'.format(\n                        epoch+1, n_epochs, d_loss.item(), g_loss.item()))\n\n\n        ## AFTER EACH EPOCH##    \n        # this code assumes your generator is named G, feel free to change the name\n        # generate and save sample, fake images\n        G.eval() # for generating samples\n        samples_z = G(fixed_z)\n        samples.append(samples_z)\n        G.train() # back to training mode\n\n    # Save training generator samples\n    with open('train_samples.pkl', 'wb') as f:\n        pkl.dump(samples, f)\n    \n    # finally return losses\n    return losses\n```\n\nSet your number of training epochs and train your GAN!\n\n\n```python\n# set number of epochs \nn_epochs = 30\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# call training function\nlosses = train(D, G, n_epochs=n_epochs)\n```\n\n    C:\\Users\\cscha\\anaconda3\\envs\\u-deep-learning\\lib\\site-packages\\torch\\nn\\functional.py:1628: UserWarning: nn.functional.tanh is deprecated. Use torch.tanh instead.\n      warnings.warn(\"nn.functional.tanh is deprecated. Use torch.tanh instead.\")\n    \n\n    Epoch [    1/   30] | d_loss: 0.9295 | g_loss: 1.5117\n    Epoch [    1/   30] | d_loss: 1.0034 | g_loss: 1.8572\n    Epoch [    1/   30] | d_loss: 1.0981 | g_loss: 2.0010\n    Epoch [    1/   30] | d_loss: 0.8415 | g_loss: 1.8121\n    Epoch [    2/   30] | d_loss: 0.9711 | g_loss: 1.0954\n    Epoch [    2/   30] | d_loss: 0.7390 | g_loss: 2.1245\n    Epoch [    2/   30] | d_loss: 1.1486 | g_loss: 1.0666\n    Epoch [    2/   30] | d_loss: 0.9295 | g_loss: 1.3925\n    Epoch [    3/   30] | d_loss: 0.9660 | g_loss: 0.9416\n    Epoch [    3/   30] | d_loss: 0.8961 | g_loss: 1.6030\n    Epoch [    3/   30] | d_loss: 0.9145 | g_loss: 1.0857\n    Epoch [    3/   30] | d_loss: 1.0376 | g_loss: 0.9892\n    Epoch [    4/   30] | d_loss: 1.1725 | g_loss: 0.6244\n    Epoch [    4/   30] | d_loss: 1.1803 | g_loss: 0.8774\n    Epoch [    4/   30] | d_loss: 0.8313 | g_loss: 1.5151\n    Epoch [    4/   30] | d_loss: 0.8474 | g_loss: 1.7635\n    Epoch [    5/   30] | d_loss: 0.8062 | g_loss: 1.6507\n    Epoch [    5/   30] | d_loss: 0.8955 | g_loss: 1.4647\n    Epoch [    5/   30] | d_loss: 0.9882 | g_loss: 0.8468\n    Epoch [    5/   30] | d_loss: 1.1139 | g_loss: 0.8816\n    Epoch [    6/   30] | d_loss: 1.0984 | g_loss: 1.8249\n    Epoch [    6/   30] | d_loss: 0.8638 | g_loss: 2.0113\n    Epoch [    6/   30] | d_loss: 0.9250 | g_loss: 1.6440\n    Epoch [    6/   30] | d_loss: 0.9876 | g_loss: 1.9577\n    Epoch [    7/   30] | d_loss: 1.0549 | g_loss: 1.6363\n    Epoch [    7/   30] | d_loss: 0.8772 | g_loss: 1.6835\n    Epoch [    7/   30] | d_loss: 0.7662 | g_loss: 1.1871\n    Epoch [    7/   30] | d_loss: 0.7329 | g_loss: 1.9859\n    Epoch [    8/   30] | d_loss: 0.8859 | g_loss: 1.5531\n    Epoch [    8/   30] | d_loss: 0.8056 | g_loss: 1.7220\n    Epoch [    8/   30] | d_loss: 0.7786 | g_loss: 1.6907\n    Epoch [    8/   30] | d_loss: 0.9269 | g_loss: 1.8390\n    Epoch [    9/   30] | d_loss: 0.7462 | g_loss: 1.9540\n    Epoch [    9/   30] | d_loss: 0.9469 | g_loss: 1.9003\n    Epoch [    9/   30] | d_loss: 0.6700 | g_loss: 1.6289\n    Epoch [    9/   30] | d_loss: 0.8469 | g_loss: 1.3337\n    Epoch [   10/   30] | d_loss: 1.0052 | g_loss: 2.2254\n    Epoch [   10/   30] | d_loss: 0.6979 | g_loss: 1.6195\n    Epoch [   10/   30] | d_loss: 1.6957 | g_loss: 0.6537\n    Epoch [   10/   30] | d_loss: 0.8477 | g_loss: 1.5737\n    Epoch [   11/   30] | d_loss: 0.7563 | g_loss: 1.9307\n    Epoch [   11/   30] | d_loss: 0.8574 | g_loss: 1.1942\n    Epoch [   11/   30] | d_loss: 0.9291 | g_loss: 1.4340\n    Epoch [   11/   30] | d_loss: 0.8597 | g_loss: 2.3718\n    Epoch [   12/   30] | d_loss: 0.9024 | g_loss: 1.4180\n    Epoch [   12/   30] | d_loss: 0.8677 | g_loss: 1.0154\n    Epoch [   12/   30] | d_loss: 0.7978 | g_loss: 2.3882\n    Epoch [   12/   30] | d_loss: 0.7028 | g_loss: 1.5528\n    Epoch [   13/   30] | d_loss: 1.0687 | g_loss: 1.8166\n    Epoch [   13/   30] | d_loss: 0.8556 | g_loss: 2.3718\n    Epoch [   13/   30] | d_loss: 1.1841 | g_loss: 1.6010\n    Epoch [   13/   30] | d_loss: 0.7439 | g_loss: 1.3635\n    Epoch [   14/   30] | d_loss: 0.5924 | g_loss: 1.6642\n    Epoch [   14/   30] | d_loss: 0.7875 | g_loss: 1.8687\n    Epoch [   14/   30] | d_loss: 0.6635 | g_loss: 1.4923\n    Epoch [   14/   30] | d_loss: 0.7753 | g_loss: 1.5124\n    Epoch [   15/   30] | d_loss: 0.9962 | g_loss: 2.2048\n    Epoch [   15/   30] | d_loss: 0.6298 | g_loss: 1.9031\n    Epoch [   15/   30] | d_loss: 0.9105 | g_loss: 2.0570\n    Epoch [   15/   30] | d_loss: 1.0415 | g_loss: 0.6226\n    Epoch [   16/   30] | d_loss: 0.6034 | g_loss: 1.8023\n    Epoch [   16/   30] | d_loss: 0.6973 | g_loss: 1.9579\n    Epoch [   16/   30] | d_loss: 0.7301 | g_loss: 2.1492\n    Epoch [   16/   30] | d_loss: 0.8045 | g_loss: 2.3191\n    Epoch [   17/   30] | d_loss: 0.6362 | g_loss: 2.1833\n    Epoch [   17/   30] | d_loss: 0.6639 | g_loss: 2.0988\n    Epoch [   17/   30] | d_loss: 0.8146 | g_loss: 1.3589\n    Epoch [   17/   30] | d_loss: 0.7049 | g_loss: 1.6876\n    Epoch [   18/   30] | d_loss: 0.6947 | g_loss: 1.4402\n    Epoch [   18/   30] | d_loss: 0.6907 | g_loss: 1.9027\n    Epoch [   18/   30] | d_loss: 0.8211 | g_loss: 2.2626\n    Epoch [   18/   30] | d_loss: 0.7755 | g_loss: 1.8786\n    Epoch [   19/   30] | d_loss: 0.7699 | g_loss: 1.3836\n    Epoch [   19/   30] | d_loss: 1.4000 | g_loss: 2.8535\n    Epoch [   19/   30] | d_loss: 0.6621 | g_loss: 1.7088\n    Epoch [   19/   30] | d_loss: 0.7580 | g_loss: 1.3050\n    Epoch [   20/   30] | d_loss: 0.8442 | g_loss: 0.9928\n    Epoch [   20/   30] | d_loss: 0.8086 | g_loss: 1.3639\n    Epoch [   20/   30] | d_loss: 0.9134 | g_loss: 2.7514\n    Epoch [   20/   30] | d_loss: 1.5106 | g_loss: 0.2603\n    Epoch [   21/   30] | d_loss: 0.6131 | g_loss: 1.0893\n    Epoch [   21/   30] | d_loss: 0.8068 | g_loss: 2.0677\n    Epoch [   21/   30] | d_loss: 0.7855 | g_loss: 2.6375\n    Epoch [   21/   30] | d_loss: 0.5379 | g_loss: 1.8356\n    Epoch [   22/   30] | d_loss: 0.7136 | g_loss: 1.4980\n    Epoch [   22/   30] | d_loss: 0.7825 | g_loss: 1.4148\n    Epoch [   22/   30] | d_loss: 0.6009 | g_loss: 1.9829\n    Epoch [   22/   30] | d_loss: 0.7280 | g_loss: 3.5112\n    Epoch [   23/   30] | d_loss: 0.9314 | g_loss: 2.2211\n    Epoch [   23/   30] | d_loss: 0.8007 | g_loss: 1.5581\n    Epoch [   23/   30] | d_loss: 0.7146 | g_loss: 1.9058\n    Epoch [   23/   30] | d_loss: 0.5722 | g_loss: 1.3804\n    Epoch [   24/   30] | d_loss: 1.0354 | g_loss: 0.9269\n    Epoch [   24/   30] | d_loss: 0.5501 | g_loss: 1.4563\n    Epoch [   24/   30] | d_loss: 0.7211 | g_loss: 1.9383\n    Epoch [   24/   30] | d_loss: 0.7860 | g_loss: 1.1207\n    Epoch [   25/   30] | d_loss: 0.7321 | g_loss: 2.1805\n    Epoch [   25/   30] | d_loss: 0.9309 | g_loss: 2.4778\n    Epoch [   25/   30] | d_loss: 0.9633 | g_loss: 0.5461\n    Epoch [   25/   30] | d_loss: 0.7648 | g_loss: 1.5755\n    Epoch [   26/   30] | d_loss: 0.7172 | g_loss: 3.1594\n    Epoch [   26/   30] | d_loss: 0.7526 | g_loss: 2.7776\n    Epoch [   26/   30] | d_loss: 1.3388 | g_loss: 3.8469\n    Epoch [   26/   30] | d_loss: 0.8049 | g_loss: 0.8139\n    Epoch [   27/   30] | d_loss: 0.6424 | g_loss: 1.1014\n    Epoch [   27/   30] | d_loss: 1.8722 | g_loss: 5.9103\n    Epoch [   27/   30] | d_loss: 0.6451 | g_loss: 2.2235\n    Epoch [   27/   30] | d_loss: 0.5864 | g_loss: 2.1465\n    Epoch [   28/   30] | d_loss: 0.7656 | g_loss: 2.3493\n    Epoch [   28/   30] | d_loss: 0.6758 | g_loss: 1.7278\n    Epoch [   28/   30] | d_loss: 0.8942 | g_loss: 2.6284\n    Epoch [   28/   30] | d_loss: 0.7407 | g_loss: 2.5703\n    Epoch [   29/   30] | d_loss: 0.5382 | g_loss: 1.5070\n    Epoch [   29/   30] | d_loss: 0.9936 | g_loss: 0.9740\n    Epoch [   29/   30] | d_loss: 0.8152 | g_loss: 1.3423\n    Epoch [   29/   30] | d_loss: 0.6531 | g_loss: 1.2543\n    Epoch [   30/   30] | d_loss: 0.7619 | g_loss: 2.2676\n    Epoch [   30/   30] | d_loss: 0.5948 | g_loss: 1.7222\n    Epoch [   30/   30] | d_loss: 0.5924 | g_loss: 1.3510\n    Epoch [   30/   30] | d_loss: 0.7323 | g_loss: 3.0855\n    \n\n## Training loss\n\nPlot the training losses for the generator and discriminator, recorded after each epoch.\n\n\n```python\nfig, ax = plt.subplots()\nlosses = np.array(losses)\nplt.plot(losses.T[0], label='Discriminator', alpha=0.5)\nplt.plot(losses.T[1], label='Generator', alpha=0.5)\nplt.title(\"Training Losses\")\nplt.legend()\n```\n\n\n\n\n    \u003cmatplotlib.legend.Legend at 0x2e41d401248\u003e\n\n\n\n\n![png](output_39_1.png)\n\n\n## Generator samples from training\n\nView samples of images from the generator, and answer a question about the strengths and weaknesses of your trained models.\n\n\n```python\n# helper function for viewing a list of passed in sample images\ndef view_samples(epoch, samples):\n    fig, axes = plt.subplots(figsize=(16,4), nrows=2, ncols=8, sharey=True, sharex=True)\n    for ax, img in zip(axes.flatten(), samples[epoch]):\n        img = img.detach().cpu().numpy()\n        img = np.transpose(img, (1, 2, 0))\n        img = ((img + 1)*255 / (2)).astype(np.uint8)\n        ax.xaxis.set_visible(False)\n        ax.yaxis.set_visible(False)\n        im = ax.imshow(img.reshape((32,32,3)))\n```\n\n\n```python\n# Load samples from generator, taken while training\nwith open('train_samples.pkl', 'rb') as f:\n    samples = pkl.load(f)\n```\n\n\n```python\n_ = view_samples(-1, samples)\n```\n\n\n![download](https://user-images.githubusercontent.com/1228838/112733938-243f1380-8f19-11eb-88c0-46d5c2d0dab4.png)\n\n\n\n### Question: What do you notice about your generated samples and how might you improve this model?\nWhen you answer this question, consider the following factors:\n* The dataset is biased; it is made of \"celebrity\" faces that are mostly white\n* Model size; larger models have the opportunity to learn more features in a data feature space\n* Optimization strategy; optimizers and number of epochs affect your final result\n\n\n**Answer:** \n\nInitially, I ran this network for 10 epochs.  I was able to generate face like objects (eyes, mouth, nose, hair) but the images were slightly disfigured.  I then ran this network for 30 epochs, and achieved the results above.  Here we can see clear human faces, with very little disfiguration or warping.  One thing to notice, the sample output all appears to be female in nature.  This might indicate a problem in the training.\n\nAs mentioned above, the data does seem to be biases as we have very little representation of black and asian races of both male and female.  Also the training data does not have much in the way of glasses, hats and types of facial hair, religious headware, etc.  My achieved results are quite indicitive of the data set itself.  Lots of white generated faces.\n\nHiar color is another factor that has a pretty slim representation in the data.  There are a few outliers that have hair that is not dark/blonde.  Most of our generated faces have a hair color that falls into this region.\n\n### Submitting This Project\nWhen 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\" -\u003e \"Download as\". Include the \"problem_unittests.py\" files in your submission.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoreyjs%2Fface-generation-gan","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcoreyjs%2Fface-generation-gan","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoreyjs%2Fface-generation-gan/lists"}