Full text
Generation of Content Through Antagonic Generative Networks Generación de contenido mediante Redes Generativas Antagónicas By García Patiño Lenza, Guillermo Alejandra Córdova, Daniela Quiñones Pérez, Mario Trabajo de fin de grado del Grado en Ingeniería Informática Facultad de Informática Universidad Complutense de Madrid Directed by Antonio Alejandro Sánchez Ruiz-Granados Madrid, 2021-2022
Abstract This work is used to explore machine learning methods for generating images, in particular, we explore the Generative Adversarial Networks (or GANs) and how these are used to generate new synthetic samples for datasets. This project is mainly focused on the generation of images through different techniques. Most of our work consists of understanding these fairly new models and implementing them ourselves, to then use them to generate images and test how well each of them works. Most machine learning methods need large sums of examples for them to understand how to fully operate in most cases, this is where GANs shine, as they can create new samples for these preestablished datasets that may not contain enough. Not only that but also the fact that this task requires a thorough understanding of the dataset makes the GAN an excellent judge for that dataset. This research has led us to understand the strengths and shortcomings of each sort of model that we produced, as well as how the next one improved on it while giving up something in return, which in most cases was time because these types of models take a long time to provide useful findings that can then be analyzed. Because these content generators aren’t perfect, they cannot be employed in operations that need a high level of precision. However, this establishes a foundation from which other types of content generators can grow and evolve, leveraging their strengths to build stronger models. Another issue with these models is that the created content can only copy current ones and cannot develop new ones, resulting in bias. In a nutshell, this study serves as a foundation for understanding current breakthroughs in generative machine learning algorithms and how they are used to generate new material from an existing dataset using GANs. KeyWords Style Transfer, GAN, Image Generation, Neural Networks, Machine Learning, Deep Learning, Artificial Intelligence ii
Resumen Este trabajo se utiliza para explorar los métodos de aprendizaje automático de generación de imágenes, en particular exploramos las Redes Generativas Adversarias (o GANs) y cómo éstas se utilizan para generar nuevas muestras sintéticas para conjuntos de datos. Este proyecto se centra principalmente en la generación de imágenes mediante diferentes técnicas. La mayor parte de nuestro trabajo consiste en comprender estos modelos novedosos e implementarlos nosotros mismos, y así luego utilizarlos para generar imágenes y probar su funcionalidad. La mayoría de los métodos de aprendizaje automático necesitan grandes sumas de ejemplos para entender cómo funcionan completamente en los distintos casos, aquí es donde las GANs brillan, ya que pueden crear nuevas muestras para estos conjuntos de datos preestablecidos que pueden no contener suficientes. No sólo eso, sino que el hecho de que esta tarea requiera un conocimiento profundo del conjunto de datos por parte del modelo, hace que el GAN sea un excelente juez para ese conjunto de datos. Esta investigación nos ha llevado a comprender los puntos fuertes y débiles de cada tipo de modelo que hemos producido, así como la forma en que el siguiente lo mejoraba renunciando a algo a cambio, que en la mayoría de los casos era el tiempo, porque este tipo de modelos necesitan mucho tiempo para poder proporcionar resultados útiles que puedan ser analizados. Como estos generadores de contenidos no son perfectos, no pueden emplearse en operaciones que necesiten un alto nivel de precisión. Sin embargo, esto establece una base a partir de la cual otros tipos de generadores de contenido pueden crecer y evolucionar, aprovechando sus puntos fuertes para construir modelos más sólidos. Otro problema de estos modelos es que los contenidos creados sólo pueden copiar los actuales y no pueden desarrollar otros nuevos, lo que provoca un sesgo. En pocas palabras, este estudio sirve de base para comprender los avances actuales en los algoritmos de aprendizaje automático generativo y cómo se utilizan para generar nuevo material a partir de un conjunto de datos existente utilizando GANs. Palabras Clave Transferencia de estilos, GAN, Generación de Imagenes, Redes Neuronales, Aprendizaje automatico, Aprendizaje profundo, Inteligencia artificial iii
Contents Page 1 Introduction 2 1.1 Objectives................................... 3 1.2 RoadMap(WorkPlan) ........................... 4 1.3 Memorystructure............................... 6 1.4 Code...................................... 6 1.4.1 Github’s Structure . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2 Generative Adversarial Networks 1 2.1 NeuralNetworks ............................... 1 2.1.1 How Neural Networks Work . . . . . . . . . . . . . . . . . . . . . 1 2.1.2 TypesofLayers............................ 2 2.1.3 CostFunctions ............................ 7 2.1.4 Training using gradient descent . . . . . . . . . . . . . . . . . . . 7 2.2 Generative Adversarial Networks . . . . . . . . . . . . . . . . . . . . . . 9 2.2.1 GANarchitecture........................... 10 2.2.2 Reaching a state of equilibrium . . . . . . . . . . . . . . . . . . . 10 2.2.3 Evaluation .............................. 11 2.2.4 GANChallenges ........................... 12 2.2.5 Stoptraining ............................. 14 2.3 Frameworks and libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3 Simple GAN: Image Generation 16 3.1 Definition of a Simple GAN . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.2 Architecture.................................. 17 3.2.1 Generator............................... 17 3.2.2 Discriminator............................. 18 3.3 Training.................................... 19 3.4 Experiments and Results . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3.4.1 MNISTDataset............................ 19 3.4.2 First Experiment: One Class Dataset . . . . . . . . . . . . . . . . 19 3.4.3 Second Experiment: Two classes Dataset . . . . . . . . . . . . . . 21 3.4.4 Third Experiment: More than two classes Datasets . . . . . . . . 23 3.4.5 Conclusions.............................. 24 4 Conditional GAN: Conditional Image Generation 25 4.1 Definition of a Conditional GAN . . . . . . . . . . . . . . . . . . . . . . 25 4.2 Architecture.................................. 26 iv
TFG Gans 2022 UCM 4.2.1 Generator............................... 26 4.2.2 Discriminator............................. 27 4.3 TrainingDetails................................ 28 4.4 Experiments and results . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 4.4.1 Fruits-360 Dataset . . . . . . . . . . . . . . . . . . . . . . . . . . 29 4.4.2 Conditional image generation . . . . . . . . . . . . . . . . . . . . 29 4.4.3 Conclusions.............................. 31 5 StyleGAN: Style Image Generation 33 5.1 Definition of a StyleGAN . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 5.1.1 StyleGAN Components . . . . . . . . . . . . . . . . . . . . . . . 34 5.2 Architecture.................................. 40 5.2.1 Generator............................... 40 5.2.2 Discriminator............................. 43 5.3 TrainingDetails................................ 44 5.4 Experiments and Results . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 5.4.1 InitialTraining............................ 45 5.4.2 StyleMixing ............................. 48 5.4.3 Conclusions.............................. 48 6 CycleGAN : Style Semantic Transfer 51 6.1 Definition of a CycleGAN . . . . . . . . . . . . . . . . . . . . . . . . . . 51 6.2 Architecture.................................. 52 6.2.1 Generator............................... 52 6.2.2 Discriminator............................. 53 6.2.3 CycleGAN Loss Functions . . . . . . . . . . . . . . . . . . . . . . 54 6.3 TrainingDetails................................ 57 6.4 Experiments and Results . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 6.5 Conclusions.................................. 59 7 Conclusions 62 7.1 Summary ................................... 62 7.2 Conclusions.................................. 63 7.3 FutureWork ................................. 64 8 Personal Contributions to the Project 66 8.1 Guillermo García Patiño Lenza . . . . . . . . . . . . . . . . . . . . . . . 66 8.2 Daniela Alejandra Córdova Porta . . . . . . . . . . . . . . . . . . . . . . 69 8.3 MarioQuiñonesPérez ............................ 71 v
List of Figures 1.1 Growth of the transistor count over time . . . . . . . . . . . . . . . . . . 3 1.2 GANSketch.................................. 4 1.3 GAU GAN input and output example taken from [1] . . . . . . . . . . . 4 1.4 Dall E’s output corresponding the input ”A teapot imitating a turtle” takenfrom[4]................................. 5 2.1 LossFunctions ................................ 4 2.2 Convolutional Layer Example . . . . . . . . . . . . . . . . . . . . . . . . 5 2.3 Pooling algorithms input and output . . . . . . . . . . . . . . . . . . . . 6 2.4 The effect of a nearest neighbor upsampling over a 2 ×2 image . . . . . 6 2.5 Supervised learning step . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.6 Structure of a simple GAN . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.7 Oscillatinglossplot.............................. 13 2.8 Mode collapse GAN’s output example . . . . . . . . . . . . . . . . . . . 14 3.1 Basic components of a GAN . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.2 A graphic view of the generator’s architecture . . . . . . . . . . . . . . . 17 3.3 Scheme of the discriminator’s architecture . . . . . . . . . . . . . . . . . 18 3.4 Handwritten digits images contained in the MNIST dataset . . . . . . . 19 3.5 Handwritten images of number 8 used in this experiment . . . . . . . . . 20 3.6 Simple GAN results trained with 1 class (1) . . . . . . . . . . . . . . . . 20 3.7 Simple GAN results trained with 1 class (2) . . . . . . . . . . . . . . . . 21 3.8 Loss function over time measured in batches . . . . . . . . . . . . . . . . 22 3.9 Simple GAN results trained with 2 classes (1) . . . . . . . . . . . . . . . 22 3.10 Simple GAN results trained with 2 classes (2) . . . . . . . . . . . . . . . 23 3.11 Loss function over time measured in batches for a two class dataset . . . 23 3.12 Training results after 64 epochs of the GAN with a dataset of all the numbers 24 4.1 An image of a Conditional GAN . . . . . . . . . . . . . . . . . . . . . . . 26 4.2 Sketch of the Conditional Generator . . . . . . . . . . . . . . . . . . . . 27 4.3 Sketch of the Conditional Discriminator . . . . . . . . . . . . . . . . . . 28 4.4 Conditional GAN Results (1) . . . . . . . . . . . . . . . . . . . . . . . . 30 4.5 Conditional GAN Results (2) . . . . . . . . . . . . . . . . . . . . . . . . 31 4.6 Loss function over time (measured in batches) . . . . . . . . . . . . . . . 32 5.1 StyleGANScheme .............................. 34 5.2 StochasticNoise................................ 35 5.3 Mapping network structure . . . . . . . . . . . . . . . . . . . . . . . . . 36 5.4 Initial state of the generator in the training process . . . . . . . . . . . . 37 vi
TFG Gans 2022 UCM 5.5 StyleGAN step in progressive growing . . . . . . . . . . . . . . . . . . . . 38 5.6 StyleMixing.................................. 39 5.7 Difference between a truncated and not truncated normal distributions . 40 5.8 Softplusfunction ............................... 40 5.9 StyleGANGenerator............................. 41 5.10 StyleGAN Result with BCE Loss . . . . . . . . . . . . . . . . . . . . . . 46 5.11 StyleGAN Results with Logistic Loss . . . . . . . . . . . . . . . . . . . . 47 5.12 BCE Loss function over time (measured in batches) in depth 32x32 . . . 48 5.13 Loss function over time (measured in batches) in depth 4x4 . . . . . . . 49 5.14 Logistic Loss function over time (measured in batches) in depth 64x64 . 49 5.15 StyleGAN batch training time Graph . . . . . . . . . . . . . . . . . . . 49 5.16StyleMixing1 ................................ 50 5.17StyleMixing2 ................................ 50 6.1 Complete Structure of a CycleGAN which has been trained with images ofhorsesandzebras ............................. 53 6.2 CycleGAN Generator structure . . . . . . . . . . . . . . . . . . . . . . . 54 6.3 PatchGAN patch division . . . . . . . . . . . . . . . . . . . . . . . . . . 57 6.4 Training results at the beginning of the first epoch for apples and pears. 58 6.5 Training results at the end of the first epoch for apples and pears. . . . . 59 6.6 Training results at the end of the third epoch for apples and pears. . . . 60 6.7 Training results after 15 epochs for apples and pears. . . . . . . . . . . . 60 6.8 Training results after 20 epochs for apples and pears. . . . . . . . . . . . 60 6.9 Loss function over time (measured in batches) . . . . . . . . . . . . . . . 61 vii
List of Tables 3.1 Simple Generator block that takes an input of size (512 ×3×3) . . . . 17 3.2 SimpleGenerator............................... 17 3.3 Simple Discriminator block that takes an input of size (512 ×26 ×26) . 18 3.4 SimpleDiscriminator............................. 18 4.1 Conditional Generator Block that takes an input of size (512 ×3×3) . 26 4.2 Conditional Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 4.3 Conditional Discriminator block that takes a tensor of size (64 ×31 ×31) asinput .................................... 28 4.4 Conditional Discriminator . . . . . . . . . . . . . . . . . . . . . . . . . . 28 5.1 Mapping Network Block . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 5.2 MappingNetwork............................... 42 5.3 Adain Block (4x4 Block Example) . . . . . . . . . . . . . . . . . . . . . . 42 5.4 Synthesis Network Block (32x32 output Block Example). Input Shape: [ 512,16,16] .................................. 43 5.5 StyleGenerator................................ 43 5.6 Discriminator Block (64x64 Block Example) . . . . . . . . . . . . . . . . 44 5.7 StyleDiscriminator.............................. 44 6.1 ResidualBlock ................................ 55 6.2 CycleGANGenerator............................. 55 6.3 CycleGAN Discriminator . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 1
Chapter 1 Introduction There have been major advances in artificial intelligence, particularly machine learning, over the past decade. These breakthroughs have been made mostly because of the increase in processing capacity over time, as anticipated by Moore’s law in 1965, which projected that the number of transistors in a given surface would double every year, as illustrated in Figure 1.1. This increase in computational power has allowed the implementation of many techniques that had been considered previously, but had not been tested to their full potential due to the lack of computational power. For example, although multilayer perceptrons were proven to be able to approach any mathematical function, by the 1980s they were outclassed by support vector machines due to the inefficiency in the training process. Thanks to advancements in efficiency and computational power, multilayer perceptrons have grown into far more complicated structures like the ones presented in this work. This increase in computation power has been used in recent years to solve mostly classification and regression problems using a variety of algorithms and models, in which the model must learn either to differentiate a sample between every class available or how the features of a given sample are related to another in order to predict its value. However, the aim of this work is to solve a much more complex problem. The models to be investigated in this work must understand not only the distinctions between the classes to which a sample can belong but also the exact attributes that essentially characterize each conceivable class. For example, while differentiating a cat from a dog is relatively simple, defining the specific characteristics of a dog and a cat is a considerably more difficult process. These models learn those specific properties to generate synthetic samples that incorporate the learning of the model. There has been a lot of progress in recent years when it comes to creating videos, photos, and even music. Deepfakes are great examples of these advances: images or films of individuals that have been artificially made by transferring the facial expressions and gestures from one video to another, resulting in videos of people saying things they did not actually say. Other studies worth examining are NVIDIA’s GauGAN [32], which can transform a segmentation map into a realistic image, and OpenAI’s Dall E [37], which can generate faithful images based on a textual description provided by the user. Figures 1.3(a), 1.3(b) and 1.4 illustrate examples of what these two models can do. 2
TFG Gans 2022 UCM one to the input of another, and these connections form a “network” – the neural network – of interconnected nodes. The simplest neural network node is called a perceptron. It consists of a single node that receives many inputs, and only one output. That output is calculated firstly by calculating a linear combination between the inputs and a vector of weights that are stored in the perceptron, and secondly by feeding the output of that linear combination to an activation function. The perceptron is patterned after a neuron in a human brain, so both of them behave similarly. Nodes are activated when there are sufficient stimuli or input. This activation spreads throughout the network, creating a response to the stimuli (output). The connections between these artificial neurons act as simple synapses, enabling signals to be transmitted from one to another. Signals traverse layers as they travel from the first input to the last output layer, and get processed along the way. When posed with a request or problem to solve, the neurons run mathematical calculations to figure out if there’s enough information to pass on the information to the next neuron. Put more simply, they read all the data and figure out where the strongest relationships exist. In the simplest type of network, data inputs received are added up, and if the sum is more than a certain threshold value, the neuron “fires” and activates the neurons it’s connected to. This way, the computer learns to recognize patterns to solve the problem that it’s trying to be solved. As the number of hidden layers within a neural network increases, deep neural networks are formed. Deep learning architectures take simple neural networks to the next level. Using these layers, data scientists can build their own deep learning networks that enable machine learning, which can train a computer to accurately emulate human tasks, such as recognizing speech, identifying images, or making predictions. 2.1.2 Types of Layers Fully connected Layers Fully connected layers are the most basic layers in a neural network. They represent each of the layers of a traditional multilayer perceptron model. Each of these layers group a set of perceptrons which get their inputs and produce their outputs according to the following formula: z[l] i=∑w[l] ia[l−1] i(2.1) Activation Layers In this chapter we will introduce the activation layers that will be needed throughout this work. •Sigmoid Fuction 2
TFG Gans 2022 UCM The sigmoid function (Figure 2.1(a)) is a non linear activation function that outputs a value between 0 and 1 given for any given input. This function is often used in the output layers of models used to classify samples in two different categories. Sigmoid(t) = 1 1 + e−t(2.2) •Hyperbolic Tangent Function The hyperbolic tangent function (Figure 2.1(b)) is very similar to the sigmoid function. While the sigmoid function returns values between 0 and 1, the tangent function returns values between -1 and 1, but they both have an ’S’ shape. This function is preferred over the sigmoid function when it comes to predictive models [14]. Tanh(t) = et−e−t et+e−t(2.3) •ReLU Function The ReLU function (Figure 2.1(c)) outputs a value between 0 and ∞for any given input. Precisely, this function outputs a 0 for any negative value, and outputs what it is given as input for any positive value. This activation function has much more sensitivity than the sigmoid and tanh functions. ReLU(x) = max(0, x)(2.4) •Leaky ReLU Function The LeakyReLU (Figure 2.1(d)) function is similar to the ReLU function, but instead of outputting 0 for any negative value, this function outputs what it gets as an input scaled by a factor αwhich is usually set to 0.01. The reason to include this factor is to avoid the function having a 0 gradient for negative values so that it provides some feedback during backpropagation. LeakyReLU(x) = max(αx, x)(2.5) Convolutional Layers A convolution is an operation performed over any tensor (a multidimensional array) to produce another tensor, although, in the context of this work, convolutions are always performed over an image (a 3-dimensional tensor). The way convolutions work is by sliding a filter (also called the kernel), which is just a square tensor with any amount of channels, across the input image and multiplying the filter and a slice of the image pixelwise, and then adding the results. For each time the filter is drawn across the input image, a scalar is generated to be part of the output image. More precisely, the position in the output image of a given scalar is determined by how many times the kernel has been slid across the image in each dimension. 3
TFG Gans 2022 UCM 3210123 0.2 0.4 0.6 0.8 (a) Sigmoid function 3210123 1.00 0.75 0.50 0.25 0.00 0.25 0.50 0.75 1.00 (b) Tanh function 3210123 0.0 0.5 1.0 1.5 2.0 2.5 3.0 (c) ReLU function 3210123 0.0 0.5 1.0 1.5 2.0 2.5 3.0 (d) LeakyReLU function Figure 2.1: Loss Functions For example, if the input data are color images, then each filter would have three channels (i.e. each having shape 3 ×n×n) to match the three channels (red, green, blue) of the image Additionally, to perform a convolution, it is necessary to understand what the stride and the padding parameter are. •Strides The stride’s parameter is the step size used by the layer to move the filters across the input. Increasing the stride, therefore, reduces the size of the output tensor. For example, when the stride is set up to two, the input tensor will be halved both in height and width. •Padding The padding parameter stands for the size of the wrapping to be applied to the input data before performing the convolution itself. For example, a given image of size 3×2×2used as input for a convolutional layer set with padding one is first transformed into a 3×4×4image before calculating the convolution. The content of the wrapping can be set to anything from just ones, to a reflection of the input data or a slice of it repeated. Padding is usually used along with strides and filter size to set up the convolution to perform a certain action over the input image, such as upsampling or downsampling it. 4
TFG Gans 2022 UCM 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 0 0 0 0 1 0 0 0 0 = 1 1 1 1 1 1 1 1 1 1 1 11 111 11 1 1 1 1 1 11 4 Filter / Kernel Stride Padding x Figure 2.2: An image of a Convolutional layer with a 5 ×5 image , a kernel of 3 ×3 that its composed of zeros except the middle with a one, a padding of 1 and a stride of 3 So, to set up a convolution over a three dimensional input, it is necessary to specify several parameters: the number of channels of the input data, the number of channels desired in the output data, the kernel size, and the padding to be added to the image. Figure 2.2 shows the first two steps a convolutional layer takes when calculating a convolution over a 5 ×5 image using a filter of size 3 ×3, padding of 1, and a stride of 3. Convolutional Transpose Layers Convolutional transpose layers perform the opposite operation of convolutional layers. While convolutional layers were used to reduce the size of the input tensor, convolutional transpose layers serve the opposite purpose. The way convolutional transpose layers increase the size of the input tensor is by adding padding data to the input tensor in two ways. First, padding data is injected between the input tensor data so that each component of the input tensor is separated from the other by a distance equal to the padding parameter in each dimension. Then, the input tensor is wrapped in more padding until the center of the filter can match the first component of the original input tensor. Finally, a traditional convolution is performed. Pooling Layers These layers are used to reduce the dimensions of a tensor using convolutions. Instead of multiplying the values in the kernel pixelwise with the image, the action performed per each stride of the kernel is either taking the average of the values on the kernel (Average Pooling) or their maximum value (Max Pooling). Figure 2.3 shows how a max pooling and an average pooling layer that use a kernel of size 2 ×2 and a stride of 2 operate over a 4 ×4 images. Upsampling Layers As an opposite to pooling layers, upsampling layers are used to increase the dimensions of a tensor using a known algorithm (linear, bilinear, nearest neighbor...) instead of using 5
TFG Gans 2022 UCM 29 15 28 90 0 56 72 38 12 12 7 2 12 12 45 6 29 15 28 90 0 50 72 38 12 12 7 2 12 12 45 6 Max pooling Avg pooling 56 90 12 45 56 57 12 15 Figure 2.3: An example of a Max Pooling and an Average Pooling layers inputs and outputs. Both images use a kernel of 2 ×2 and a stride of 2. The Max pooling takes the maximum value of each stride of the kernel through the image of 4 ×4, while Avg pooling takes the average of the values from the stride convolutions. Figure 2.4 shows the input and output of an upsampling layer over an image to double its size. 5 3 4 2 5 5 5 5 3 3 3 3 4 4 4 4 2 22 2 Figure 2.4: The effect of a nearest neighbor upsampling over a 2 ×2 image Batch Normalization Layers This layer uses the mean and the variance of the inputs in a certain node to normalize them. Using this kind of layer, a single sample can produce different results depending on the batch in which the sample is contained during testing. To avoid this issue, these layers gather the running mean and the variance of the different batches during training and then use them as a fixed value during testing. 6
TFG Gans 2022 UCM ˆy[l] i=(z[l] i−µz[l] i ) √σ2 z[l] i +ϵ(2.6) y[l] i=γ∗ˆy[l] i+β(2.7) Instance Normalization Layer Instance normalization layers normalize their input the same way batch normalization layers do. The only difference between these two layers is that while batch normalization acts upon the entire batch taking into account the running mean and standard deviation, instance normalization acts over a part of the input tensor. For example, when taking images (three dimensional tensors) as an input, these layers normalize each channel of each input tensor independently without caring about the rest of the batch or the other channels of the image. 2.1.3 Cost Functions Binary Cross Entropy Binary cross entropy (BCE) cost function measures the effectiveness of a model at classifying samples between two different classes. It is designed to evaluate the cost of a binary sorter that produces a real value between 0 and 1 for each input. If that is taken into account and then being yi= 1 for samples in the first class and yi= 0 for samples in the second class, the BCE cost function forces the model to produce a value closer to 0 for ˆyiif the input is a sample from the second class, and a value closer to 1 if the input is a sample from the first class. On the other hand, if the difference between the tag (yi)and the output of the model (ˆyi)maximizes, the BCE goes to infinity. BCE =−1 m∑(yi∗log(ˆyi) + (1 −yi)∗log(1 −ˆyi)) (2.8) Although the use of this cost function may lead to some training problems, the BCE cost function is one of the most commonly used functions in GANs training. 2.1.4 Training using gradient descent In this work, the goal of the model is to produce an output for a given sample that matches the class the input sample belongs to, and that class is the information the model has at its disposal to learn. Feeding both the model’s output and the correct tag to the cost function, the model gets feedback on how accurate its output was and finally, the gradient descent algorithm 7
TFG Gans 2022 UCM indicates to the model how to update the weights in each node to perform better next time (score lower on the cost function). This process is described in a schematic way in figure 2.5 CLASS A CLASS B SAMPLE OUTPUT Cost Function Figure 2.5: Supervised learning training step, in which the samples are passed through the network in order to get a result, then this results are compared to the samples that were used for the generation and the differences from the real samples and the output of the network are used as a cost function in order to update the weights of said network Essentially, gradient descent calculates the partial derivatives of the cost function for each weight in the model and then evaluates those partial derivatives, thus obtaining a value (which is called the gradient) to update each weight. This process has been refined and implemented in several algorithms provided by libraries such as pytorch [34] or tensorflow [3] to a point where each one offers a different trade-off between efficiency and speed. The one used in the context of this work is the Adam optimizer [25] , provided by pytorch. It calculates the weights as shown in Equation 2.9 , using the gradients calculated using the weights used in the previous training step (gt) and two set coefficients β1and β2 usually set to a value close to 1. The Adam optimizer is the one that optimizes the best cost function, but also the one that takes the most time to reach the minimum value of that function. Taking the equations above into account, the Adam optimizer updates the weights for the next iteration as shown in Equation 2.9. 8
TFG Gans 2022 UCM gt=J(θt) mt=β1×mt−1+ (1 −β1)×gt vt=β2×vt−1+ (1 −β2)×g2 t mt=mt 1−βt 1 vt=vt 1−βt 2 θt+1 =θt−η √ˆvt+ϵ−ˆmt (2.9) 2.2 Generative Adversarial Networks Generative adversarial networks (GANs) [15] are machine learning models whose task is to produce artificial samples similar to the ones used to train them. Having the model do a different task rather than classifying samples into two classes means that it is necessary to change certain aspects of both the neural network and the training process. First, the model needs to become sort of an artist who is trying to produce a fake copy of, let’s say, the Mona Lisa and then tries to sell it to an art critic. Imagine that the critic does not only determine if the painting the artist delivers is a fake one, but also tells the artist what to do to paint a more faithful copy. Then, the artist would end up painting perfect copies of the Mona Lisa, and the critic would have no other option but to randomly guess if what the artist delivers is either a fake copy or the real painting. To be more specific, the GAN is made up of two submodels competing against each other, the generator, which plays the role of the artist, and the discriminator, which plays the role of the art critic. Although the artist-critic metaphor provides a clear idea of the interaction between the generator and the discriminator, there are many differences that are worth noting: • Instead of creating a painting from scratch like the artist does, the generator needs a random noise vector as an input to produce a fake sample. • Since the critic already knows what a real Mona Lisa looks like, the only one learning during the process is the artist. In contrast, at the beginning of the training of a GAN, neither the generator nor the discriminator has any kind of knowledge. During the training process, the generator has to learn using the feedback provided by the discriminator, and the discriminator has to do it by looking at real samples from a dataset. • While it is quite clear that the discriminator ends up being a binary classifier, the task the generator performs is not so clear. To clarify the generator’s task, it is necessary to think of the dataset used to train the GAN as a probability distribution that models the frequency in which certain features appear in real samples. 9
TFG Gans 2022 UCM Taking this into account, what the generator is really doing is approximating the distribution in the dataset. It is worth noticing the importance of the competition between the generator and the discriminator in the training process. On the one hand, if the discriminator never learned what a real sample looked like, the generator wouldn’t learn how to produce faithful samples. On the other hand, if the generator didn’t take advantage of the feedback provided by the discriminator, the duty of the discriminator would be too simple and there would be no point in training that model. Although the valuable part of a GAN ends up being the generator, the discriminator learning at a similar rate to the generator while being able to compete with the generator is the key to achieving a working GAN. 2.2.1 GAN architecture The structure of the GAN is as shown in Figure 2.6, and the parts that compose it are as follows: •Training dataset Dataset of real examples that we want to emulate with the Generator. It is the input to the Discriminator network. •Random noise vector Vector of random numbers used by the Generator to synthesize fake examples. It is the input to the Generator network. The changes in this vector are used in order to increase diversity on the images generated by the Generator Network. •Generator network This network takes in the random noise vector and outputs fake examples. Its goal is to generate fake examples as similar as possible to the real examples. •Discriminator network This network takes in a real example (training set) or a fake example (Generator). For each example, the discriminator determinates the probability of whether the example is real. 2.2.2 Reaching a state of equilibrium A GAN is fully trained when its reaches Nash equilibrium. The following requirements must be fulfilled: • The Generator produces fake examples that are identical or almost identical to the real example in the training dataset. • At best, the Discriminator can predict whether a particular case is real or fake at random (i.e., make a 50/50 guess). 10
TFG Gans 2022 UCM Figure 2.6: Simplified structure of a Generative Adversarial Network or GAN that uses both a generator, which takes a random noise and converts it into an image, and a discriminator which takes both the generated fake images and real images and discerns which ones are which 2.2.3 Evaluation Given the task of generating fake samples of any kind, it is difficult to think of a way to measure how a model performs at it. On top of that, if the model needs not only to produce faithful copies of the original samples but also to generate a wide variety of them, the evaluation becomes even tougher. For example, it wouldn’t be much of a success if a GAN trained to generate human faces only produced white male faces, and neither would be the desired result if the samples generated were diverse but fooled no human observer. Although the best case possible would be to have both high quality and diverse images, there is usually a trade-off between these two features, just as there is one between precision and recall when it comes to training a binary classifier. In fact, the only module of the GAN that is being tested during the evaluation is the generator, while the discriminator is left behind. As previously mentioned, the generator’s duty is to approximate the probability distribution that appears in the dataset used to train it. Taking that into account, it’s easy to realize that evaluating a GAN equals measuring the difference between the distribution in the dataset and the one learned by the generator. Inception score The inception score (IS) [8] is a way of rating GANs based on the convolutional network named Inception. The rating is calculated feeding the same input to both models (the inception network and the model to rate ), and comparing both outputs by either using cosine distance or by just taking the difference between the mean of the two outputs. 11
TFG Gans 2022 UCM Conv Layer Batch Norm ReLu Discriminator Block Discriminator % of being real Fake Image Figure 3.3: Scheme of the discriminator’s architecture 3.2.2 Discriminator The Discriminator used for this GAN is just a copy of the generator except for the last block, which is formed by a convolutional layer and a sigmoid as an activation function, whose output sizes are detailed in Table 3.3. The only difference between the two modules is that, while the generator upsamples the initial noise vector that it receives as input, the Discriminator needs to gradually decrease the input tensor to produce a number between 1 and 0 that indicates how close the image is to be real or fake. Figure 3.3 shows a graphic view of the architecture of this module. Additionally, table 3.4 provides more details on the layers used in this model. Moreover, it is worth noticing that the Discriminator uses convolutional layers instead of transposed convolutional layers since, even though both layers can be set to produce any output size, transposed convolutional layers ease the upsampling of their input when it comes to coding them, and convolutional layers do it at downsampling their input. Layer(type) Output Shape Num Params Conv2d [ 512, 12, 12 ] 131.200 BatchNorm2d [ 512, 12, 12 ] 256 ReLU [ 512, 12, 12 ] 0 Table 3.3: Simple Discriminator block that takes an input of size (512 ×26 ×26) Layer (type) Output Shape Param # Simple Discriminator Block 1 [ 64, 26, 26] 3.264 Simple Discriminator Block 2 [ 128, 12, 12] 131.456 Simple Discriminator Block 3 [ 256, 5, 5] 525.056 Conv2d [ 3, 1, 1] 12.291 Table 3.4: Simple Discriminator 18
TFG Gans 2022 UCM Figure 3.4: Handwritten digits images contained in the MNIST dataset 3.3 Training The discriminator has to discern between real and fake images, as such the loss function used in this model was BCE Loss Function 2.8 combined with a Sigmoid Layer 2.2. We use the Adam optimizer for both the Generator and Discriminator, with a learning ratio of 0.003 and a batch size of 16 during training. The hyperparameters used to train this model are : •Batch size : 16 •Learning rate : 0.003 •Loss function : BCE as explained in section 1.4 of chapter 2 •Image resolution : 55 ×55 •Adam Betas : 0.9 and 0.999 3.4 Experiments and Results 3.4.1 MNIST Dataset This dataset consists of 60000 images of numbers written by hand separated into classes from 0 to 9. Each class contains around 6000 images as shown in, and all the images are 28 by 28 pixels each. All images are black and white, making the training of the models faster, as there was no need to learn the specific coloring of the image. Figure 3.4 shows 35 random images sampled from this dataset. 3.4.2 First Experiment: One Class Dataset Once we had built a basic GAN architecture, we then tried to prove it and were able to generate faithful images in a very reduced scope. To that end, we trained the GAN on a 19
TFG Gans 2022 UCM Figure 3.5: Handwritten images of number 8 used in this experiment Figure 3.6: Training results after 1 (left), 4 (middle) and (right) epochs. The upper row shows what the GAN outputed, while the lower row displays real samples. subset of the original MNIST dataset made of only handwritten images of the number 8 like the ones shown in Figure 3.5. The following images are the result of the generator from the first epochs (1 and 8) to the later epochs (16 to 64) in which the generator has learned how to create real looking numbers. These images contain the results of the generators on the top row, while the bottom one consists of real images from the dataset. Obtaining these images took around 1 hour and a half to generate, running the experiment on an NVIDIA 1660 paired with a Ryzen 5 3600 and 16 GB of RAM available. As shown in 3.6 on the very first epoch the generator doesn’t really do a good job at creating an image of an eight. In fact, it tries all the pixels of the image until it reaches a state in which it learns the shape of the number vaguely on the fourth and continues learning until the eighth. Even though it isn’t exactly an eight, the progress is noticeable. 20
TFG Gans 2022 UCM Figure 3.7: Training results after 16 epochs (left), 32 epochs (middle) and 64 epochs (left). The upper row shows what the GAN outputed, while the lower row displays real samples. In the later stages of training, the GAN is as shown in 3.7, the number eight is more visible and the generator tries different shapes in order to match the real images from the dataset. At the begging in epoch 16, the shapes are clearly distinct, but by the 64th epoch, the shape of the numbers are much alike even though the background is still the same black color different from the gray shade of the real images. Finally, in the last images, 3.8, we can see the loss function of both the generator and the discriminator. The discriminator is separated between the real images, the fake images losses, and the loss of both combined. It is evident that the discriminator learns far too quickly and consistently beats the generator; even on later epochs, where the shapes of the images are very identical, the discriminator can detect the slightest change and make a very accurate guess. The generator’s loss, on the other hand, keeps oscillating while it learns how to create a more realistic looking eight, even ending with higher loss values than it began with, due to the discriminator learning at a much faster pace. Notice that even though the Discriminator loss details the loss for fake samples and real samples, that information is not clearly visible in Figure 3.8 as the scale needed to plot them along with the Generator loss is too large. 3.4.3 Second Experiment: Two classes Dataset Following the promising results of the GAN trained with a single class dataset, a more complicated dataset was employed in the training procedure to demonstrate the GAN’s full potential. More precisely, this dataset was made of two classes that contained both images from ones and sevens. Similar to previous figures, in the ones following the top row represents the generated fake images, while the bottom represents the real ones that the top ones are trying to imitate. 21
TFG Gans 2022 UCM Figure 3.8: Loss function over time measured in batches Figure 3.9: Training results after 1 (left) and 4 (right) epochs. The upper row shows what the GAN outputed, while the lower row displays real samples. As seen on the first image in Figure 3.9, the generator starts the same as the previous section 3.4.2 in which it tries to roughly create the shape that most resembles a one and a seven combined. By the fourth epoch, it reaches a point where the shape of the number can be seen in some way. But by the eighth epoch, as shown in Figure 3.10, it starts showing promising results. Due to the simplistic shapes of both the classes used during the training and the number of images on this one relative to the previous one (more than double) the training process takes way fewer epochs in order to harbor convincing results. In the latest epochs, the numbers have almost no difference from their original ones. Still, the generator doesn’t differentiate between one and seven. Due to the similarities between both images, the generator creates a random image that doesn’t discriminate between ones and sevens and creates one of them indiscriminately. As seen on Figure 3.11, the same as Figure 3.4.2 the discriminator loss doesn’t get too high for the same reasons as before, only in this case it has one more reason not to increase, 22
TFG Gans 2022 UCM Figure 3.10: Training results after 8 epochs (left), 15 epochs (left). Top row showing training results and bottom row showing real samples. and that is the generator incapability of creating a specific number given a class. The generator oscillates in its loss while still learning how to generate a good enough looking number, while still not knowing which class it belongs to. 0 2000 4000 6000 8000 10000 12000 0 1 2 3 4 5 6 7 8 Gen Loss: 7.979340792360885 Disc Loss: 0.032539679172953064 Gen Loss Disc Loss Disc Fake Loss Disc Real Loss Figure 3.11: Loss function over time measured in batches for a two class dataset 3.4.4 Third Experiment: More than two classes Datasets As the previous experiment shows promising results, we move on to more complex datasets with more than two classes or classes with not many similarities. It resulted in the generator not learning while trying to create a mixture of all classes of images at the same time, producing blurry and random images that don’t resemble the originals in any way, shape, or form as it is shown in Figure 3.12. Due to this problem in creating images for the more complex dataset, we need a GAN that takes into account which class the generated images has to represent, for that purpose 23
TFG Gans 2022 UCM Figure 3.12: Training results after 64 epochs of the GAN with a dataset of all the numbers we move onto a more advanced GAN on chapter 4. 3.4.5 Conclusions In this chapter, we applied the basic notions about GANs to create a simple architecture able to produce images fairly similar to the ones used during its training. First, we tested the architecture on a one class dataset, and the Simple GAN proved to be capable of achieving realistic images. Then, we expanded the scope of training this GAN with a dataset containing images from 2 similar classes and tested the Simple GAN. The results produced by this test were worse than the ones obtained through the first experiment, but still were somehow similar to the real samples. Finally, we ran one last experiment using the whole MNIST dataset. The results of this experiment proved that the Simple GAN was not powerful enough to deal with so many classes. Thanks to these experiments, we learned about the basic structure of a GAN, and well as its limits. They clearly showed that, although maybe this architecture would produce higher quality images by stacking more blocks in both the Generator and the Discriminator, this architecture’s potential is limited. Additionally, these experiments served us to get down to work with Pytorch and the tools it provides to build and train models, and also its utilities to manage datasets. 24
Chapter 4 Conditional GAN: Conditional Image Generation GANs are capable of producing examples, but by using simple GANs we can not specify any of the features of the data samples or classes the GAN would generate. The downside to the standard GANs is that if any feature is desired to be present in the generated samples, the only choice to generate a fake sample with said feature is by trial and error. This makes the model very slow to provide an example that meets the desired conditions, and also produces a lot of undesired images to get rid of. Fortunately, conditional GANs [30] tackle and solve this challenge pretty well with almost no change to the standard GAN architecture. 4.1 Definition of a Conditional GAN Conditional GANs are generative adversarial networks that contain additional information on the input to condition the Generator and Discriminator during training. This auxiliary data might theoretically be anything, such as a class classification, a set of tags, or even a written explanation. In the context of this work, this additional information will be a label indicating one of the multiple classes. The fact that the Conditional Generator’s input is extended with the label of the sample to generate, implies that both the Conditional Generator and the Conditional Discriminator need to learn a way to map the features of the samples in each class to their label. Then, the Conditional Generator learns this in order to provide control to the user over the features of the generated sample. Furthermore, the Conditional Discriminator now needs to detect images paired with the wrong label regardless of whether the image is real or fake, and fake images paired with the correct label. As a result, producing realistic-looking data via the Conditional GAN Generator is insufficient to fool the Discriminator. It’s also important that the examples it generates match their labels. After the Generator has been fully trained, the Conditional GAN can synthesize any sample from any class by feeding it the desired label. To clarify the idea 25
TFG Gans 2022 UCM that this architecture introduces, 4.1 shows a sketch of how everything is put together. Figure 4.1: An image of a Conditional GAN 4.2 Architecture 4.2.1 Generator As the dataset used is originally split into categories differentiating each fruit, it is easy to encode the label of an image using a one-hot vector. So, to sum up, being z the random noise vector the generator takes as input and being y the label of the sample desired, the generator produces G(z, y) = x∗|y(read as “x* given that, or conditioned on, y”) The purpose of this false example is to resemble a real case for the supplied label as closely as possible (in the eyes of the Discriminator). At a lower level, the Conditional GAN Generator consists of a series of blocks, each one performing a convolution, a batch normalization, and an activation function on their input. More precisely, the convolution performs an upsample on the input tensor while halving its number of channels. The layers along with the output layers are shown in Tables 4.2 and 4.1 and in Figure 4.2. The reason for this is that, doubling the size of the input tensor while halving its number of channels is a way of maintaining the amount of information of the random noise vector fed to the Conditional GAN Generator as its shape is being changed along its way through the Generator using the kernels in the convolutional layers. Layer (type) Output Shape Num Params ConvTranspose2d [256, 6, 6] 2.097.408 BatchNorm2d [256, 6, 6] 512 ReLU [256, 6, 6] 0 Table 4.1: Conditional Generator Block that takes an input of size (512 ×3×3) Finally, we use ReLu activation in all layers except for the output layer where we use the Tanh function in consequence of previous experimentation [36], where it was discovered 26
TFG Gans 2022 UCM Transp Conv Batch Norm ReLu Generator Block Conditional Generator Noise Vector Fake Image One hot tag vector Figure 4.2: Sketch of the Conditional Generator Layer (type) Output Shape Num Params ConvTranspose2d [512, 3, 3] 365.568 ConvTranspose2d [256, 6, 6] 2.097.408 BatchNorm2d [256, 6, 6] 512 ReLU [256, 6, 6] 0 ConvTranspose2d [128, 13, 13] 295.040 BatchNorm2d [128, 13, 13] 256 ReLU [128, 13, 13] 0 ConvTranspose2d [64, 27, 27] 73.792 BatchNorm2d [64, 27, 27] 128 ReLU [64, 27, 27] 0 ConvTranspose2d [3, 56, 56] 3.075 Tanh [3, 56, 56] 0 Table 4.2: Conditional Generator that, by adopting a limited activation, the model was able to learn to saturate and cover the training distribution’s color space more quickly. 4.2.2 Discriminator The Discriminator receives real examples with labels (x, y), and fake examples with the label used to generate them, (x∗|y, y). On the real example-label pairs, the Discriminator learns how to recognize real data and how to recognize matching pairs. On the Generatorproduced examples, it learns to recognize fake image-label pairs, thereby learning to tell them apart from the real ones. The Discriminator outputs a single probability indicating its conviction that the input is a real, matching pair. Its goal is to learn to reject all fake examples and all examples that fail to match their label, while accepting all real example-label pairs, Also, the Discriminator is never explicitly trained to reject mismatched pairs by being trained on real examples with mismatching labels; its ability to identify mismatched pairs is a by-product of being trained to accept only real matching pairs. 27
TFG Gans 2022 UCM as an input. The idea behind having two different inputs is that the constant vector will travel through several convolutional layers and end up as the generated image, whereas the random noise vector is processed by some fully connected layers to generate other that represents the styles that will be applied to the random noise vector at various points during the generation process. The StyleGAN Discriminator, on the other hand, is quite similar to the Conditional GAN Discriminator, but it also applied some changes for it to keep up with the Generator. A whole intuition of the complete architecture is given in Figure 5.1 Latent Space (Z)Latent Space (Z) Mapping Layers Intermediate Space Constant Input Generator Critic Fake Sample Real Sample % of Real Latent Space (Z)Latent Space (Z) Mapping Layers Intermediate Space Constant Input Generator Discriminator Fake Sample Real Sample % of Real Figure 5.1: The StyleGAN’s architecture takes a random vector and a constant vector as an input. The random vector first is ran through the mapping layers to produce another vector wthat then will be inputed to the Generator. Then, the data flows through the model as it does in previous GAN architectures. 5.1.1 StyleGAN Components These style components are significant advancements made primarily in the style generator architecture to allow style usage throughout the architecture. •Random Noise Injection The goal of this component is to perturb the present image to obtain different variations of it. This adds more noise to the model, and depending on which blocks of the network this is added, the changes will be coarser or finer. This noise is sampled from a normal distribution and concatenated to the vector resulting from a generator block’s convolutional layer preceding the other layers in the block. The extent to which this noise influences the image is determined by a learning factor λ. The changes with Stochastic Noise can be as subtle as the orientation of a wisp of hair, as seen in Figure5.2. This adds variance to the image, which can then be used for all subsequent images generated. •Mapping Network 34
TFG Gans 2022 UCM Figure 5.2: Stochastic Noise As well as the Conditional GAN generator, the StyleGAN generator also takes a random noise vector zas input. Each vector component’s value is drawn at random from a normal distribution. The noise is then sent into a neural network called a mapping network, which is constructed by stacking fully connected layers and activation functions to form an intermediate vector w. The goal of these mapping layers is to disentangle the values of the vector, that is, to transform the initial vector zinto another vector wof the same size, whose components map to the features of the generated image more precisely. This way, changing values of the vector wprovides more control over the style of the generated image than changing those in the vector z. The structure of this mapping network is shown in Figure 5.3 •Progressive Growing As shown by Karras et al.[23], this component is utilized to facilitate the production of a high definition image by gradually training the generator and discriminator from lower resolution images to higher resolution ones. It starts by, for example, using the Generator to make 4 ×4 images and the Discriminator to distinguish between them and the real ones. To make it more difficult for the Discriminator, the original photos would be downsampled to 4 ×4. When both models are sufficiently trained, the next step is to double everything, so that instead of 4 ×4 images, the generator output an 8 ×8 image and the discriminator receives 4 ×4 images to compare. This process will be repeated until the resulting image is the required size, as shown in Figure 5.4. However, during this process, neither the Generator nor the Discriminator employs either the produced or upsampled outputs, but rather both images. Because the new convolutional layer has not yet been trained, the upsampled version is largely used at first. As the training progresses, the proportion of both images used in the combination gradually increases, favoring the convolutional one until it is the sole one used. The combination is as follows: 5.1 35
TFG Gans 2022 UCM Figure 5.3: Mapping network structure image = (1 −α)∗U+C∗α(5.1) Where alpha gradually increases until it becomes 1, being U the output of the algorithm to upsample the image and C the output of the convolutional block. The procedure is then repeated with the next layers. Figure 5.5 shows how a StyleGAN would grow from using 16 ×16 images to 32 ×32 •Adaptive Instance Normalization Adaptive instance normalization (AdaIn) is the mechanism used by the StyleGAN Generator to integrate the noise vector wproduced by the mapping network with the image at several points as the image travels through the StyleGAN Generator. Essentially, it extracts two scalars αand βfrom the intermediate noise vector w and uses them to modify the image. Let us dissect this procedure. Similarly to batch normalization, as seen in equation 2.6, AdaIn normalizes each value in an instance by taking the mean and standard deviation of the values in the instance into account. An instance in this context is a set that contains every value in a certain channel of an image. The adaptive procedure begins once normalization is complete. The image is scaled and shifted by two factors, as illustrated in equation 5.2, where αis the scaling factor and βis the shifting factor. These scalars are obtained by propagating the intermediate noise vector wthrough two separate sets of fully connected layers. 36
TFG Gans 2022 UCM Figure 5.4: Initial state of the generator in the training process x′ i=α∗ˆxi+β(5.2) Along with progressive growing, adaptive instance normalization is an important component of the style-based approach. Due to progressive growing, the same style vector creates different variations on the resulting image depending on where it is used during the generation process. The earlier the style vector is inputted in the generating process, the larger the difference in the final image. This way, by using different style vectors along the training process, the StyleGAN generator allows more precise control over the generated image. •Style Mixing When training the Generator, each layer of it is given w1, the vector that the mapping network creates. However, this isn’t limited to only one vector for each layer. Another w2can be added to different layers created from different noise vectors passed through the same mapping layer. This new vector, w2, can be used in different parts of the network. For example, if w1is used in the first half of the network this would control the coarser features of the resulting image, such as shape and color, while w2would modify finer features if used in the later blocks of the architecture. This method increases diversity during training due to this mixing in styles getting more diverse outputs. As shown in Figure 5.6, depending on which layers of the network the source B (which would be our w2) is added in, the Style of the original A (w1) changes in 37
TFG Gans 2022 UCM Figure 5.5: This example demonstrates the transformation of 16X16 images (a) to 32X32 images (b) (c). During the transition (b), we treat the higher-resolution layers as if they were residual blocks, with a weight that increases linearly from 0 to 1. Both the toRGB and fromRGB layers use 1X1 convolutions to convert feature vectors to RGB colors. different ways. For coarser details, the whole shape and age of the person change, but for finer details only the color of the hair and the background change. In a nutshell, Style Mixing is a way to intertwine two images, to create a new onthatch has the styles of both, controlling the level of detail and the degree to which the changes affect the image by selecting how deep the style vector is added. Additionally, this can be extended to any number of vectors used as input at different points in the architecture to change different styles in the output image. •Noise Truncation Noise truncation is a way of trading off between diversity and fidelity by truncating the normal distribution used to generate the noise vector. This is done after training the StyleGAN using a hyperparameter and is another way of controlling the features of the output image. The difference between a truncated and a not truncated normal distributions can be seen in Figure 5.7 When training generative models, the dataset used to train the discriminator strongly influences the quality of the images generated. Due to this, features poorly represented in the dataset are not well learned by the generator, thus it may end up producing poor quality images when trying to represent those features. Noise truncation addresses this issue by truncating the normal distribution noise vectors are taken. This way, the values of the noise vector are closer to the mean of the distribution and represent features the generator is able to generate properly. •Pixel Normalization of the Feature Vector StyleGAN are prone to generator and discriminator magnitudes going out of control as a result of competition. To avoid this, the feature vector is normalized at each pixel to the unit length in the generator after each convolutional layer. •Loss Functions 38
TFG Gans 2022 UCM Figure 5.6: Style Mixing Finally, to train this architecture, a new loss function, the logistic loss, was used. This new loss function is calculated as shown in the next equation, where fp stands for the prediction of the Discriminator for fake samples, and rp is the prediction of the Discriminator for real samples. LogisticLoss(x) = E(softplus(fp) + softplus(−rp)) (5.3) The function softplus applied to the prediction emitted by the Style Discriminator acts like a ReLU function but softens the slope to make a smoother transition to where the function behaves as the identity. Figure 5.8 shows a plot of this function, which depends on two parameters: – Beta: which is used in the smoothening of the function – Threshold: which marks the point where the function starts behaving like the identity. Bearing these two parameters in mind, the function is calculated as follows: softplus(x) = 1 β×log(1 + eβx)if x ×β≤Threshold x if x ×β > T hreshold (5.4) 39
TFG Gans 2022 UCM Figure 5.7: Difference between a truncated and not truncated normal distributions 6420246 0 1 2 3 4 5 6 7 Figure 5.8: Softplus function A regularization function called R1 regularization [29] is introduced in addition to these calculations. This technique uses a penalty and gradient regularization to train generative adversarial networks. Through gradient penalty, it penalizes the discriminator for deviating from Nash Equilibrium only on real data. In a nutshell, R1 is the gradient norm, which specifies how quickly the weights will be changed. 5.2 Architecture 5.2.1 Generator The style generator uses every component previously mentioned in order to create a high definition image to which you can impose a style. Before explaining the whole Generator architecture, Figure 5.9 shows a sketch of how every component is put together. The Generator consists of 3 main elements. The block in charge of mapping the styles (Mapping Network), the block in charge of progressive growing, injecting the vector of styles that has been produced by the mapping layer and adding variability to the images, 40
TFG Gans 2022 UCM Figure 5.9: Structure of a StyleGAN Generator that has two blocks, a 4x4, which is the initial block that starts the GAN’s training and takes the vector was it’s input, and a 8x8 block which takes the output of the previous block and does the same process. This structure also shows the stochastic noise and style mixing and where they are added onto the initial structure which helps with diversity and variation to outputs. Image taken from [24]. and finally a functionality to truncate the images within stipulated limits. Table 5.5 shows a full report on the layers and blocks employed in this architecture. It begins with a learned constant. A non-linear mapping network f(Z) = Wfirst produces w given a random vector z sampled from latent space Z. An 8-layer multilayer perceptron (MLP) is used to implement the mapping f. The mapping network applying affine transformations to the vector zcan be thought of as a way to draw samples for each style from a learned distribution. The effects of each style are localized in the network, which means that changing a specific subset of the styles will affect only certain aspects of the image. The detailed report on the layers used in this mapping network is shown in Tables 5.1 and 5.2. Then, each block of the synthesis network (Table 5.4) learns affine transformations to specialize wto styles y= (ys, yb)that control adaptive instance normalization (AdaIN) (Eq.5.2) operations contained in the blocks detailed in Table 5.3. To understand why this localization is necessary, consider how the AdaIN operation first normalizes each channel to zero mean and unit variance before applying scales and biases based on the style. The new per-channel statistics, as specified by the style, change the relative importance of features for the subsequent convolution operation, but they are independent of the 41
TFG Gans 2022 UCM Layer (type) Output Shape Num Params EqualizedLinearPropia [ 512 ] 262,656 LeakyReLU [ 512 ] 0 Table 5.1: Mapping Network Block Layer (type) Output Shape Num Params Mapping Network Block-1 [ 512 ] 262,656 Mapping Network Block-2 [ 512 ] 262,656 Mapping Network Block-3 [ 512 ] 262,656 Mapping Network Block-4 [ 512 ] 262,656 Mapping Network Block-5 [ 512 ] 262,656 Mapping Network Block-6 [ 512 ] 262,656 Mapping Network Block-7 [ 512 ] 262,656 Mapping Network Block-8 [ 512 ] 262,656 Table 5.2: Mapping Network original statistics due to normalization. As a result, each style can only control one convolution before being overwritten by the next AdaIN operation. Layer (type) Output Shape Num Params NoiseLayer [ 512, 4, 4] 512 ReLU [ 512, 4, 4] 0 InstanceNorm2d (Adain) [ 512, 4, 4] 0 EqualizedLinear [ 1024 ] 525,312 Table 5.3: Adain Block (4x4 Block Example) To improve the localization of the styles in the generated images, mixing regularization [24] is implemented in the StyleGAN Generator. Mixing regularization consists of applying style mixing during the training process by first running two different inputs, z1 and z2through the mapping network to generate two intermediate latent vectors w1and w2. Then, at a set point during the training process, the latent vector used in the AdaIN blocks is switched from w1to w2. This regularization technique prevents the network from making the assumption that adjacent styles are correlated. Finally, by introducing explicit noise inputs, the generator is given a direct way to generate stochastic detail. It is fed a single-channel dedicated noise image to each layer of the synthesis network. By using learned per-feature scaling factors, the noise image is broadcasted to all feature maps and then added to the output of the corresponding convolution. The reason why the stochastic variations are not introduced the traditional way in this architecture is because it is difficult and not always successful to hide the periodicity of general signals. This architecture avoids these issues entirely by including per-pixel noise after each convolution. The noise only has to affect stochastic aspects of the system, leaving the overall composition and high-level aspects such as identity unaffected. To sum up, each block ends up performing the following: • A transposed convolution and a Upsampling layer to upsample the input image 42
TFG Gans 2022 UCM using learned weights. • Then, performs the random noise injection to produce stochastic variation on the image. • Runs the result through an LeakyReLU • Takes the latent vector w, calculates the style shift and the style scale coefficients using the AdaIn multilayer perceptrons, normalizes the input and finally applies the calculated coefficients to the results. To enhance the performance of the generators, the previous sequence can be altered to perform the upsampling, the noise injection and the adaptive instance normalization twice in each block. This way, each block learns even more with each training step. Layer (type) Output Shape Num Params Upscale2d [ 512, 32, 32] 0 Conv2d [ 512, 32, 32] 0 Adain Block [ 512, 32, 32] 0 Conv2dPropia [ 512, 32, 32] 2,359,808 Adain Block [ 512, 32, 32] 0 Table 5.4: Synthesis Network Block (32x32 output Block Example). Input Shape: [ 512, 16, 16] Component Output Shape Num Params PixelNormLayer-1 [ 512 ] 0 Mapping Network-2 [ 10, 512 ] 0 Truncation-3 [ 10, 512 ] 0 ConstantLayer-4 (4x4) [ 10, 512 ] 0 Adain Block-5 (4x4) [ 512, 4, 4 ] 525,824 Conv2dPropia-6 (4x4) [ 512, 4, 4 ] 2,359,808 Adain Block-7 (4x4) [ 512, 4, 4 ] 525,824 Synthesis Network Block (8x8) [ 512, 8, 8 ] 5,771,264 Synthesis Network Block (16x16) [ 512, 16, 16 ] 5,771,264 Synthesis Network Block (32x32) [ 512,16, 16] 5,771,264 Conv2dPropia (64x64) [ 3, 64, 64 ] 13,827 Synthesis Network Block (64x64) [ 256, 64, 64] 2,295,808 Conv2dPropia (64x64) [ 3, 64, 64 ] 6,915 Table 5.5: Style Generator 5.2.2 Discriminator As previously stated, the StyleGAN’s Discriminator is extremely similar to the Conditional GAN’s one. This neural network is built with convolution and average pooling layers to decrease the size of the input image in half, a batch normalization layer, and 43
TFG Gans 2022 UCM Figure 5.16: The StyleGAN developed three rows of images that combined various attributes of various fruits to create a variety of styles. The first row merges the tomato’s style and attempts to shift the viewpoint or position of the tomato so that it is similar to the style of the other fruits; however, because all the fruits have similar perspectives, the tomato does not change. The second row changes the shape of the tomato by merging it with the shapes of the other fruits, resulting in tomatoes of varied shapes. Finally, the lastrow aims to change the color style of the tomato by creating tomatoes with the skin of other fruits. Figure 5.17: The StyleGAN in this case utilizes a white grape as an example of a picture to be mixed. As in the preceding scenario, the most noticeable cases occur when a combination of styles is used to alter the form and skin of the grape. 50
Chapter 6 CycleGAN : Style Semantic Transfer Following the explanation of architectures that learnt how to define styles and classes, the next step would be to develop a model that learned how to transfer features or styles between images. The goal is to create a texture from a source image in its entirety while constraining the texture synthesis to preserve the semantic content (such as an object) of a target image. It is a texture transfer algorithm that constrains a texture synthesis method by using feature representation from a convolutional neural network. Translating images from one to another is about discovering the mapping between an input image and an output image based on a set of training images. For example, if the model were to generate an apple with pear skin or vice-versa, the model must be able to define the common characteristics between two photos (apple and pear) and transfer the necessary attribute to the other image. To make this possible, a neuronal network architecture should be capable of retaining most of the attributes of an image that allows it to be recognized as part of a specific class while also being capable of changing some characteristics. That is, an architecture that recognizes an image as an apple but can transform it into a pear’s skin. Notice how what we aim to do in this chapter is different from what was achieved in the last one. The StyleGAN built an image from scratch bearing a vector that somehow described the style to be applied to the final image. The model provided in this chapter, on the other hand, attempts to learn what content is shared between two images and to swap the style of the common content. 6.1 Definition of a CycleGAN A CycleGAN [42] is essentially two modules facing each other, where each one learns a mapping function from one class to another. If the CycleGAN is set to transform images from class A to class B and vice-versa, it receives a sample from class A, and first runs that input through the first module which produces a fake sample of class B. Then, that fake sample goes through the second module, producing a new fake sample of class A. Each module in the CycleGAN is in the end a GAN, so it contains a Generator 51
TFG Gans 2022 UCM and a Discriminator, making up to 2 Generators and 2 Discriminators contained in one CycleGAN. The CycleGAN learns by comparing the final sample of class A to the original one because, in the end, if the final sample resembles the original one, that means that both the transformation from class A to class B and the one from class B to class A have worked correctly. Furthermore, assuming the CycleGAN has been appropriately trained, the two components can be separated to produce two independent models capable of transferring features from one class to a sample of another class. By using unsupervised learning, CycleGAN can learn a mapping function from one image domain to another. This implies that the dataset doesn’t need to contain samples of a class transformed into the other. Instead of learning the features of some transformed samples, CycleGAN learns to perform this transformation by telling Generator Networks to learn a mapping from domain X to what seems to be a picture from domain Y and vice-versa. So, the mapping functions between two domains X and Y learned by the model would be. G:X→Y F:Y→X(6.1) Given training samples x ϵX and y ϵY and data distributions denoted by x data(x)and y data(y), the architecture consists of two adversarial discriminators DXand DY, where DXaims to distinguish between images x and translated images F(y); in the same way, DYaims to discriminate between y and G(x). In addition, two new loss functions are introduced. The first one, adversarial loss, is used to match the distribution of generated images to the distribution of data in the target domain, while the second one, cycle consistency losses, keeps the learned mappings G and F from contradicting one another. Both mapping functions are subjected to adversarial losses. In Figure 6.1 it can be seen the complete structure of a CycleGAN that transforms horses into zebras and vice versa. The first generator transforms a horse into a zebra, and then this generated image is passed on to the other generator to make a horse. 6.2 Architecture 6.2.1 Generator The generators in each GAN of the CycleGAN are a modified U-Net [38], which is an architecture that specializes in processing images to generate segmentation maps built by joining two separate modules. Within the U-Net architecture, one is an encoder in which each block is built by stacking a convolution, a batch normalization layer, and a leaky ReLU function. Then this encoder is followed by a series of nine blocks which 52
TFG Gans 2022 UCM Figure 6.1: Complete Structure of a CycleGAN which has been trained with images of horses and zebras perform two convolutions and an Instance Normalization layer while having the output size unchanged as shown in 6.1. Then the Decoder downsamples the image by creating the same organization as the Encoder, only backward to ensure the output image is the same size as the real images from the dataset. Table 6.2 provides more detail about the layers used and their output sizes. The entire structure can be seen on Figure 6.2 6.2.2 Discriminator The discriminator used is called PatchGAN [20]. This discriminator outputs a matrix of values, each of which corresponds to a ”patch” or region, that are sections of the image, as seen in Figure 6.3. This value ranges between 0 and 1, with 0 representing a fake part of the image and 1 representing a real one. All of these terms are combined into a value matrix, with each number representing a patch. On this discriminator, the label for fake isn’t 0, but a matrix filled with zeroes. Both Discriminators have a much simpler structure. Each has a series of four blocks that contain a convolution to upsample the input image and an Instance Normalization layer, as shown in Table 6.3. Following that, a convolutional is used to transform the vector image into a 1 ×1 vector, which is then utilized as the discriminator’s prediction on how much of this image is real or fake. 53
TFG Gans 2022 UCM Figure 6.2: CycleGAN Generator structure 6.2.3 CycleGAN Loss Functions Cycle Consistency Loss For each of the parts that conform to the CycleGAN, it is added a loss term that calculates the pixel differences between the real image that is used as the input, to the generated image that has passed through a cycle of the generators. On the first Generator G:X→ Ythe loss function goes: ∑(x−F(G(x))) (6.2) Where the difference is between the real image (x) and the image that the generator G creates (G(x)) which is then passed through F(F(G(x))). On the other hand, the second generator F:Y→Xloss function goes: ∑(y−G(F(y))) (6.3) Which calculate the same function but for the other types of images y. Both terms are added to the loss function which is shared between both generators multiplied by a factor λas follows: 54
TFG Gans 2022 UCM Layer (type) Output Shape Param # Conv2d-4 [-1, 128, 50, 50] 18,496 InstanceNorm2d-5 [-1, 128, 50, 50] 0 ReLU-6 [-1, 128, 50, 50] 0 Conv2d-7 [-1, 128, 50, 50] 73,856 InstanceNorm2d-8 [-1, 128, 50, 50] 0 ResidualBlock-15 [-1, 128, 50, 50] 0 Table 6.1: Residual Block Layer (type) Output Shape Param # Conv2d-1 [-1, 32, 200, 200] 4,736 FeatureMapBlock-2-2 [-1, 32, 200, 200] 0 Conv2d-3 [-1, 64, 100, 100] 4,736 InstanceNorm2d-4 [-1, 64, 100, 100] 0 ReLU-3 [-1, 64, 100, 100] 0 ContractingBlock-3 [-1, 64, 100, 100] 0 Conv2d-3 [-1, 128, 50, 50] 4,736 InstanceNorm2d-4 [-1, 128, 50, 50] 0 ReLU-3 [-1, 128, 50, 50] 0 ContractingBlock-3 [-1, 128, 50, 50] 0 Residual Block 1 to 9 (6.1) [-1, 128, 50, 50] 0 ConvTranspose2d-64 [-1, 64, 186, 186] 73,792 InstanceNorm2d-65 [-1, 64, 186, 186] 0 LeakyReLU-66 [-1, 64, 186, 186] 0 ConvTranspose2d-67 [-1, 32, 180, 180] 18,464 InstanceNorm2d-68 [-1, 32, 180, 180] 0 LeakyReLU-69 [-1, 32, 180, 180] 0 Conv2d-70 [-1, 3, 200, 200] 4,707 InstanceNorm2d-71 [-1, 3, 200, 200] 0 LeakyReLU-72 [-1, 3, 200, 200] 0 Table 6.2: CycleGAN Generator ιcyc =λ×(∑(x−F(G(x))) + ∑(y−G(F(y)))) (6.4) Adversarial Loss The adversarial loss function used is the least squares loss function, which is commonly used in CycleGAN. This loss function is used to help with training stability, and more specifically with the vanishing gradient problem. This function uses a method that minimizes the sum of square residuals between the prediction D(x) and the label (1 for real images and 0 for fakes). •Discriminator On the discriminator, the functions go as follows: 55
TFG Gans 2022 UCM Layer (type) Output Shape Param # Conv2d-1 [ 64, 197, 197 ] 3,136 LeakyReLU-2 [ 64, 197, 197 ] 0 Conv2d-3 [ 128, 194, 194 ] 131,200 InstanceNorm2d-4 [ 128, 194, 194 ] 0 LeakyReLU-5 [ 128, 194, 194 ] 0 Conv2d-6 [ 256, 191, 191 ] 524,544 InstanceNorm2d-7 [ 256, 191, 191 ] 0 LeakyReLU-8 [ 256, 191, 191 ] 0 Conv2d-9 [ 512, 188, 188 ] 2,097,664 InstanceNorm2d-10 [ 512, 188, 188 ] 0 LeakyReLU-11 [ 512, 188, 188 ] 0 Conv2d-12 [ 1, 188, 188 ] 513 Table 6.3: CycleGAN Discriminator Ex[[(D(x)−1)2]] + Ez[[(D(G(z)) −0)2]] (6.5) Where Exare the real images, whose predictions from the discriminator are compared to the real ground truth 1, and Ezare the generated images that are passed to the discriminator to achieve the difference between the prediction of the discriminator and its fake ground truth 0. This equation can be simplified into: Ex[[(D(x)−1)2]] + Ez[[(D(G(z)))2]] (6.6) •Generator On the generator’s side, the functions go as follows: Ez[[(D(G(z)) −1)2]] (6.7) As the generator’s role is to create an image as realistic as possible, the loss function reflects the distance between those images and the real ground truth 1. Both terms are unified into an adversarial loss term by adding them up, so the term ends up like this: ιadv =Ez[[(D(G(z)) −1)2]] + Ex[[(D(x)−1)2]] + Ez[[(D(G(z)))2]] (6.8) Identity Loss This is an optional loss term that is introduced to the loss function to aid with color preservation in outputs. When putting an image ythat goes through the mapping G: X→Ythe result should be the same input y. This loss term calculates the pixel difference between yand G(y)which should be the same images. 56
TFG Gans 2022 UCM Figure 6.3: PatchGAN patch division ιid =∑[[x−F(x)]] + ∑[[y−G(y)]] (6.9) Full Loss Function Taking every loss term previously explained, the CycleGAN loss function ends up as follows: Loss =ιadv +λ1×ιcyc +λ2×ιid (6.10) 6.3 Training Details Because this sort of GAN only requires two classes to learn, only two of the classes from the dataset specified in 4.4.1 were used for training the CycleGAN. The two fruits that were originally chosen were the apple and the pear. More precisely, the classes Apple Red 1 and Pear from the original dataset. Which results in a dataset consisting of 984 images. The hyperparameters used to train this model are : 57
TFG Gans 2022 UCM •Batch size : 1 •Learning rate : 0.002 •Loss function : The mix of Cycle Consistency Loss, Least Squares Loss and Identity Loss presented in Equation 6.10 •Adam Betas : 0.9 and 0.999 •Image resolution : 200 ×200 6.4 Experiments and Results Once the CycleGAN was fully implemented, the model was trained using only the pears and the apples, leaving the rest of the fruits unused. The objective was to test which features the CycleGAN was able to transfer between the two fruits and the quality of the images it produced. The following figures show the generator’s output at the start and end of the first epoch, and the remainder are the outputs after each epoch, which are epochs 3, 15, and 20. The lower row displays the generated image’s output, while the upper row displays the real sample of the class used by the generator to generate each matching result. Figure 6.4: Training results at the beginning of the first epoch for apples and pears. At the start of training, as shown in Figures 6.4 and 6.5, it is clear that the GAN only tried to change its colour while maintaining its shape to create the image, but by the fourth epoch the colour was completely mimicked, and the finer details were the only ones left (As demonstrated in Figure 6.6). By epoch 15 , as shown on Figure 6.7, it is clear that the color and skin have been replicated, resulting in an excellent result. Finally, at epoch 20 , in Figure 6.8, the fruit has changed color to the other type but has begun to try to change the shape, indicating 58
TFG Gans 2022 UCM Figure 6.5: Training results at the end of the first epoch for apples and pears. that the GAN is attempting to learn to transfer the shape, which is not what we want. As a result, we must halt the training. Due to the small size of the Dataset for training and the similarities in shape and form of the two types of fruit, the training took less than 20 epochs to reach a point where the learning rate was insufficient to justify the continuation, as seen in Figure 6.9, and thus the training was assumed to be completed. The results show that even the finer details like the shine and the rind texture were changed in order to mimic the other fruit. 6.5 Conclusions During this chapter, we’ve shown how to combine Patch GANs with U-Nets to create the CycleGAN, a model capable of transferring features from one domain to another by learning two mapping functions. This architecture attempts to solve a slightly different generative challenge in which the image must remain unmodified after being converted into another and then restored to the original image to complete the cycle. As a result, the loss function had to be modified to include a term that measured the difference between the input and output images, in addition to the one that considered the image’s realism. This experiment served us to peek into a different kind of generative problem and learn how to approach it using GANs. It provided us with a broad enough perspective to continue learning about more difficult challenges connected to this one, such as creating and applying segmentation maps in computer vision tasks. 59
Chapter 8 Personal Contributions to the Project 8.1 Guillermo García Patiño Lenza As part of the team, I watched the online lessons of the Coursera GANs specialization and took notes, so we were able to consult them and acquire the necessary knowledge to implement the models correctly. Additionally, during the first months, I also read and took notes on some papers published related to generative models and read books in order to get some ideas on what could be achieved using GANs. Afterward, when we began implementing the models, I contributed to the first implementation of the Simple GAN using the Google Collab python notebooks by calculating and adjusting the input and output sizes and by making them more accessible through a function that returned them. Moving forwards, while implementing the Conditional GAN, I wrote the code that allowed to attach the tags to their corresponding samples. Additionally, during that time, I coded the original Conditional Generator and fixed an issue where the Conditional Discriminator wasn’t outputting a single value per sample by fixing the kernel sizes and padding values of the convolutions in the Conditional Discriminator. When we were to implement the Style GAN, as working in Collab Notebooks was becoming a bit of a mess, I updated our GitHub repository with the Style GAN code we had developed to that moment written and structured in regular .py files. This code contained classes that implemented both the Style Generator and the Style Discriminator, as well as utilities to plot the loss functions during the training process and to save the generated images in a selected folder. Then, I began implementing a Style Discriminator from scratch. The first functional version of this Discriminator wasn’t able to distinguish correctly a fake sample from a real one, so, advised by the director of this work, I began to tear apart each component from the Discriminator and testing simpler versions of it to detect the components that were causing the malfunction of this module. 66
TFG Gans 2022 UCM First, I implemented a simple convolutional discriminator that was capable of telling apart samples from two different classes. Then, I tried to use progressive growing in that discriminator. This way, I managed to obtain a Discriminator who learned to differentiate between two classes much faster than the original one but still worked poorly with our Generators. After some more testing and re-reading of the bibliography, I discovered the main reason was that the progressive growing hadn’t been implemented correctly. Apparently, in a progressive growing discriminator, the input must be previously downsampled using an algorithm and then ran through only the necessary blocks instead of processed all the way through the architecture with every αset to 0 except for the last one. Another fix that was implemented along this testing process was the use of fromRGB and toRGB blocks, whose function was to turn the image into a tensor with more channels to increase the information the Discriminator works with and to transform a tensor produced by the Discriminator into an image that could be merged with the downsampled one using equation 5.1. Once the implementation of the Style Discriminator was completed, the GitHub repository contained a lot of duplicated code, since I had to implement a single function to train only the discriminator that contained the same code as the function to train the whole GAN. To solve this, I turned the training functions into class objects. This way, each GAN architecture would have its own trainer class that offered methods to either train each module separately or the whole GAN. In addition, I implemented utilities to save the plots of the loss function and the generated samples of the models. Additionally, as training was taking more and more time for each try we made, I also implemented utility methods to save the state of the GAN periodically and load it to resume the training at any point. Also, to speed up the training process, I wrote a Python script that preprocessed a given dataset turning each image into tensors, applying some initial transformations, and saving them all together into a .pt file. Finally, I also created some classes similar to the ones provided by pytorch that allowed us to create subsets of a given dataset. Next, Daniela and I tried to implement and test the Style Generator. However, this time the testing process was far easier since Daniela had previously studied the Style GAN paper and achieved a useful pytorch implementation for the Style Generator. This way, I just wrapped her implementation into a class that featured the methods required to work with the trainer class I previously developed. To finish the Style GAN implementation, I coded and tested how different cost functions worked with our architecture to find out that, in the end, the logistic loss explained in 5.3 was the one that made the model work the best, while the BCE 2.8 made the model produce almost random images and promoted mode collapse during training. When it was time to write this document, I collaborated by writing, correcting, and generating images for most of the chapters. In chapter 1 I wrote the introduction and the subsections for the objectives and the road map. 67
TFG Gans 2022 UCM Then, in chapter 2 I elaborated the subsections explaining the types of layers in a neural network, the BCE, the gradient descent and the Adam algorithm, and the different ways of evaluating how well a GAN performs, the GAN challenges and the frameworks and libraries used in the project. Additionally, I also created most of the images in that chapter either by using matplotlib or inkscape (a free open source vector graphics editor). Afterward, in chapter 3, I redacted the motivation section, the explanation of the Simple GAN architecture, and generated the sketches for the architectures of both the Conditional Generator and the Conditional Discriminator. Moreover, in the next chapter, I collaborated in the writing of subsections for the motivation, the explanation of the architecture, the training details, and the results. Next, in chapter 5 I collaborated on the redaction of the motivation section, the explanation of the Style GAN Generator, the Style Discriminator, its components, and the new loss function. Additionally, in the chapter that explains the Cycle GAN, I helped correct and reviewing the motivation subsection, the explanation for the Cycle GAN architecture, and its loss functions. Also, I wrote the final chapter that contains both the conclusions and the lines of work we suggest continuing our work in the future. Finally, we first delivered a draft of this document to the director of this work, and he provided us with lots of changes to the structure of the chapters and to some explanations, so a reader would understand better what we tried to present. I took charge of changing the structure of every chapter following those directions, and also of reading again the whole document to check if the new structure made sense. 68
TFG Gans 2022 UCM 8.2 Daniela Alejandra Córdova Porta I began my research for the TFG by taking the GANs course on Coursera, as did the rest of my colleagues, and in combination with this, I completed minor practical activities relating to the supplied topic and read papers connected to the architectures seen in the course. In addition, I thoroughly researched the theory utilizing books devoted to the subject. After finishing the course and discovering that we could start building GANs, I started working on the first Conditional GAN in Google Collab. I started by creating the necessary classes, layering them according to the theory, and then implementing the code to import the Kaggle dataset into the Google Collab notebook. I began customizing it and adding features and inputs to ensure that it produced respectable results, i.e. more or less recognized fruits. We spent hours analyzing the results and searching for papers to see what they suggested for refining the architecture because we learned it for black and white photos and wewere using a fruit dataset. In other words, we wanted the GAN to be able to generate color visuals that looked like a specific fruit. I began customizing it and adding features and inputs to ensure that it produced acceptable results, that is, identifiable fruits. This meant adding new layers and changing how the GAN handled stride and padding on different layers. We proceed with the implementation of a more complex GAN after receiving encouraging replies from the professor. In my case, I was responsible for the construction of the CycleGAN 6. I started researching articles and getting the training I needed to create this GAN by reading books and evaluating how some new layers are built in Pytorch or how they differ from the ones used in the ConditionalGAN 4. I tweaked it for several weeks to reach the intended outcomes because it required continual study and reading of related papers because we couldn’t get the styles across appropriately. We were able to achieve good results after discovering that the problem was not with the architecture, but with the images that we were utilizing, which were too small for the architecture, resulting in poor learning. This first GAN was implemented in Google Collab for the first time, and then we moved it to a Jupyter notebook to train the GAN for a longer period of time. We ended up converting the code to Python files for better understanding and to be able to discover what issues were occurring and how the images were being changed. I trained this GAN and subsequent GANs using the Pycharm development environment. Then I assisted my colleagues in the construction of the StyleGAN 5, and since several weeks had gone by with no satisfactory results, I made it my responsibility to read the StyleGAN [24] and ProGAN [23] articles step by step and observe how they were implemented in TensorFlow. We discovered that many layers and changes were not being used in our Pytorch implementation. To avoid dragging difficulties, I designed an architecture from scratch and began comparing it to what my colleagues had built. I constructed the architectures: mapping network, synthesis network, and layers that were missing. The new layers I had to construct were specifically relevant to the notion of Equalized Learning Rate and Pixel Normalization of the Feature Vector. This was explained in the original ProGAN article but not in the 69
TFG Gans 2022 UCM Style article, therefore we overlooked it when constructing the GAN. After we found that they produced some but not particularly good results, I began to experiment with different loss functions to see what was going on. I determined that the Logistic was the optimal loss function for our dataset because the Generator was unable to understand the various elements that comprise a fruit’s style and was overlearning when it reached dimensions bigger than 16x16. Training this GAN was one of the most difficult aspects of the project, as the model needed to be trained for several days in order to produce respectable results. In many cases, after hours of training, some layer or outcome produced a mistake, forcing us to restart. There were also issues with early results in some of the models, which were whitish, but with regular study of how a dataset is loaded and how the dataset modification influences the images, I was able to acquire better results. As a consequence, the fruits produced by CycleGAN and StyleGAN are non-whitish and vibrant. In terms of the TFG report, I contributed to all chapters, both theoretically and in the presentation of the GAN architecture or outcomes. I contributed to the State of the Art Chapter 2 by writing portions, completing others started by colleagues, and modifying their wording for greater understanding. Then I wrote a portion of the architecture and theory of the ConditionalGAN 4, StyleGAN 5, and CycleGAN 6, as well as their outcomes. I created the tables with my colleagues and spent some time arranging them for better understanding and connecting them with the graphics in the respective chapters. I designed some of the visual features shown in prior chapters and provided certain conceptual parts that were required in others. In brief, I helped build all of the chapters by adding information, amending portions, and fixing typos. For the project’s completion, my colleagues and I fixed the code and cleaned up the files on Github. 70
TFG Gans 2022 UCM 8.3 Mario Quiñones Pérez As a member of the team, like my teammates, I watched the online lessons from Coursera GAN’s specialization [39] and completed the exercises that were given. During the first month, all of us read books and papers and investigated the topic and everything that was needed in order to understand GANs and what results could we expect from our work. I also read about other models such as Variation Encoders [26] in order to further understand what was special about GANs and why they are more famous in the image generation field. The first models were created using Google Collab, where we programmed in python [2] the first model that is explained during this work, the Simple GAN 3 . I was responsible for passing this model to its .py format much further into the project when we decided to change it into a GitHub repository. This process was easy as another colleague, Guillermo, made a class for training models which could be partially used. To this end I only needed to add a script that could process a dataset into a .pt file where all the images would be one channel vectors, which would mean a black and white image. This was used in order for the Simple GAN to train faster with much less information to process, as they were one channel vectors instead of three channel ones. The first Style generator 5 was created by all of us, but I was in charge of trying to fix its problems. As it wasn’t performing nearly as well as we imagined and still being at is the initial stage where it wasn’t yielding any results. I tried changing its structure multiple times , as well as only training the generator and not the discriminator in order to ascertain if said generator was truly learning, but to no avail. During this process, as it wasn’t yielding any promising results, it was decided that it needed to be rearranged from scratch, and Daniela mostly created this new model. To help with training, and in order to pass it to the GitHub repository, the Simple and Cycle GANs were passed to .py and its training classes were created in order to make use of them. During the training of both models, certain aspects of them were changed in order to achieve better results, like the image size of both of them, as larger images would tend to throw an exception of out of memory, as well as the batch size and kernel size to improve efficiency while still obtaining good results. Given how the Simple GAN model could process results that achieved what we expected on a one-class dataset, I set on testing the limits of said model, reaching the conclusion that even a two-class dataset was too complex for the said model, as shown in chapter 3 on the results section. I helped fix bugs in the conditional GAN as its generator wasn’t taking the labels of the dataset correctly, concatenating the image vector with the label in a way that the shapes of the resulting vector didn’t match what the model was expecting. I also added the possibility to log the time for each epoch and the step it took to train the models in order to further understand the time needed for the models to produce good enough results and to graph the StyleGAN curve of learning and time spent on training on each step of progressive growing. My colleagues and I all contributed to the code’s repository by restructuring it and making 71
TFG Gans 2022 UCM sure it all worked after the changes. In particular, I moved both the Simple and Cycle GANs to their respective folders and added all the README files to the project. During the realization of this document, all of us participated by writing and correcting the document. My work in particular specialized in completing chapters by adding training details and results and other minor changes that were requested by the professor, and fixing internal references and cites. Also, I contributed by rephrasing paragraphs whose initial wording wasn’t on par with the rest of the document. In the first chapter 1, I contributed by writing the first iteration of the memory structure before some changes were needed in this document, needing to also change its structure. I helped with the introduction, and made the code structure subsections. In the following chapter, chapter 2, I contributed by adding images and fixing problems that were pointed out by our tutor. Also contributing by adding to both, GAN Architecture as well as challenges, and the Convolutional layers subsections. In chapter 3, I added the training details and results of said training, by giving examples of all the subsections of the dataset that was used and how well this GAN performed on them. Also, I added the tables which will be later divided in two by my colleagues. All the dataset used during this project were described by me, and all the parts that were deemed important. on Chapter 5, I contributed to describing why a Style GAN is called so, stating where the Style came from, by adding to its components both style mixing and Random Noise injection. Also, I contributed to other parts, like the explanation of progressive growing or the mapping network. I also helped with the definition of the Generator and discriminator of the Style and how they are connected, as well as adding the tables of the generator structure. On Chapter 6, I added all the loss functions that are introduced with the Cycle GAN and how they are all used in order to improve the learning of said model. I explained both the Generator and Discriminator and added the details and results of its training. 72
Bibliography [1] Gaugan test website. http://gaugan.org/gaugan2/. Accessed: 2022-21-05. [2] Python official documentation. https://docs.python.org/3.10/. Accessed: 2022- 23-05. [3] Martín Abadi, Paul Barham, Jianmin Chen, Zhifeng Chen, Andy Davis, Jeffrey Dean, Matthieu Devin, Sanjay Ghemawat, Geoffrey Irving, Michael Isard, et al. Tensorflow: A system for large-scale machine learning. In 12th USENIX Symposium on Operating Systems Design and Implementation (OSDI 16), pages 265–283, 2016. [4] Open AI. Dalle test website. https://openai.com/blog/dall-e/. Accessed: 2022- 21-05. [5] David Bau, Jun-Yan Zhu, Hendrik Strobelt, Bolei Zhou, Joshua B. Tenenbaum, William T. Freeman, and Antonio Torralba. GAN dissection: Visualizing and understanding generative adversarial networks. CoRR, abs/1811.10597, 2018. [6] Yoann Boget. Adversarial regression. generative adversarial networks for non-linear regression: Theory and assessment, 2019. [7] Peter J. Braspenning, Frank Thuijsman, and A. J. M. M. Weijters, editors. Artificial Neural Networks: An Introduction to ANN Theory and Practice, volume 931 of Lecture Notes in Computer Science. Springer, 1995. [8] Min Jin Chong and David A. Forsyth. Effectively unbiased FID and inception score and where to find them. CoRR, abs/1911.07023, 2019. [9] Jeff Donahue, Philipp Krähenbühl, and Trevor Darrell. Adversarial feature learning. CoRR, abs/1605.09782, 2016. [10] Vincent Dumoulin, Ethan Perez, Nathan Schucher, Florian Strub, Harm de Vries, Aaron Courville, and Yoshua Bengio. Feature-wise transformations. Distill, 2018. [11] David Foster. Generative deep learning. O’Reilly Media, Sebastopol, CA, July 2019. [12] Hongchang Gao, Jian Pei, and Heng Huang. Progan: Network embedding via proximity generative adversarial network. In Proceedings of the 25th ACM SIGKDD International Conference on Knowledge Discovery amp; Data Mining, KDD ’19, page 1308–1316, New York, NY, USA, 2019. Association for Computing Machinery. 73
TFG Gans 2022 UCM [13] Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge. Image style transfer using convolutional neural networks. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), June 2016. [14] Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Deep Learning. MIT Press, 2016. http://www.deeplearningbook.org. [15] Ian J. Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron C. Courville, and Yoshua Bengio. Generative adversarial networks. Commun. ACM, 63(11):139–144, 2020. [16] Google. Logistic regression: Loss and regularization |machine learning crash course |google developers. https://developers.google.com/machine-learning/ crash-course/logistic-regression/model-training?hl=es_419. Accessed 2022-16-05. [17] J. Hany and G. Walters. Hands-On Generative Adversarial Networks with Pytorch 1. X: Implement Next-Generation Neural Networks to Build Powerful GAN Models Using Python. Packt Publishing, 2019. [18] John Hany and Greg Walters. Hands-On Generative Adversarial Networks with PyTorch 1.x. Packt Publishing, Birmingham, England, December 2019. [19] J. D. Hunter. Matplotlib: A 2d graphics environment. Computing in Science & Engineering, 9(3):90–95, 2007. [20] Phillip Isola, Jun-Yan Zhu, Tinghui Zhou, and Alexei A. Efros. Image-to-image translation with conditional adversarial networks. CoRR, abs/1611.07004, 2016. [21] Phillip Isola, Jun-Yan Zhu, Tinghui Zhou, and Alexei A. Efros. Image-to-image translation with conditional adversarial networks, 2016. [22] Yoshifumi Ito, Wataru Shimoda, and Keiji Yanai. Food image generation using a large amount of food images with conditional GAN: ramengan and recipegan. In Ichiro Ide and Yoko Yamakata, editors, Proceedings of the Joint Workshop on Multimedia for Cooking and Eating Activities and Multimedia Assisted Dietary Management, MADiMa@IJCAI 2018, Mässvägen, Stockholm, Sweden, July 15, 2018, pages 71–74. ACM, 2018. [23] Tero Karras, Timo Aila, Samuli Laine, and Jaakko Lehtinen. Progressive growing of gans for improved quality, stability, and variation. CoRR, abs/1710.10196, 2017. [24] Tero Karras, Samuli Laine, and Timo Aila. A style-based generator architecture for generative adversarial networks. CoRR, abs/1812.04948, 2018. [25] Diederik P. Kingma and Jimmy Ba. Adam: A method for stochastic optimization, 2014. cite arxiv:1412.6980Comment: Published as a conference paper at the 3rd International Conference for Learning Representations, San Diego, 2015. [26] Diederik P Kingma and Max Welling. Auto-encoding variational bayes, 2013. 74
TFG Gans 2022 UCM [27] Alex Krizhevsky, Ilya Sutskever, and Geoffrey E Hinton. Imagenet classification with deep convolutional neural networks. In F. Pereira, C. J. C. Burges, L. Bottou, and K. Q. Weinberger, editors, Advances in Neural Information Processing Systems, volume 25. Curran Associates, Inc., 2012. [28] Jakub Langr and Vladimir Bok. GANs in Action. Manning Publications, New York, NY, October 2019. [29] Lars M. Mescheder. On the convergence properties of GAN training. CoRR, abs/1801.04406, 2018. [30] Mehdi Mirza and Simon Osindero. Conditional generative adversarial nets. CoRR, abs/1411.1784, 2014. [31] Augustus Odena, Christopher Olah, and Jonathon Shlens. Conditional image synthesis with auxiliary classifier gans. CoRR, abs/1610.09585, 2016. [32] Taesung Park, Ming-Yu Liu, Ting-Chun Wang, and Jun-Yan Zhu. Gaugan: semantic image synthesis with spatially adaptive normalization. pages 1–1, 07 2019. [33] Taesung Park, Ming-Yu Liu, Ting-Chun Wang, and Jun-Yan Zhu. Gaugan: Semantic image synthesis with spatially adaptive normalization. In ACM SIGGRAPH 2019 Real-Time Live!, SIGGRAPH ’19, New York, NY, USA, 2019. Association for Computing Machinery. [34] Adam Paszke, Sam Gross, Francisco Massa, Adam Lerer, James Bradbury, Gregory Chanan, Trevor Killeen, Zeming Lin, Natalia Gimelshein, Luca Antiga, Alban Desmaison, Andreas Kopf, Edward Yang, Zachary DeVito, Martin Raison, Alykhan Tejani, Sasank Chilamkurthy, Benoit Steiner, Lu Fang, Junjie Bai, and Soumith Chintala. Pytorch: An imperative style, high-performance deep learning library. In Advances in Neural Information Processing Systems 32, pages 8024–8035. Curran Associates, Inc., 2019. [35] Thomas Pinetz, Daniel Soukup, and Thomas Pock. Impact of the latent space on the ability of {gan}s to fit the distribution, 2020. [36] Alec Radford, Luke Metz, and Soumith Chintala. Unsupervised representation learning with deep convolutional generative adversarial networks. November 2015. [37] Aditya Ramesh, Mikhail Pavlov, Gabriel Goh, Scott Gray, Chelsea Voss, Alec Radford, Mark Chen, and Ilya Sutskever. Zero-shot text-to-image generation, 2021. [38] Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. CoRR, abs/1505.04597, 2015. [39] Eda Zhou Sharon Zhou, Eric Zelikman. Specialized program: Generative adversarial networks (gans). https://www.coursera.org/specializations/ generative-adversarial-networks-gans#courses.html, 2021. Accessed 14/05/22. [40] Michael Soloveitchik, Tzvi Diskin, Efrat Morin, and Ami Wiesel. Conditional frechet inception distance. CoRR, abs/2103.11521, 2021. 75