"This work must be done individually. The expected output is a repository named gan-cgan on https://gitlab.ec-lyon.fr. It must contain your notebook (or python files) and a README.md file that explains briefly the successive steps of the project. The last commit is due before 11:59 pm on Wednesday, March 29, 2023. Subsequent commits will not be considered."
"This work must be done individually. The expected output is a private repository named gan-cgan on https://gitlab.ec-lyon.fr. It must contain your notebook (or python files) and a README.md file that explains briefly the successive steps of the project. Don't forget to add your teacher as developer member of the project. The last commit is due before 11:59 pm on Monday, April 1st, 2024. Subsequent commits will not be considered."
]
]
}
}
],
],
...
...
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
<h1><big><center>MSO 3.4 - Deep Structured Learning</center></big></h1>
<h1><big><center>MSO 3.4 - Deep Structured Learning</center></big></h1>
<h2><big><center> BE 2 - GANs and cGAN </center></big></h2>
<h2><big><center> BE 2 - GANs and cGAN </center></big></h2>
<h5><big><center>Adapted from <i>Projet d'Option</i> of : Mhamed Jabri, Martin Chauvin, Ahmed Sahraoui, Zakariae Moustaïne and Taoufik Bouchikhi
<h5><big><center>Adapted from <i>Projet d'Option</i> of : Mhamed Jabri, Martin Chauvin, Ahmed Sahraoui, Zakariae Moustaïne and Taoufik Bouchikhi
The aim of this assignment 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 ! )
The aim of this assignment 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 ! )
Before starting the exploration of the world of GANs, here's what students should do and send back for this assignement :
Before starting the exploration of the world of GANs, here's what students should do and send back for this assignement :
* In the "tutorial" parts of this assignement that focus on explaining new concepts, you'll find <fontcolor='red'>**questions**</font> that aim to test your understanding of those concepts.
* In the "tutorial" parts of this assignement that focus on explaining new concepts, you'll find <fontcolor='red'>**questions**</font> that aim to test your understanding of those concepts.
* In some of the code cells, you'll have to complete the code and you'll find a "TO DO" explaining what you should implement.
* In some of the code cells, you'll have to complete the code and you'll find a "TO DO" explaining what you should implement.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# Part1: DC-GAN
# Part1: DC-GAN
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
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
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
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
##Work to do
##Work to do
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)
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)
Please re-train the DCGAN and display some automatically generated handwritten digits.
Please re-train the DCGAN and display some automatically generated handwritten digits.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
#TO DO: your code here to adapt the code from the tutorial to experiment on MNIST dataset
#TO DO: your code here to adapt the code from the tutorial to experiment on MNIST dataset
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# Part2: Conditional GAN (cGAN)
# Part2: Conditional GAN (cGAN)
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Let's take the example of the set described in the next picture.
Let's take the example of the set described in the next picture.


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.
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.
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).
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).
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).
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).


%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### Generator
### Generator
In the cGAN architecture, the generator chosen is a U-Net.
In the cGAN architecture, the generator chosen is a U-Net.
A U-Net takes as input an image, and outputs another image.
A U-Net takes as input an image, and outputs another image.
It can be divided into 2 subparts : an encoder and a decoder.
It can be divided into 2 subparts : an encoder and a decoder.
* The encoder takes the input image and reduces its dimension to encode the main features into a vector.
* The encoder takes the input image and reduces its dimension to encode the main features into a vector.
* The decoder takes this vector and map the features stored into an image.
* The decoder takes this vector and map the features stored into an image.
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.
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.
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.
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 id: tags:
%% Cell type:markdown id: tags:
Now, let's create or cGAN to generate facades from a template image. For this purpose, we will use the "Facade" dataset available at http://cmp.felk.cvut.cz/~tylecr1/facade/.
Now, let's create or cGAN to generate facades from a template image. For this purpose, we will use the "Facade" dataset available at http://cmp.felk.cvut.cz/~tylecr1/facade/.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Let's first create a few classes describing the layers we will use in the U-Net.
Let's first create a few classes describing the layers we will use in the U-Net.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# Importing all the libraries needed
# Importing all the libraries needed
importmatplotlib.pyplotasplt
importmatplotlib.pyplotasplt
importimageio
importimageio
importglob
importglob
importrandom
importrandom
importos
importos
importnumpyasnp
importnumpyasnp
importmath
importmath
importitertools
importitertools
importtime
importtime
importdatetime
importdatetime
importcv2
importcv2
frompathlibimportPath
frompathlibimportPath
fromPILimportImage
fromPILimportImage
fromtorch.utils.dataimportDataset,DataLoader
fromtorch.utils.dataimportDataset,DataLoader
importtorchvision.transformsastransforms
importtorchvision.transformsastransforms
fromtorchvision.utilsimportsave_image,make_grid
fromtorchvision.utilsimportsave_image,make_grid
fromtorchvisionimportdatasets
fromtorchvisionimportdatasets
fromtorch.autogradimportVariable
fromtorch.autogradimportVariable
importtorch.nnasnn
importtorch.nnasnn
importtorch.nn.functionalasF
importtorch.nn.functionalasF
importtorch
importtorch
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# code adapted from https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_parts.py
# code adapted from https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_parts.py
# At this stage x8 is our encoded vector, we will now decode it
# At this stage x8 is our encoded vector, we will now decode it
x=self.up7(x8,x7)
x=self.up7(x8,x7)
x=self.up6(x,x6)
x=self.up6(x,x6)
x=self.up5(x,x5)
x=self.up5(x,x5)
x=self.up4(x,x4)
x=self.up4(x,x4)
x=self.up3(x,x3)
x=self.up3(x,x3)
x=self.up2(x,x2)
x=self.up2(x,x2)
x=self.up1(x,x1)
x=self.up1(x,x1)
x=self.outc(x)
x=self.outc(x)
returnx
returnx
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# We take images that have 3 channels (RGB) as input and output an image that also have 3 channels (RGB)
# We take images that have 3 channels (RGB) as input and output an image that also have 3 channels (RGB)
generator=U_Net(3,3)
generator=U_Net(3,3)
# Check that the architecture is as expected
# Check that the architecture is as expected
generator
generator
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
You should now have a working U-Net.
You should now have a working U-Net.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 1**</font>
<fontcolor='red'>**Question 1**</font>
Knowing the input and output images will be 256x256, what will be the dimension of the encoded vector x8 ?
Knowing the input and output images will be 256x256, what will be the dimension of the encoded vector x8 ?
<fontcolor='red'>**Question 2**</font>
<fontcolor='red'>**Question 2**</font>
As you can see, U-net has an encoder-decoder architecture with skip connections. Explain why it works better than a traditional encoder-decoder.
As you can see, U-net has an encoder-decoder architecture with skip connections. Explain why it works better than a traditional encoder-decoder.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### Discriminator
### Discriminator
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.
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.
The size N is given by the depth of the net. According to this table :
The size N is given by the depth of the net. According to this table :
| Number of layers | N |
| Number of layers | N |
| ---- | ---- |
| ---- | ---- |
| 1 | 16 |
| 1 | 16 |
| 2 | 34 |
| 2 | 34 |
| 3 | 70 |
| 3 | 70 |
| 4 | 142 |
| 4 | 142 |
| 5 | 286 |
| 5 | 286 |
| 6 | 574 |
| 6 | 574 |
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)`.
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)`.
In our case we are going to create a 70x70 PatchGAN.
In our case we are going to create a 70x70 PatchGAN.
As we want a 70x70 Patch GAN, the architecture will be as follows :
As we want a 70x70 Patch GAN, the architecture will be as follows :
```
```
1. C64 - K4, P1, S2
1. C64 - K4, P1, S2
2. C128 - K4, P1, S2
2. C128 - K4, P1, S2
3. C256 - K4, P1, S2
3. C256 - K4, P1, S2
4. C512 - K4, P1, S1
4. C512 - K4, P1, S1
5. C1 - K4, P1, S1 (output)
5. C1 - K4, P1, S1 (output)
```
```
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.
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.
*Note :* For the first layer, we do not use batchnorm.
*Note :* For the first layer, we do not use batchnorm.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 3**</font>
<fontcolor='red'>**Question 3**</font>
Knowing input images will be 256x256 with 3 channels each, how many parameters are there to learn ?
Knowing input images will be 256x256 with 3 channels each, how many parameters are there to learn ?
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
classPatchGAN(nn.Module):
classPatchGAN(nn.Module):
def__init__(self,n_channels,n_classes):
def__init__(self,n_channels,n_classes):
super(PatchGAN,self).__init__()
super(PatchGAN,self).__init__()
# TODO :
# TODO :
# create the 4 first layers named conv1 to conv4
# create the 4 first layers named conv1 to conv4
self.conv1=
self.conv1=
self.conv2=
self.conv2=
self.conv3=
self.conv3=
self.conv4=
self.conv4=
# output layer
# output layer
self.out=out_block(512,n_classes)
self.out=out_block(512,n_classes)
defforward(self,x1,x2):
defforward(self,x1,x2):
x=torch.cat([x2,x1],dim=1)
x=torch.cat([x2,x1],dim=1)
x=self.conv1(x)
x=self.conv1(x)
x=self.conv2(x)
x=self.conv2(x)
x=self.conv3(x)
x=self.conv3(x)
x=self.conv4(x)
x=self.conv4(x)
x=self.out(x)
x=self.out(x)
returnx
returnx
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# We have 6 input channels as we concatenate 2 images (with 3 channels each)
# We have 6 input channels as we concatenate 2 images (with 3 channels each)
discriminator=PatchGAN(6,1)
discriminator=PatchGAN(6,1)
discriminator
discriminator
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
You should now have a working discriminator.
You should now have a working discriminator.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### Loss functions
### Loss functions
As we have seen in the choice of the various architectures for this GAN, the issue is to map both low and high frequencies.
As we have seen in the choice of the various architectures for this GAN, the issue is to map both low and high frequencies.
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 :
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 :
* the first part to map hight frequencies, will try to optimize the mean squared error of the GAN.
* the first part to map hight frequencies, will try to optimize the mean squared error of the GAN.
* the second part to map low frequencies, will minimize the $\mathcal{L}_1$ norm of the generated picture.
* the second part to map low frequencies, will minimize the $\mathcal{L}_1$ norm of the generated picture.
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)$$
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 id: tags:
%% Cell type:code id: tags:
``` python
``` python
# Loss functions
# Loss functions
criterion_GAN=torch.nn.MSELoss()
criterion_GAN=torch.nn.MSELoss()
criterion_pixelwise=torch.nn.L1Loss()
criterion_pixelwise=torch.nn.L1Loss()
# Loss weight of L1 pixel-wise loss between translated image and real image
# Loss weight of L1 pixel-wise loss between translated image and real image
lambda_pixel=100
lambda_pixel=100
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### Training and evaluating models
### Training and evaluating models
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# parameters
# parameters
epoch=0# epoch to start training from
epoch=0# epoch to start training from
n_epoch=200# number of epochs of training
n_epoch=200# number of epochs of training
batch_size=10# size of the batches
batch_size=10# size of the batches
lr=0.0002# adam: learning rate
lr=0.0002# adam: learning rate
b1=0.5# adam: decay of first order momentum of gradient
b1=0.5# adam: decay of first order momentum of gradient
b2=0.999# adam: decay of first order momentum of gradient
b2=0.999# adam: decay of first order momentum of gradient
decay_epoch=100# epoch from which to start lr decay
decay_epoch=100# epoch from which to start lr decay
img_height=256# size of image height
img_height=256# size of image height
img_width=256# size of image width
img_width=256# size of image width
channels=3# number of image channels
channels=3# number of image channels
sample_interval=500# interval between sampling of images from generators
sample_interval=500# interval between sampling of images from generators
checkpoint_interval=-1# interval between model checkpoints
checkpoint_interval=-1# interval between model checkpoints
cuda=Trueiftorch.cuda.is_available()elseFalse# do you have cuda ?
cuda=Trueiftorch.cuda.is_available()elseFalse# do you have cuda ?
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Download the dataset.
Download the dataset.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
importurllib.request
importurllib.request
fromtqdmimporttqdm
fromtqdmimporttqdm
importos
importos
importzipfile
importzipfile
defdownload_hook(t):
defdownload_hook(t):
"""Wraps tqdm instance.
"""Wraps tqdm instance.
Don't forget to close() or __exit__()
Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
the tqdm instance once you're done with it (easiest using `with` syntax).
print('There isn\' a training available with this number of epochs')
print('There isn\' a training available with this number of epochs')
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
load_model(epoch=200)
load_model(epoch=200)
# switching mode
# switching mode
generator.eval()
generator.eval()
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# show a sample evaluation image on the training base
# show a sample evaluation image on the training base
image,mask=next(iter(dataloader))
image,mask=next(iter(dataloader))
output=generator(mask.type(Tensor))
output=generator(mask.type(Tensor))
output=output.view(16,3,256,256)
output=output.view(16,3,256,256)
output=output.cpu().detach()
output=output.cpu().detach()
foriinrange(8):
foriinrange(8):
image_plot=reverse_transform(image[i])
image_plot=reverse_transform(image[i])
output_plot=reverse_transform(output[i])
output_plot=reverse_transform(output[i])
mask_plot=reverse_transform(mask[i])
mask_plot=reverse_transform(mask[i])
plot2x3Array(mask_plot,image_plot,output_plot)
plot2x3Array(mask_plot,image_plot,output_plot)
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# show a sample evaluation image on the validation dataset
# show a sample evaluation image on the validation dataset
image,mask=next(iter(val_dataloader))
image,mask=next(iter(val_dataloader))
output=generator(mask.type(Tensor))
output=generator(mask.type(Tensor))
output=output.view(8,3,256,256)
output=output.view(8,3,256,256)
output=output.cpu().detach()
output=output.cpu().detach()
foriinrange(8):
foriinrange(8):
image_plot=reverse_transform(image[i])
image_plot=reverse_transform(image[i])
output_plot=reverse_transform(output[i])
output_plot=reverse_transform(output[i])
mask_plot=reverse_transform(mask[i])
mask_plot=reverse_transform(mask[i])
plot2x3Array(mask_plot,image_plot,output_plot)
plot2x3Array(mask_plot,image_plot,output_plot)
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 4**</font>
<fontcolor='red'>**Question 4**</font>
Compare results for 100 and 200 epochs
Compare results for 100 and 200 epochs
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# TO DO : Your code here to load and evaluate with a few samples
# TO DO : Your code here to load and evaluate with a few samples
# a model after 100 epochs
# a model after 100 epochs
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# And finally :
# And finally :
ifcuda:
ifcuda:
torch.cuda.empty_cache()
torch.cuda.empty_cache()
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# How to submit your Work ?
# How to submit your Work ?
This work must be done individually. The expected output is a repository named gan-cgan on https://gitlab.ec-lyon.fr. It must contain your notebook (or python files) and a README.md file that explains briefly the successive steps of the project. The last commit is due before 11:59 pm on Wednesday, March 29, 2023. Subsequent commits will not be considered.
This work must be done individually. The expected output is a private repository named gan-cgan on https://gitlab.ec-lyon.fr. It must contain your notebook (or python files) and a README.md file that explains briefly the successive steps of the project. Don't forget to add your teacher as developer member of the project. The last commit is due before 11:59 pm on Monday, April 1st, 2024. Subsequent commits will not be considered.