diff --git a/Practical_sessions/Session_8/Subject_8_GAN.ipynb b/Practical_sessions/Session_8/Subject_8_GAN.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..76a1517eedc3f2289353d5cf4fad79318cc5cc98 --- /dev/null +++ b/Practical_sessions/Session_8/Subject_8_GAN.ipynb @@ -0,0 +1,1201 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### **_Deep Learning - Bsc Data Science for Responsible Business - Centrale Lyon_**\n", + "\n", + "2024-2025\n", + "\n", + "Emmanuel Dellandréa\t " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "UGwKsKS4GMTN" + }, + "source": [ + "\n", + "\n", + "# Practical Session 8 - GANs and cGAN\n", + "\n", + "<p align=\"center\">\n", + "<img height=300px src=\"https://cdn-images-1.medium.com/max/1080/0*tJRy5Chmk4XymxwN.png\"/></p>\n", + "<p align=\"center\"></p>" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "16aVF81lJuiP" + }, + "source": [ + "The objective of this tutorial is to discover GANs, understand how they are implemented and then explore one specific architecture of GANs that allows us to perform image to image translation (which corresponds to the picture that you can see above this text ! ).\n", + "\n", + "The notebook contains code cells with the **\"# TO DO\"** comments. Your goal is to complete these cells and run the proposed experiments. Also, there are several questions that you have to anwer.\n", + "\n", + "As the computation is heavy, particularly during training, we encourage you to use a GPU. If your laptob is not equiped, you may use one of these remote jupyter servers, where you can select the execution on GPU :\n", + "\n", + "1) [jupyter.mi90.ec-lyon.fr](https://jupyter.mi90.ec-lyon.fr/)\n", + "\n", + "This server is accessible within the campus network. If outside, you need to use a VPN. Before executing the notebook, select the kernel \"Python PyTorch\" to run it on GPU and have access to PyTorch module.\n", + "\n", + "2) [Google Colaboratory](https://colab.research.google.com/)\n", + "\n", + "Before executing the notebook, select the execution on GPU : \"Exécution\" Menu -> \"Modifier le type d'exécution\" and select \"T4 GPU\". " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "M-WNKvhOP1ED" + }, + "source": [ + "# Part1: DC-GAN" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "y_r8nMTGQI9a" + }, + "source": [ + "In this part, we aim to learn and understand the basic concepts of **Generative Adversarial Networks** through a DCGAN and generate new celebrities from the learned network after showing it real celebrities. For this purpose, please study the tutorial here: https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we want to generate handwritten digits using the MNIST dataset. It is available within torvision package (https://pytorch.org/vision/stable/generated/torchvision.datasets.MNIST.html#torchvision.datasets.MNIST)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# TO DO: your code here to adapt the code from the tutorial to experiment on MNIST dataset" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "jiHCy4_UUBFb" + }, + "source": [ + "\n", + "\n", + "Please re-train the DCGAN and display some automatically generated handwritten digits.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "5fbSgsrE1GqC" + }, + "source": [ + "# Part2: Conditional GAN (cGAN)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "7SjXNoT7BUey" + }, + "source": [ + "Let's take the example of the set described in the next picture.\n", + "\n", + "\n", + "\n", + "We have a picture of a map (from Google Maps) and we want to create an image of what the satellite view may look like.\n", + "\n", + "As we are not only trying to generate a random picture but a mapping between a picture to another one, we can't use the standard GAN architecture. We will then use a cGAN introduced in this [paper](https://arxiv.org/pdf/1611.07004.pdf).\n", + "\n", + "A cGAN is a supervised GAN aiming at mapping a label picture to a real one or a real picture to a label one. As you can see in the diagram below, the discriminator will take as input a pair of images and try to predict if the pair was generated or not. The generator will not only generate an image from noise but will also use an image (label or real) to generate another one (real or label).\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "0JRaeHfzl6cO" + }, + "source": [ + "### Generator\n", + "\n", + "In the cGAN architecture, the generator chosen is a U-Net.\n", + "\n", + "\n", + "A U-Net takes as input an image, and outputs another image. \n", + "\n", + "It can be divided into 2 subparts : an encoder and a decoder. \n", + "* The encoder takes the input image and reduces its dimension to encode the main features into a vector. \n", + "* The decoder takes this vector and map the features stored into an image.\n", + "\n", + "A U-Net architecture is different from a classic encoder-decoder in that every layer of the decoder takes as input the previous decoded output as well as the output vector from the encoder layers of the same level. It allows the decoder to map low frequencies information encoded during the descent as well as high frequencies from the original picture. \n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "xFqMOsoYwzFe" + }, + "source": [ + "The architecture we will implement is the following (the number in the square is the number of filters used).\n", + "\n", + "\n", + "\n", + "\n", + "The encoder will take as input a colored picture (3 channels: RGB), it will pass through a series of convolution layers to encode the features of the picture. It will then be decoded by the decoder using transposed convolutional layers. These layers will take as input the previous decoded vector AND the encoded features of the same level. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "yzy7y4hmbbX3" + }, + "source": [ + "Now, let's create or cGAN to generate facades from a template image. For this purpose, we will use the \"Facade\" dataset that consists of 506 Building Facades & corresponding Segmentations with split into train and test subsets." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Q_jf9H_NDESm" + }, + "source": [ + "Let's first create a few classes describing the layers we will use in the U-Net." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "uOKvYDyu0w8N" + }, + "outputs": [], + "source": [ + "# Importing all the libraries needed\n", + "import matplotlib.pyplot as plt\n", + "import glob\n", + "import random\n", + "import os\n", + "import numpy as np\n", + "import math\n", + "import itertools\n", + "import time\n", + "import datetime\n", + "from pathlib import Path\n", + "from PIL import Image\n", + "\n", + "from torch.utils.data import Dataset, DataLoader\n", + "import torchvision.transforms as transforms\n", + "from torchvision.utils import save_image, make_grid\n", + "from torchvision import datasets\n", + "from torch.autograd import Variable\n", + "\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "Zk5a6B5hILN2" + }, + "outputs": [], + "source": [ + "# code adapted from https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_parts.py\n", + "\n", + "# Input layer\n", + "class inconv(nn.Module):\n", + " def __init__(self, in_ch, out_ch):\n", + " super(inconv, self).__init__()\n", + " self.conv = nn.Sequential(\n", + " nn.Conv2d(in_ch, out_ch, kernel_size=4, padding=1, stride=2),\n", + " nn.LeakyReLU(negative_slope=0.2, inplace=True)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " x = self.conv(x)\n", + " return x\n", + "\n", + "# Encoder layer\n", + "class down(nn.Module):\n", + " def __init__(self, in_ch, out_ch):\n", + " super(down, self).__init__()\n", + " self.conv = nn.Sequential(\n", + " nn.Conv2d(in_ch, out_ch, kernel_size=4, padding=1, stride=2),\n", + " nn.BatchNorm2d(out_ch),\n", + " nn.LeakyReLU(negative_slope=0.2, inplace=True)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " x = self.conv(x)\n", + " return x\n", + "\n", + "# Decoder layer\n", + "class up(nn.Module):\n", + " def __init__(self, in_ch, out_ch, dropout=False):\n", + " super(up, self).__init__()\n", + " if dropout :\n", + " self.conv = nn.Sequential(\n", + " nn.ConvTranspose2d(in_ch, out_ch, kernel_size=4, padding=1, stride=2),\n", + " nn.BatchNorm2d(out_ch),\n", + " nn.Dropout(0.5, inplace=True),\n", + " nn.ReLU(inplace=True)\n", + " )\n", + " else:\n", + " self.conv = nn.Sequential(\n", + " nn.ConvTranspose2d(in_ch, out_ch, kernel_size=4, padding=1, stride=2),\n", + " nn.BatchNorm2d(out_ch),\n", + " nn.ReLU(inplace=True)\n", + " )\n", + "\n", + " def forward(self, x1, x2):\n", + " x1 = self.conv(x1)\n", + " x = torch.cat([x1, x2], dim=1)\n", + " return x\n", + "\n", + "# Output layer\n", + "class outconv(nn.Module):\n", + " def __init__(self, in_ch, out_ch):\n", + " super(outconv, self).__init__()\n", + " self.conv = nn.Sequential(\n", + " nn.ConvTranspose2d(in_ch, out_ch, kernel_size=4, padding=1, stride=2),\n", + " nn.Tanh()\n", + " )\n", + "\n", + " def forward(self, x):\n", + " x = self.conv(x)\n", + " return x" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "1rZ5Qz1mBUe8" + }, + "source": [ + "Now let's create the U-Net using the helper classes defined previously." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "4Tbp_535EVPW" + }, + "outputs": [], + "source": [ + "class U_Net(nn.Module):\n", + " ''' \n", + " Ck denotes a Convolution-BatchNorm-ReLU layer with k filters.\n", + " CDk denotes a Convolution-BatchNorm-Dropout-ReLU layer with a dropout rate of 50%\n", + " Encoder:\n", + " C64 - C128 - C256 - C512 - C512 - C512 - C512 - C512\n", + " Decoder:\n", + " CD512 - CD1024 - CD1024 - C1024 - C1024 - C512 - C256 - C128\n", + " '''\n", + " def __init__(self, n_channels, n_classes):\n", + " super(U_Net, self).__init__()\n", + " # Encoder\n", + " self.inc = inconv(n_channels, 64) # 64 filters\n", + " # TO DO :\n", + " # Create the 7 encoder layers called \"down1\" to \"down7\" following this sequence\n", + " # C64 - C128 - C256 - C512 - C512 - C512 - C512 - C512\n", + " # The first one has already been implemented\n", + " \n", + " \n", + " # Decoder\n", + " # TO DO :\n", + " # Create the 7 decoder layers called up1 to up7 following this sequence :\n", + " # CD512 - CD1024 - CD1024 - C1024 - C1024 - C512 - C256 - C128\n", + " # The last layer has already been defined\n", + " \n", + " \n", + " self.outc = outconv(128, n_classes) # 128 filters\n", + "\n", + " def forward(self, x):\n", + " x1 = self.inc(x)\n", + " x2 = self.down1(x1)\n", + " x3 = self.down2(x2)\n", + " x4 = self.down3(x3)\n", + " x5 = self.down4(x4)\n", + " x6 = self.down5(x5)\n", + " x7 = self.down6(x6)\n", + " x8 = self.down7(x7)\n", + " # At this stage x8 is our encoded vector, we will now decode it\n", + " x = self.up7(x8, x7)\n", + " x = self.up6(x, x6)\n", + " x = self.up5(x, x5)\n", + " x = self.up4(x, x4)\n", + " x = self.up3(x, x3)\n", + " x = self.up2(x, x2)\n", + " x = self.up1(x, x1)\n", + " x = self.outc(x)\n", + " return x" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "1hmcejTWJSYY" + }, + "outputs": [], + "source": [ + "# We take images that have 3 channels (RGB) as input and output an image that also have 3 channels (RGB)\n", + "generator=U_Net(3,3)\n", + "# Check that the architecture is as expected\n", + "generator" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "xIXFtHzcBUfO" + }, + "source": [ + "You should now have a working U-Net." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "RqD1katYBUfP" + }, + "source": [ + "<font color='red'>**Question 1**</font> \n", + "Knowing the input and output images will be 256x256, what will be the dimension of the encoded vector x8 ?\n", + "\n", + "Your answer :\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<font color='red'>**Question 2**</font> \n", + "As you can see, U-net has an encoder-decoder architecture with skip connections. Explain why it works better than a traditional encoder-decoder.\n", + "\n", + "Your anwer :" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "cchTp3thBUfR" + }, + "source": [ + "### Discriminator\n", + "\n", + "In the cGAN architecture, the chosen discriminator is a Patch GAN. It is a convolutional discriminator which enables to produce a map of the input pictures where each pixel represents a patch of size NxN of the input.\n", + "\n", + "\n", + "\n", + "The size N is given by the depth of the net. According to this table :\n", + "\n", + "| Number of layers | N |\n", + "| ---- | ---- |\n", + "| 1 | 16 |\n", + "| 2 | 34 |\n", + "| 3 | 70 |\n", + "| 4 | 142 |\n", + "| 5 | 286 |\n", + "| 6 | 574 |\n", + "\n", + "The number of layers actually means the number of layers with `kernel=(4,4)`, `padding=(1,1)` and `stride=(2,2)`. These layers are followed by 2 layers with `kernel=(4,4)`, `padding=(1,1)` and `stride=(1,1)`.\n", + "In our case we are going to create a 70x70 PatchGAN." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "ge6I7M0aBUfT" + }, + "source": [ + "Let's first create a few helping classes." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "RYqomFO8BUfV" + }, + "outputs": [], + "source": [ + "class conv_block(nn.Module):\n", + " def __init__(self, in_ch, out_ch, use_batchnorm=True, stride=2):\n", + " super(conv_block, self).__init__()\n", + " if use_batchnorm:\n", + " self.conv = nn.Sequential(\n", + " nn.Conv2d(in_ch, out_ch, kernel_size=4, padding=1, stride=stride),\n", + " nn.BatchNorm2d(out_ch),\n", + " nn.LeakyReLU(negative_slope=0.2, inplace=True)\n", + " )\n", + " else:\n", + " self.conv = nn.Sequential(\n", + " nn.Conv2d(in_ch, out_ch, kernel_size=4, padding=1, stride=stride),\n", + " nn.LeakyReLU(negative_slope=0.2, inplace=True)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " x = self.conv(x)\n", + " return x\n", + " \n", + "\n", + "class out_block(nn.Module):\n", + " def __init__(self, in_ch, out_ch):\n", + " super(out_block, self).__init__()\n", + " self.conv = nn.Sequential(\n", + " nn.Conv2d(in_ch, 1, kernel_size=4, padding=1, stride=1),\n", + " nn.Sigmoid()\n", + " )\n", + "\n", + " def forward(self, x):\n", + " x = self.conv(x)\n", + " return x" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "5m4Dnup4BUfc" + }, + "source": [ + "Now let's create the Patch GAN discriminator.\n", + "As we want a 70x70 Patch GAN, the architecture will be as follows :\n", + "```\n", + "1. C64 - K4, P1, S2\n", + "2. C128 - K4, P1, S2\n", + "3. C256 - K4, P1, S2\n", + "4. C512 - K4, P1, S1\n", + "5. C1 - K4, P1, S1 (output)\n", + "```\n", + "Where Ck denotes a convolution block with k filters, Kk a kernel of size k, Pk is the padding size and Sk the stride applied.\n", + "*Note :* For the first layer, we do not use batchnorm." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "AH6u5a-PBUfg" + }, + "source": [ + "<font color='red'>**Question 3**</font> \n", + "Knowing input images will be 256x256 with 3 channels each, how many parameters are there to learn ?\n", + "\n", + "Your answer : " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "g_9LxNhGBUfi" + }, + "outputs": [], + "source": [ + "class PatchGAN(nn.Module):\n", + " def __init__(self, n_channels, n_classes):\n", + " super(PatchGAN, self).__init__()\n", + " # TODO :\n", + " # create the 4 first layers named conv1 to conv4\n", + " self.conv1 =\n", + " self.conv2 =\n", + " self.conv3 =\n", + " self.conv4 =\n", + " # output layer\n", + " self.out = out_block(512, n_classes)\n", + " \n", + " def forward(self, x1, x2):\n", + " x = torch.cat([x2, x1], dim=1)\n", + " x = self.conv1(x)\n", + " x = self.conv2(x)\n", + " x = self.conv3(x)\n", + " x = self.conv4(x)\n", + " x = self.out(x)\n", + " return x" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "W_sevZRnBUfn" + }, + "outputs": [], + "source": [ + "# We have 6 input channels as we concatenate 2 images (with 3 channels each)\n", + "discriminator = PatchGAN(6,1)\n", + "discriminator" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "v_QubOycBUfv" + }, + "source": [ + "You should now have a working discriminator." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "DiI2CByRBUfz" + }, + "source": [ + "### Loss functions\n", + "\n", + "As we have seen in the choice of the various architectures for this GAN, the issue is to map both low and high frequencies.\n", + "To tackle this problem, this GAN rely on the architecture to map the high frequencies (U-Net + PatchGAN) and the loss function to learn low frequencies features. The global loss function will indeed be made of 2 parts :\n", + "* the first part to map hight frequencies, will try to optimize the mean squared error of the GAN.\n", + "* the second part to map low frequencies, will minimize the $\\mathcal{L}_1$ norm of the generated picture.\n", + "\n", + "So the loss can be defined as $$ G^* = arg\\ \\underset{G}{min}\\ \\underset{D}{max}\\ \\mathcal{L}_{cGAN}(G,D) + \\lambda \\mathcal{L}_1(G)$$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "k4G_xewPBUf4" + }, + "outputs": [], + "source": [ + "# Loss functions\n", + "criterion_GAN = torch.nn.MSELoss()\n", + "criterion_pixelwise = torch.nn.L1Loss()\n", + "\n", + "# Loss weight of L1 pixel-wise loss between translated image and real image\n", + "lambda_pixel = 100" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "c12q2NwkBUf7" + }, + "source": [ + "### Training and evaluating models " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "vGKjO0UMBUf9" + }, + "outputs": [], + "source": [ + "# parameters\n", + "epoch = 0 # epoch to start training from\n", + "n_epoch = 200 # number of epochs of training\n", + "batch_size =10 # size of the batches\n", + "lr = 0.0002 # adam: learning rate\n", + "b1 =0.5 # adam: decay of first order momentum of gradient\n", + "b2 = 0.999 # adam: decay of first order momentum of gradient\n", + "decay_epoch = 100 # epoch from which to start lr decay\n", + "img_height = 256 # size of image height\n", + "img_width = 256 # size of image width\n", + "channels = 3 # number of image channels\n", + "sample_interval = 500 # interval between sampling of images from generators\n", + "checkpoint_interval = -1 # interval between model checkpoints\n", + "cuda = True if torch.cuda.is_available() else False # do you have cuda ?" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "PhPkU7BDYooV" + }, + "source": [ + "Download the dataset. \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "!wget https://partage.liris.cnrs.fr/index.php/s/4L9JpxxHBGc4rRR/download/CMP_facade_DB_base.zip\n", + "!wget https://partage.liris.cnrs.fr/index.php/s/SyrJb7mASjyDQR9/download/CMP_facade_DB_extended.zip" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import zipfile\n", + "\n", + "# Extract in the correct folder\n", + "with zipfile.ZipFile(\"CMP_facade_DB_base.zip\", 'r') as zip_ref:\n", + " zip_ref.extractall(\"./facades\")\n", + " os.rename(\"./facades/base\", \"./facades/train\")\n", + "\n", + "# Extract in the correct folder\n", + "with zipfile.ZipFile(\"CMP_facade_DB_extended.zip\", 'r') as zip_ref:\n", + " zip_ref.extractall(\"./facades\")\n", + " os.rename(\"./facades/extended\", \"./facades/val\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "6DHT9c0_BUgA" + }, + "source": [ + "Configure the dataloader" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "rxi_QIpgBUgB" + }, + "outputs": [], + "source": [ + "class ImageDataset(Dataset):\n", + " def __init__(self, root, transforms_=None, mode='train'):\n", + " self.transform = transforms.Compose(transforms_)\n", + "\n", + " self.files_img = sorted(glob.glob(os.path.join(root, mode) + '/*.jpg'))\n", + " if mode == 'val':\n", + " self.files_img.extend(\n", + " sorted(glob.glob(os.path.join(root, 'val') + '/*.jpg')))\n", + "\n", + " self.files_mask = sorted(glob.glob(os.path.join(root, mode) + '/*.png'))\n", + " if mode == 'val':\n", + " self.files_mask.extend(\n", + " sorted(glob.glob(os.path.join(root, 'val') + '/*.png')))\n", + " \n", + " assert len(self.files_img) == len(self.files_mask)\n", + "\n", + " def __getitem__(self, index):\n", + "\n", + " img = Image.open(self.files_img[index % len(self.files_img)])\n", + " mask = Image.open(self.files_mask[index % len(self.files_img)])\n", + " mask = mask.convert('RGB')\n", + "\n", + " img = self.transform(img)\n", + " mask = self.transform(mask)\n", + "\n", + " return img, mask\n", + "\n", + " def __len__(self):\n", + " return len(self.files_img)\n", + " \n", + "# Configure dataloaders\n", + "transforms_ = [transforms.Resize((img_height, img_width), Image.BICUBIC),\n", + " transforms.ToTensor()] # transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))\n", + "\n", + "dataloader = DataLoader(ImageDataset(\"facades\", transforms_=transforms_),\n", + " batch_size=16, shuffle=True)\n", + "\n", + "val_dataloader = DataLoader(ImageDataset(\"facades\", transforms_=transforms_, mode='val'),\n", + " batch_size=8, shuffle=False)\n", + "\n", + "# Tensor type\n", + "Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Okb3LU76BUgG" + }, + "source": [ + "Check the loading works and a few helper functions" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "xuxq4TZRBUgJ" + }, + "outputs": [], + "source": [ + "def plot2x2Array(image, mask):\n", + " f, axarr = plt.subplots(1, 2)\n", + " axarr[0].imshow(image)\n", + " axarr[1].imshow(mask)\n", + "\n", + " axarr[0].set_title('Image')\n", + " axarr[1].set_title('Mask')\n", + "\n", + "\n", + "def reverse_transform(image):\n", + " image = image.numpy().transpose((1, 2, 0))\n", + " image = np.clip(image, 0, 1)\n", + " image = (image * 255).astype(np.uint8)\n", + "\n", + " return image\n", + "\n", + "def plot2x3Array(image, mask,predict):\n", + " f, axarr = plt.subplots(1,3,figsize=(15,15))\n", + " axarr[0].imshow(image)\n", + " axarr[1].imshow(mask)\n", + " axarr[2].imshow(predict)\n", + " axarr[0].set_title('input')\n", + " axarr[1].set_title('real')\n", + " axarr[2].set_title('fake')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "m2NxLrQEBUgM" + }, + "outputs": [], + "source": [ + "image, mask = next(iter(dataloader))\n", + "image = reverse_transform(image[0])\n", + "mask = reverse_transform(mask[0])\n", + "plot2x2Array(image, mask)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "zAvaxAbxBUgQ" + }, + "source": [ + "Initialize our GAN" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "dVgF3qfDBUgR" + }, + "outputs": [], + "source": [ + "# Calculate output of image discriminator (PatchGAN)\n", + "patch = (1, img_height//2**3-2, img_width//2**3-2)\n", + "\n", + "if cuda:\n", + " generator = generator.cuda()\n", + " discriminator = discriminator.cuda()\n", + " criterion_GAN.cuda()\n", + " criterion_pixelwise.cuda()\n", + " \n", + "# Optimizers\n", + "optimizer_G = torch.optim.Adam(generator.parameters(), lr=lr, betas=(b1, b2))\n", + "optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=lr, betas=(b1, b2))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rN3cbiWaBUgf" + }, + "source": [ + "Start training" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "msmQQUX-BUgh" + }, + "outputs": [], + "source": [ + "def save_model(epoch):\n", + " # save your work\n", + " torch.save({\n", + " 'epoch': epoch,\n", + " 'model_state_dict': generator.state_dict(),\n", + " 'optimizer_state_dict': optimizer_G.state_dict(),\n", + " 'loss': loss_G,\n", + " }, 'generator_'+str(epoch)+'.pth')\n", + " torch.save({\n", + " 'epoch': epoch,\n", + " 'model_state_dict': discriminator.state_dict(),\n", + " 'optimizer_state_dict': optimizer_D.state_dict(),\n", + " 'loss': loss_D,\n", + " }, 'discriminator_'+str(epoch)+'.pth')\n", + " \n", + "def weights_init_normal(m):\n", + " classname = m.__class__.__name__\n", + " if classname.find('Conv') != -1:\n", + " torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\n", + " elif classname.find('BatchNorm2d') != -1:\n", + " torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\n", + " torch.nn.init.constant_(m.bias.data, 0.0)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "6UXrZLLNBUgq" + }, + "source": [ + "<font color='red'>Complete the loss function </font> in the following training code and train your network: " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "7NUuGcQ0SiJw" + }, + "outputs": [], + "source": [ + "# ----------\n", + "# Training\n", + "# ----------\n", + "\n", + "losses = []\n", + "num_epochs = 200\n", + "\n", + "# Initialize weights\n", + "generator.apply(weights_init_normal)\n", + "discriminator.apply(weights_init_normal)\n", + "epoch_D = 0\n", + "epoch_G = 0\n", + "\n", + "# train the network\n", + "discriminator.train()\n", + "generator.train()\n", + "print_every = 400\n", + "\n", + "for epoch in range(epoch_G, num_epochs):\n", + " for i, batch in enumerate(dataloader):\n", + "\n", + " # Model inputs\n", + " real_A = Variable(batch[0].type(Tensor))\n", + " real_B = Variable(batch[1].type(Tensor))\n", + "\n", + " # Adversarial ground truths\n", + " valid = Variable(Tensor(np.ones((real_B.size(0), *patch))), requires_grad=False)\n", + " fake = Variable(Tensor(np.zeros((real_B.size(0), *patch))), requires_grad=False)\n", + "\n", + " # ------------------\n", + " # Train Generators\n", + " # ------------------\n", + "\n", + " optimizer_G.zero_grad()\n", + "\n", + " # GAN loss\n", + " # TO DO: Put here your GAN loss\n", + "\n", + " # Pixel-wise loss\n", + " # TO DO: Put here your pixel loss\n", + "\n", + " # Total loss\n", + " # TO DO: Put here your total loss\n", + "\n", + " loss_G.backward()\n", + "\n", + " optimizer_G.step()\n", + "\n", + " # ---------------------\n", + " # Train Discriminator\n", + " # ---------------------\n", + "\n", + " optimizer_D.zero_grad()\n", + "\n", + " # Real loss\n", + " pred_real = discriminator(real_A, real_B)\n", + " loss_real = criterion_GAN(pred_real, valid)\n", + "\n", + " # Fake loss\n", + " pred_fake = discriminator(fake_A.detach(), real_B)\n", + " loss_fake = criterion_GAN(pred_fake, fake)\n", + "\n", + " # Total loss\n", + " loss_D = 0.5 * (loss_real + loss_fake)\n", + "\n", + " loss_D.backward()\n", + " optimizer_D.step()\n", + " \n", + " # Print some loss stats\n", + " if i % print_every == 0:\n", + " # print discriminator and generator loss\n", + " print('Epoch [{:5d}/{:5d}] | d_loss: {:6.4f} | g_loss: {:6.4f}'.format(\n", + " epoch+1, num_epochs, loss_D.item(), loss_G.item()))\n", + " ## AFTER EACH EPOCH##\n", + " # append discriminator loss and generator loss\n", + " losses.append((loss_D.item(), loss_G.item()))\n", + " if epoch % 100 == 0:\n", + " print('Saving model...')\n", + " save_model(epoch)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Ed-ZbuVWBUgu" + }, + "source": [ + "Observation of the loss along the training" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "nOLW054DTLpg" + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "losses = np.array(losses)\n", + "plt.plot(losses.T[0], label='Discriminator')\n", + "plt.plot(losses.T[1], label='Generator')\n", + "plt.title(\"Training Losses\")\n", + "plt.legend()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "S58kJj9HBUgV" + }, + "source": [ + "If the training takes too much time, you can use a pretrained model in the meantime, to evaluate its performance.\n", + "\n", + "It is available at : https://partage.liris.cnrs.fr/index.php/s/xwEFmxn9ANeq4zY" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "i0TC5qK3BUg4" + }, + "source": [ + "### Evaluate your cGAN" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "fYBRR6NYBUg6" + }, + "outputs": [], + "source": [ + "def load_model(epoch=200):\n", + " if 'generator_'+str(epoch)+'.pth' in os.listdir() and 'discriminator_'+str(epoch)+'.pth' in os.listdir():\n", + " if cuda:\n", + " checkpoint_generator = torch.load('generator_'+str(epoch)+'.pth')\n", + " else:\n", + " checkpoint_generator = torch.load('generator_'+str(epoch)+'.pth', map_location='cpu')\n", + " generator.load_state_dict(checkpoint_generator['model_state_dict'])\n", + " optimizer_G.load_state_dict(checkpoint_generator['optimizer_state_dict'])\n", + " epoch_G = checkpoint_generator['epoch']\n", + " loss_G = checkpoint_generator['loss']\n", + "\n", + " if cuda:\n", + " checkpoint_discriminator = torch.load('discriminator_'+str(epoch)+'.pth')\n", + " else:\n", + " checkpoint_discriminator = torch.load('discriminator_'+str(epoch)+'.pth', map_location='cpu')\n", + " discriminator.load_state_dict(checkpoint_discriminator['model_state_dict'])\n", + " optimizer_D.load_state_dict(checkpoint_discriminator['optimizer_state_dict'])\n", + " epoch_D = checkpoint_discriminator['epoch']\n", + " loss_D = checkpoint_discriminator['loss']\n", + " else:\n", + " print('There isn\\' a training available with this number of epochs')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "4V0DwQomBUg9" + }, + "outputs": [], + "source": [ + "load_model(epoch=200)\n", + "\n", + "# switching mode\n", + "generator.eval()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "gyvmvkIvBUhB" + }, + "outputs": [], + "source": [ + "# show a sample evaluation image on the training base\n", + "image, mask = next(iter(dataloader))\n", + "output = generator(mask.type(Tensor))\n", + "output = output.view(16, 3, 256, 256)\n", + "output = output.cpu().detach()\n", + "for i in range(8):\n", + " image_plot = reverse_transform(image[i])\n", + " output_plot = reverse_transform(output[i])\n", + " mask_plot = reverse_transform(mask[i])\n", + " plot2x3Array(mask_plot,image_plot,output_plot)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "nqvrxBoGBUhD" + }, + "outputs": [], + "source": [ + "# show a sample evaluation image on the validation dataset\n", + "image, mask = next(iter(val_dataloader))\n", + "output = generator(mask.type(Tensor))\n", + "output = output.view(8, 3, 256, 256)\n", + "output = output.cpu().detach()\n", + "for i in range(8):\n", + " image_plot = reverse_transform(image[i])\n", + " output_plot = reverse_transform(output[i])\n", + " mask_plot = reverse_transform(mask[i])\n", + " plot2x3Array(mask_plot,image_plot,output_plot)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "qkFVjRsOBUhG" + }, + "source": [ + "<font color='red'>**Question 4**</font> \n", + "Compare results for 100 and 200 epochs" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "k85Cl5_UDWyv" + }, + "outputs": [], + "source": [ + "# TO DO : Your code here to load and evaluate with a few samples\n", + "# a model after 100 epochs\n", + "\n" + ] + } + ], + "metadata": { + "colab": { + "collapsed_sections": [], + "name": "BE2 - GAN and cGAN.ipynb", + "provenance": [] + }, + "kernelspec": { + "display_name": "llm", + "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.11.11" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +}