scieee AI-readable full text Open interactive document viewer

Analysis of state-of-the-art deep generative models for images

Salvia Punsoda, Víctor

Abstract

In this work we will try to break down the fundamentals of deep generative models for image generation. For the sake of simplicity and understanding we will be using the MNIST dataset, which can be easily trained and understood. The algorithms that we will be explaining and comparing are an autoregressive model, a flow-based model, a variational autoencoder, and a generative adversarial network. Within each of these categories, we have chosen simple algorithms for the sake of clarity as well. Keep in mind that this is a wide but introductory work to the area of image generation. However, these algorithms were certainly state-of the-art around 2016.

Full text

Title: Analysis of state-of-the-art deep generative models for images Author: Víctor Salvia Punsoda Advisor: Alberto Sanfeliu Cortés Department: Mobile Robotics and Intelligent Systems, IRI Academic year: 2019-2020 Degree in Mathematics Universitat Politècnica de Catalunya Facultat de Matemàtiques i Estadística Degree in Mathematics Bachelor’s Degree Thesis Analysis of state-of-the-art deep generative models for images Víctor Salvia Punsoda Supervised by Alberto Sanfeliu Cortés June, 2020 First of all, I would like to thank Alberto for his guidance, passion, and trust. I will always remember how he introduced me to such an exciting and useful tool for the future. I also wanted to thank Javi and Albert for their help throughout the whole project. Finally, thanks to my family and friends for their unconditional support. Abstract In this work we will try to break down the fundamentals of deep generative models for image generation. For the sake of simplicity and understanding we will be using the MNIST dataset, which can be easily trained and understood. The algorithms that we will be explaining and comparing are an autoregressive model, a flow-based model, a variational autoencoder, and a generative adversarial network. Within each of these categories, we have chosen simple algorithms for the sake of clarity as well. Keep in mind that this is a wide but introductory work to the area of image generation. However, these algorithms were certainly state-of the-art around 2016. Keywords Machine Learning, Deep Learning, Artificial Neural Networks, Deep Generative models, Image Generation, Computer Vision, GANs, VAEs, Autoregressive Models, Flow-Based Models. 1 Contents 1 Introduction 3 1.1 Motivation of deep generative models . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 Generation of images: Handwritten digits . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Goalsofthework .................................... 6 1.4 Notation......................................... 7 2 Background: Deep Learning and Machine Learning basics 8 2.1 Introduction ....................................... 8 2.2 Models: Artificial Neural Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.3 Loss function, optimization, and back-propagation . . . . . . . . . . . . . . . . . . . 11 2.4 Training, Validation, and Test sets . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.5 Deep generative models taxonomy . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3 Tractable density models: MADE and NICE 17 3.1 Training ......................................... 17 3.2 Autoregressive models: MADE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 3.3 Flow-basedmodels:NICE................................ 21 3.4 Results.......................................... 26 4 Approximate density models: Variational Autoencoders (VAEs) 28 4.1 Model .......................................... 28 4.2 Training ......................................... 29 4.3 Architecture ....................................... 31 4.4 Results.......................................... 32 5 Implicit density models: Generative Adversarial Networks (GANs) 35 5.1 Model: generator and discriminator agents . . . . . . . . . . . . . . . . . . . . . . . 35 5.2 Training ......................................... 36 5.3 Architecture ....................................... 37 5.4 Results.......................................... 38 6 Conclusions, Comparisons and Future Work 41 7 Bibliography 44 A Programs 46 1. Introduction In this section we will motivate the work done as well as present the specific problem that we want to solve. 1.1 Motivation of deep generative models Figure 1: Faces generated by GANs [10] We live in a world where data is becoming increasingly important. Classical statistical models help us with reasonable amounts of data, but when dimensions are high (images, voice, text...) they fail to capture meaningful features. This is the case for images and computer vision. So far, deep learning has had a big impact in supervised learning 1, where we basically prepare the data so that the algorithm knows what we want ’him’ to learn. Then, showing ’him’ these prepared examples it learns the specific task. For instance, we could train a supervised model to distinguish cats from dogs. Conversely, unsupervised learning makes no use of labelled data. This is much more real and practical, since we can use raw data, but way more challenging. One of the possible unsupervised tasks is to model the probability distribution of a given dataset - such as handwritten digits or faces. Some important examples are: •Images (GANs) •Speech (WaveNet) •Texts (GPT-2) These kinds of data are not normally labelled unless we invest a significant amount of time in doing so. Great achievements in the area of unsupervised learning are the generation of images with GANs, the generation of voice with WaveNet, and text generation with GPT2. 1Task of learning a function that maps an input to an output based on example input-output pairs. 3 Deep Generative Models direction3the more activated the neuron. In the sigmoid case things are similar. If we get further in the positive direction the neuron gets more activated, whereas in the negative direction it loses signal. To see the last statement in the sigmoid case, let us define z=w1x1+···+wnxn+b ˆy=1 1 + e−z If we impose z= 0 we get ˆy= 1/2, which comes to say that the hyperplane z= 0 is the boundary of halfway activation. If z>0then we will have more signal, else (z<0) we will have less. This can be visualized in figure 6. Figure 6: Hyperplane z= 0 that separates the data space into 2 regions, signals higher than 0.5 and lower. The distances to the hyperplane are the ones defining the signalling. Fully Connected Neural Networks In this setting we will basically stack together some neurons using layers. The architecture can be visualized in figure 7. In that case we only have one hidden layer, but there could be as many as we would like to. The notation will be very important to understand the equations in this thesis. We will use W(i)to denote the weights used to go from layer i−1to layer i. Also, keep in mind that normally we will use the same activation function for all the neurons of a given layer, and we will also have the bias b(i) j, where jindicates the position of the neuron in the layer and ithe layer we are in. Clearly, with all this we will have a parametric model which can be written as ˆ y=f(x;θ) where θwill be used as the whole set of parameters and where the output can be a vector. 3This means the direction in which the normal vector is pointing towards, such that in that direction the weighted sum gets higher. 10 Figure 7: Fully connected neural network. Other architectures Using these as the building blocks there are also other architectures that are being used. The most typical ones are convolutional neural networks (CNNs) and recurrent neural networks (RNNs). Once the building blocks are clear both are very easy to understand. The former ones are used for images because the architecture is tailored for these kinds of applications. The basic idea is that they use filters (a small matrix of weights) and slide them through the whole image such that each filter learns to capture different shapes. If we wanted to improve the performance of our algorithms we could try to use CNNs in our architectures, but since the goal of this work was to introduce and explore deep learning in generative models we have kept it simple by ommitting the use of CNNs. In real world models the architectures are extremely complex, stacking all these architectures together. A typical model for images is to use some convolutional layers at the beginning and end with some fully connected ones (as well as pooling layers,batch normalization [9], etc.). 2.3 Loss function, optimization, and back-propagation The first thing we should do if we want to learn something using Artificial Neural Networks is to define a loss function. A loss function is basically one which tells you how far you are from the desired outcome. This means that the higher the loss function, the worse your models are performing. In supervised learning for example we normally have our outputs ˆ yand the real targets y. Then, the function will compute some distance between those so that we have a value to optimize. In our case we don’t have a target (unsupervised learning) so we could see our loss function as: L(f(x;θ)) If we are using the whole dataset we will use the average 1 N N X k=1 L(f(x(k);θ)) The way to define our loss in generative models will be based in principles related to maximum likelihood. Now, we will need a good algorithm to optimize (minimize in this case) the function. 11 Deep Generative Models We want it to be as low as possible so that we are close to the desired output. In order to find the minimum of this function we could take the derivatives and equate them to zero. However, this has no closed form and this is why we must use an optimization algorithm. What an optimization algorithm does is basically take the function we are trying to minimize and roll downhill. The inevitable question now is how to find out the downhill direction. Easy, we just have to compute the gradient at the position we are in. The gradient is the direction of steepest ascent, which means we should take negative gradient and roll down a bit in that direction. This is the essence of all the optimization algorithms that we will see now. Let us introduce now different ways to approach this problem. Gradient descent Gradient descent is the classical method for optimization. In it we take the whole dataset (Ndata points), compute the loss function, and take its gradient. Then, we move in the opposite direction with a given rate (the learning rate µ): θnew =θold −µ∇θ 1 N N X k=1 L(f(x(k);θold))! Stochastic gradient descent (SGD) Now, rather than computing the whole loss function we only evaluate it in a simple example. The way to update the weights would be, for every data point x(k): θnew =θold −µ∇θL(f(x(k);θold)) The advantages of this method is that for large datasets we do not have to wait to compute the function in the complete dataset, which can be very expensive computationally, and instead we can break the task into unit steps. Also, since this will not lead us straight towards the minimum as you will see in a later visualization 8, it can be very useful to avoid local minima. Minibatch gradient descent Now, we will do something in between the methods you have seen above. We will split our training data in a bunch of batches of datapoints. Once we have this, we will do the same as in the former methods. The direction we get will be more reliable than the SGD and at the same time quicker than gradient descent. This is a tradeoff we will always face. Find a great visualization of all these methods in 8. Figure 8: Visualization of the optimization algorithms [15]. 12 Momentum Momentum is something we can add in our optimization algorithm which basically saves all the past gradients. Adding it in our algorithms helps them converge faster. We will initialize a velocity parameter v, and at each step update it doing vnew =αvold −µ∇θ b X k=1 L(f(x(k)))! where bis the batch size. And now: θnew =θold +v Clearly, the larger αis with respect to µ, the more previous gradients affect the current direction. RMSProp: Root Mean Square Propagation This algorithm incorporates an adaptative learning rate. The way it does this is by keeping an exponentially decaying average of the square of the gradients. g=1 b∇θ b X k=1 L(f(x(k);θ))! r=ρr+ (1 −ρ)gg ∆θ=−µ √δ+rg θ=θ+ ∆θ This helps in the sense that for the directions in which the last gradients have been very large it reduces the learning rate, but for the directions that have had little change it forces them to move faster. Notice that δis just a small value to prevent dividing by zero. Also, we are incorporating a new hyperparameter4ρ. This one is called the decay rate and is basically how fast we forget past information. Empirically, this has been shown to be one of the best algorithms for deep learning. Adam: Adaptative Moments Estimation [12] In this final algorithm we will be using first and second order estimates. g=1 b∇θ b X k=1 L(f(x(k);θ))! t=t+ 1 s=ρ1r+ (1 −ρ1)g r=ρ2r+ (1 −ρ2)gg ∆θ=−µs √r+δ 4A hyperparameter is a parameter that we set and it is not learned. 13 Deep Generative Models where sis the first order estimate and rthe second order. The interpretation here is that the first moment is basically taking the role of momentum and the second one is helping in adapting the learning rate. Another fair interpretation is that we are basically normalizing the steps with the variance of the gradients. In reality there is an intermediate step which is used to correct some bias but it has little effect in the long run and it will not help us understand what the algorithm is doing. Adam will be the algorithm that we will be using in most of the models. Note: Something worth mentioning is that the initialization of the weights can be very important in training. Empirically, sampling them in the following way has been shown to be a good practice: std =1 layer size w∼U[−std,std] This is how PyTorch (the programming language used) automatically initializes the weights in fully connected layers. Back-propagation Now, how do we take derivatives? It turns out we can do it analytically. Recall that we have L(f(x(k);θ)) for each data point. Basically we would like to see how to find the gradient with respect to all the weights so that we can update them. First of all the loss function has to be differentiable with respect to ˆyi=fi(x;θ), the i-th components of the function. That way we would have ∂L ∂ˆyi where L=1 bPb k=1 L(f(x(k);θ)). Now, we have that ˆyi=g(z(l) i)5, and since the activation function is differentiable and assuming we know the derivative we can do ∂ˆyi ∂z(l) i Finally, since z(l) i= n X j=1 wi j(l)h(l−1) j+bi(l) we would have that ∂z(l) i ∂wi j(l)=h(l−1) j The notation wi j(l)means that it is the weight that goes from poistion jto position iin layer l(in the matrix W(l)it is row iand column j). Following this same process we can go all the way backwards until we have all the gradients. This is how the library PyTorch we are using computes them. Once we have the gradients for each step, we can use the chain rule: ∂L ∂wi j(l)=∂L ∂ˆyi ∂ˆyi ∂z(l) i ∂z(l) i ∂wi j(l) 5Recall that g is the activation function an z(l) iis the result of the weighted sum in the i-th neuron before applying the activation in layer l. 14 This gets more complex as we go backwards into the network but the idea is exactly the same. 2.4 Training, Validation, and Test sets Now, how do we see whether our model is actually good or not? The first thing we must check is that our loss function is decreasing. This indicates that our model is learning/improving under the metric we set with the data that we are using. However, this can be misleading. Imagine that you were doing well with your data but only because you memorized what you have to do. For example, in trying to distinguish cats from dogs you memorized which pictures are cats and which ones are dogs, rather than trying to capture meaningful features that define what is a cat and what is a dog. In that case, if shown new data of cats and dogs you would have no clue on how to identify them correctly. This is a pervasive problem in deep learning and is called overfitting. In order to check that our algorithm is generalizing knowledge and not memorizing, we will divide the initial dataset Xin two subsets Xtrain and Xtest (in the supervised setting we would do the same with the outcome variable y). Since we have only learned with the training set, the algorithm has not seen the test set. We will use this set to evaluate how well our model does with unseen data, which basically tells us whether it is really learning or just memorizing. Sometimes we can even divide into 3 sets: validation, training, and test. In that case, we train with the training set and make some evaluations with the validation that helps us tune the hyperparameters. Once this is done we use the test set. This allows us to avoid overfitting to the test set as well. 2.5 Deep generative models taxonomy There are different types of generative models. All of them are somehow maximizing the likelihood of the training set coming from our distribution. The difference is that some of them are learning the explicit distribution while others are only learning to sample from the distribution - they don’t have access to the density function (Implicit density: GANs). Within the first category we can find models that have access to the distribution (Tractable density: autoregressive models and flow models) and others that only have access to an approximation (Approximate density: VAEs). Figure 9shows how Ian Goodfellow describes it. Figure 9: Taxonomy of deep generative models using maximum likelihood [6] 15 Deep Generative Models In this work we have used an autoregressive model (MADE), a flow-based model (NICE, change of variable models), a variational autoencoder, and a GAN. 16 3. Tractable density models: MADE and NICE In tractable density models we have the analytical expression for pθand are able to evaluate it. These models are trained minimizing the KL divergence6between two distributions, or equivalently, maximizing the likelihood of the sample to occur. There are two questions to be answered now: how do we train and represent pθ? First we will see how to train our model using maximum likelihood. Then, we will see how to design pθ. The requirements are the following ones: •Compute log pθ(x)efficiently as well as its gradient. • ∀θ,Pxpθ(x)=1and pθ(x)≥0, ∀x We will tackle this in two different ways. These are the most common ones in the tractable density paradigm: Autoregressive models and Flow-based models. 3.1 Training In this section we will assume we have a given model pθ(x)and want to find the best parameters ˜ θ. In order to do so we have the following sample: x(1), ..., x(N)∼pdata(x) Where every point is a picture of the MNIST dataset. Figure 10: Clearly, we want to find the nearest point that minimizes the distances between models [20]. KL-divergence and Maximum Likelihood Now, how do we measure closeness? This definition will allow us to find the parameters that minimize this distance. We will use KL-divergence, which is equivalent to maximum likelihood. KL-divergence measures the distance between two distributions: DKL (p||q) = Ex∼plog p(x) log q(x) 6Explained bellow. 17 Deep Generative Models Clearly, if both distributions are the same DKL (p||q) = 0. Intuitively we can see that the distance will be low if in likely points of p, both distributions are similar. Notice as well that it is not a distance, since it is asymmetric. Also, we know that DKL (p||q)≥0, which will be very helpful in future applications. Finally, doing some simple maths and applying it to our model: DKL (pdata||pθ) = Ex∼pdata [log pdata(x)] −Ex∼pdata [log pθ(x)] And since the first term does not depend on θ, by minimizing the KL-divergence we are basically maximizing the expected log-likelihood. Using the a Monte Carlo estimator: Ex∼pdata [log pθ(x)] ≈Ex∼pdata [log pθ(x)] = 1 N N X k=1 log pθ(x(k)) We know that Monte Carlo estimators are unbiased, converge to the expected value, and the variance decreases as the number of samples increases. In order to solve this non-convex optimization problem we used the Adam algorithm. Remember that we will not find the optimal point but we just want a "satisfying" solution. Understand that this will be the same process no matter which model we are using, that is why we explained first the training because it is common in all tractable density models. 3.2 Autoregressive models: MADE Recall our MNIST case (n= 784): x(1), ..., x(N)∼pdata,x∈ {0, 1}n We want to find the explicit density function as well as be able to sample from it. We will try to tackle this problem using the following property: p(x) = n Y i=1 p(xi|x1, ..., xi−1) This is a specific type of Bayes network which holds the autoregressive property, hence the name of the model. The autoregressive property states that the probability of the current state depends on the whole past states. The order we pick for the pixels will be an implicit assumption we are making on the given data. In our specific case of pictures we will typically order them left to right and top to bottom. Note: The autoregressive property is much more natural in text or voice applications, where data is a real sequence. The probabilistic model we are building for each pixel iis the following (Bernoulli distribution): pθi(xi|x<i) = Be(fi(x<i;θi)) The fully expressive model would be a histogram, meaning that the function fwould have a different parameter for every set of inputs indicating the probability. However, as we have seen in the introduction, it is not useful at all in our scenario. What we will do is to reduce the expressiveness of our function in order to have a feasible model. 18 Logistic Regression We can first try with fi(x1, ..., xi−1) = σ(αi 0+αi 1x1+ ... + αi i−1xi−1)∈[0, 1] Since each fineeds iparameters, then |θ|=Pn i=0 i=n(n+1) 2≈O(n2), which now gives us a more reasonable amount of parameters. Single layer neural network Going one step further we can try a single layer neural network, which would be much more expressive than a logistic regression. hi=σ(Aix<i+ci) fi(x1, ..., xi−1) = σ((αi)thi+bi) With hi∈Rk, we have now O(n2k). Therefore we have increased both the parameters and the expressiveness of the model. NADE: The Neural Autoregressive Density Estimatior [13] Now, to reduce the number of parameters, we will tie the weights that come from every single input as done in figure 11. We will do the following: hi=σ(W:,<ix<i+ci) ˆxi=p(xi|x<i) = σ((αi)thi+bi) Notice that now the weight matrix Wis shared among all hi. The number of parameters we now Figure 11: This picture from [21] shows the architecture that NADE follows. have are O(nd), which is an important improvement. 19 Deep Generative Models 2nd layer: h(2) I2=h(1) I2,h(2) I1=h(1) I2+m(2)(h(1) I2) ... The third and fourth layers are the same permutations. Finally, the scaling layer: ˆ x=h(5) =esh(4) We have defined 4 functions m(1), ..., m(4) that will be learned with fully connected neural networks. All of them will have the same structure, 5 hidden layers with 500 units. 3.4 Results We have trained both models using maximum likelihood and 100 epochs each. As it can be seen in figures 16 and 17 both models converge without important overfitting. It is interesting to see how the likelihood in both models is very different. This is due to the construction of both models. In the autoregressive model we have learned a discrete model in which pixels were binary. However, in flows we have learned it as if our pixels were continuous. This is why both likelihoods are very different and cannot be compared. The last thing has been sampling from both models, which can be seen in figure 18. We will compare both algorithms in the last section. Figure 16: MADE losses. 26 Figure 17: NICE losses. Figure 18: NICE in the left and MADE in the right. 27 Deep Generative Models 4. Approximate density models: Variational Autoencoders (VAEs) In this setting we assume that the data {x(i)}N i=1 ∼pdata(x)is generated from an unobserved latent variable Z=R2. This hidden variable encodes the digit, the dimension of the number, the rotation, etc. You will see in figure 25 how this space will represent meaningful features. Figure 19: This is the model we are building. The circles within each space emphasize the fact that the image of the function (either the encoder or the decoder) is a probability distribution in the other space. 4.1 Model Let us define first the following distributions: •pz(z) = N(0, I)is the prior distribution on Z. •pdata(x)is the real distribution of the images and pθ(x)our approximation. •pθ(x|z) = N(µx=f(z;θ), σ2I)is a model we will learn (decoder), where fθ:R2→R784 is a neural network. Basically, given a code zwe will output a distribution in the image space with mean µx. We will assume σ2≈0to avoid noisy samples. Having all this defined, it follows that: •Implicitly, we are already defining the likelihood: pθ(x) = Zpθ(x|z)pz(z)dz •And the posterior (encoder): pθ(z|x) = pθ(x|z)pz(z) pθ(x) 28 •As we will see, this posterior is intractable because pθis intractable. That is why we define an approximation qφ(z|x) = N(µz(x;φ), Σz(x;φ)). Here, similarly, µzand Σzwill be neural networks. Keep in mind that all these are assumptions we are making in order to model the real distributions. The result will tell us if this were logical assumptions or not. We will attempt to model pθ(x|z) because it will be much easier than the whole pθ(x), which will be approximated later on. Once we have the model, we will be able to generate new images using: z∼pz x∼pθ(x|z) One can check how all this looks like in image 19. 4.2 Training Problem: As we have seen, the likelihood we would like to maximize under the training data is: pθ(x) = Zpθ(x|z)pz(z)dz We could easily think that in order to approximate the integral we could use: pθ(x) = 1 N N X i=1 pθ(x|zi), with zi∼pz(z)(1) However, in order for this to be accurate we would need a lot of samples. In practice this is an intractable problem, and this is why we will use variational inference. We will find a tractable lower bound of the likelihood and optimize it. Notice that given an image ˜ xthere are a lot of zi’s that don’t contribute to the likelihood whatsoever. If p(·|zi)is the distribution obtained from the code zigiven, but the image on the training p(˜ x|zi)≈0is very unlikely, then it is not contributing to equation 1. It would be nice if we knew how to sample the "right way", meaning the z’s that are more likely under the xwe are seeing. Then, we could do the latter approximation without the need of many samples. This is why we introduced qφ(z|x), which approximates the intractable pθ(z|x). Solution: variational inference Now, how can we relate all this? DKL (qφ(z|x)||pθ(z|x)) = Ez∼qφ(z|x)[log qφ(z|x)−log pθ(z|x)] =Ez∼qφ(z|x)[log qφ(z|x)−log pθ(x|z)−log pz(z)] + log pθ(x) Rearranging some terms and using that the KL divergence is non-negative: log pθ(x)≥log pθ(x)−DKL (qφ(z|x)||pθ(z|x)) =Ez∼qφ(z|x)[log pθ(x|z)] −DKL (qφ(z|x)||pz(z)) = L(θ,φ;x) It is very important to understand that this function is for a single image x. We will call this term the variational lower bound (VLB) and we will define each term as: 29 Deep Generative Models •The reconstruction loss:Ez∼qφ(z|x)[log pθ(x|z)]. This is reconstruction because we first sample an image x, encode the image using qφ, and go back to the image space with pθ(x|z). It is then evident that we want to maximize this term. •The regularization term:DKL (qφ(z|x)||pz(z)). This term is the distance between the 2 distributions. It is called the regularization term because it is making sure that the new distribution behaves as similarly to the prior as possible (minimizing). By maximizing the whole loss function we are both maximizing the likelihood as well as minimizing the distance between the two distributions (qφ(z|x),pθ(z|x)). Hence, we are not only learning a model pθ(x)but also approximating pθ(z|x)with qφ(z|x), which can give us further information about the latent space. Loss function Now, we can break down the optimization objective. First of all, the KL-divergence has a closed form because it is comparing two gaussians: DKL (qφ(z|x)||pz(z)) = DKL (N(µz(x;φ), Σz(x;φ))||N(0, I)) =1 2[tr(Σz) + µt zµz−k−log(det(Σz))] The reconstruction term, Ez∼qφ(z|x)[log pθ(x|z)], will be approximated with just one example (stochastic approximation). How to compute log pθ(x|z)? Knowing that the dimension of the space is n= 784,Σx=σ2In, and det Σx=σ2n: pθ(x|z) = 1 (2π)n/2|Σx|1/2e −1 2(x−µx)tΣ−1 x(x−µx)=1 (2π)n/2σne −1 2σ2(x−µx)2 Now, doing the log-probability we get that it is proportional to the mean square error, which is widely used in these kinds of tasks. Reconstruction loss =λ(x−µx)2 Therefore, the loss function for the whole dataset or batch X= [x(1), ..., x(N)]will be: L(θ,φ;X) = 1 N N X i=1 L(θ,φ;x(i)) L(θ,φ;x(i)) = log pθ(x(i)|z)−DKL qφ(z|x(i))pz(z) This is the approximation we are making, which converges to the real gradient we aim for. In order to train our model we just have to use an optimization algorithm. Gradients Given the random nature of these mappings, it is unclear how we should be taking gradients. In figure 20 one can see how the losses are computed through the process. The problem is that there 30 are random processes which do not allow gradients to be taken. What we will do is known as the reparameterization trick. Instead of sampling from µxand Σx, we will do the following: z=µx+Σx, where ∼ N(0, In) Other than that all are differentiable functions, which means we can take gradients without any problem. Figure 20: In this image we can see how the losses are computed in the process. One can clearly see that in order to take gradients from the reconstruction loss to the encoder qφwe have to go through a random process (sampling z). However, in order to be able to take gradients we can implement the reparameterization trick. The image can be found in [4]. 4.3 Architecture Figure 21: VAE architecture. All the layers are fully connected ones. One can see the architecture used in figure 21. As you can see, we are using fully-connected layers both in the encoder and the decoder. Also, notice that the latent space is very low dimensional (2). This means that we are compressing a lot the initial space, learning a very meaningful representation. 31 Deep Generative Models 4.4 Results We ran the algorithm for 100 epochs and used a batch size of N= 100. As you can see in figure 22, we stopped at epoch 100 to avoid overfitting. Although the gap between the training and test performance was considerable, the test performance was still as good as in epoch 60. This is why as the final model we used the one at epoch 100. One can see the resulting images in figure 23. Latent space interpolation and 2D visualization In figure 24 we can see what happens if we interpolate two random points in the latent space and project the line between them. Since the prior is a normal, we expect that the line between the points must be very likely as well, and this is why the images are still digits. In this case we go from a7to a 9. Another great visualization can be seen in figure 25. In it we are basically taking some images and using the encoder to know which point in R2corresponds to each of them. Once this is done we can see how different numbers are distributed in the Zspace. Notice that 7and 9are close in this space and this is why when doing the interpolation we did not go through any other numbers. Figure 22: Losses for variational autoencoders. 32 Figure 23: VAEs generated digits. Figure 24: This is the interpolation of 2 random points in the latent space projected in the image space. 33 Deep Generative Models Figure 25: Here one can visualize the digits in the latent space. It is very interesting to see how similar digits are clustered next to each other (1and 7for instance). 34 5. Implicit density models: Generative Adversarial Networks (GANs) So far we obtained good likelihood-based models, but what if we tried likelihood-free learning? In likelihood-based models we maximize the probability of observing the training set given a parametric probability function - we optimize the parameters of this function to fit the data. Once this is done, we have a tractable distribution where we can sample from. Keep in mind that a good generative model is one which has good sample quality and high likelihood. However, the highest likelihood does not necessarily mean the best sampling. We will now switch our approach by focusing on the sampling process - we will learn a sampler. We will define an agent (G, generator) that generates new images, and another (D, discriminator) that discriminates whether an image is real or fake. These two agents will play against each other the following game several rounds. Each round will consist of the following steps. 1. Ggenerates new images. 2. Dwill be given several images, both generated and real. 3. Dwill classify these images as real or fake. 4. Gand Dwill learn from the errors they have made and improve their methods/systems. Following this process, Gand Dwill become stronger and stronger. Notice that if they end up being perfect, the generated images will be indistinguishable from the real ones and Dwill be unable to discern real from fake. Once this happens, Gwill be the sampler we are looking for. 5.1 Model: generator and discriminator agents We will define these agents using neural networks (Gand Dare neural networks). The discriminator will learn a mapping from the image space to the [0, 1] space. Dθd:R784 −→ [0, 1] x−→Dθd(x) = p(real|x) As you can see the discriminator depends on the weights θdof the neural network that defines the agent. From now on we will just use D=Dθd. The generator will learn a mapping from a latent space Z=R64 to the image space. Gθg:Z −→ R784 z−→Gθg(z) = fake image Similarly, we will use G=Gθg. We will define a prior distribution in Z(multivariate normal) where we will sample noise from. The sampling process goes as follows: z∼pz 35 Deep Generative Models •In real applications GANs have lately outperform any other model in terms of sampling. •An advantage of VAEs over GANs is that with VAEs we have an approximation of the likelihood, which might be worth using in some applications. Note: A very important advantage in using VAEs is that they learn a low-dimensional representation which can help us find very interesting features that other algorithms might not. In GANs we also have a low dimensional representation but it is not as accessible as the one in VAEs. To sum up, each algorithm has its strengths and weaknesses and we should be aware of them in order to make the best possible choice. Depending on the task we want to implement we will decide which one is best. Future Work There are several things we could do as a natural continuation of this work. 1. Try to build conditional models. These are the same ones we have built but with the ability of telling them which number you want to sample. The models in which this feature has been less explored are flows. There is some research being done such as [18], conducted by researchers at IRI as well. 2. Once the models have been tested and understood in the MNIST dataset, we could go on and compare them in very high dimensional spaces (the most natural continuation would be to apply it in better quality images). This would allow us to have a much more accurate comparison of each model in real examples. 3. We could also change the architectures of the networks being used and see how much our models could improve. As we have mentioned throughout the thesis, CNNs are the most suited architectures for images. These, combined with some final fully connected layers and other typical features could certainly improve performance. 4. As a final suggestion, we could also do some research and see where we could apply these generative models. As a personal preference I would start looking at medical image applications. Conclusions We will go through the goals we had for this work. 1. The first goal has been accomplished by far. I feel very comfortable now with reading deep learning papers and thinking about possible applications of this incredible tool. I even had the pleasure to attend a conference in Barcelona with top researchers in the field. Also, I understand how high-dimensional distributions are modelled and most importantly why these models are used. 2. Also, we succeeded in reviewing and comparing these 4 approaches in the field of image generation. We compared their ability to yield quality samples, their ability to evaluate the likelihood function, and their ability to learn a low dimensional representation. 42 3. I have learned PyTorch, the most promising deep learning library, as well as how to develop and structure a machine learning project in general (using GitHub as well). 4. Finally, I have written this thesis in a way that it could be understood by a wide audience without renouncing the use of advanced mathematics. My hope is that this will be used as an introduction to the field of deep learning and deep generative models. 43 Deep Generative Models 7. Bibliography The most important sources of knowledge for this work have been the Deep Learning Book [7], two different online courses on Deep Generative Models [20] and [1], and the Deep Learning Specialization on Coursera [15]. References [1] Pieter Abbeel. Deep Unsupervised Learning. Online Course. 2019. url:https : / / sites .google.com/view/berkeley-cs294-158-sp19/home. [2] DeepMind. WaveNet. Audio generation. 2016. url:https://deepmind.com/blog/article/ wavenet-generative-model-raw-audio. [3] Laurent Dinh, David Krueger, and Yoshua Bengio. NICE: Non-linear Independent Components Estimation. 2014. arXiv: 1410.8516 [cs.LG]. [4] Carl Doersch. “Tutorial on variational autoencoders”. In: arXiv preprint arXiv:1606.05908 (2016). [5] Mathieu Germain et al. MADE: Masked Autoencoder for Distribution Estimation. 2015. arXiv: 1502.03509 [cs.LG]. [6] Ian Goodfellow. “NIPS 2016 tutorial: Generative adversarial networks”. In: arXiv preprint arXiv:1701.00160 (2016). [7] Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Deep Learning.http://www.deeplearningbook .org. MIT Press, 2016. [8] Ian Goodfellow et al. “Generative adversarial nets”. In: Advances in neural information processing systems. 2014, pp. 2672–2680. [9] Sergey Ioffe and Christian Szegedy. “Batch normalization: Accelerating deep network training by reducing internal covariate shift”. In: arXiv preprint arXiv:1502.03167 (2015). [10] Tero Karras, Samuli Laine, and Timo Aila. “A style-based generator architecture for generative adversarial networks”. In: Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2019, pp. 4401–4410. [11] Adam King. Talk To Transformer. Text generation. url:https://talktotransformer.com/. [12] Diederik P Kingma and Jimmy Ba. “Adam: A method for stochastic optimization”. In: arXiv preprint arXiv:1412.6980 (2014). [13] Hugo Larochelle and Iain Murray. “The neural autoregressive distribution estimator”. In: Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics. 2011, pp. 29–37. [14] Yann LeCun, Corinna Cortes, and CJ Burges. “MNIST handwritten digit database”. In: AT&T Labs [Online]. Available: http://yann. lecun. com/exdb/mnist 2 (2010), p. 18. [15] Andrew Ng. Deep Learning Specialization. Deep Learning course. url:https://www.coursera .org/specializations/deep-learning. [16] Michael Nielsen. A visual proof that neural nets can compute any function. Neural Networks and approximation. url:http://neuralnetworksanddeeplearning.com/chap4.html. 44 [17] Aaron van den Oord et al. WaveNet: A Generative Model for Raw Audio. 2016. arXiv: 1609 .03499 [cs.SD]. [18] Albert Pumarola et al. C-Flow: Conditional Generative Flow Models for Images and 3D Point Clouds. 2019. arXiv: 1912.07009 [cs.CV]. [19] Alec Radford et al. “Language models are unsupervised multitask learners”. In: OpenAI Blog 1.8 (2019), p. 9. [20] Aditya Grover Stefano Ermon. Deep Generative Models. Course offered by top researchers in this field. url:https://deepgenerativemodels.github.io/. [21] Benigno Uria et al. Neural Autoregressive Distribution Estimation. 2016. arXiv: 1605.02226 [cs.LG]. [22] Wikipedia. Artificial Neuron. Used for an image. url:https://en.wikipedia.org/wiki/ Artificial_neuron. 45 Deep Generative Models A. Programs One can find the 4 codes in my github https://github.com/VictorSP17. The repositories are: Simple GAN MNIST,VAE MNIST,MADE MNIST, and NICE MNIST. In each of them there is a jupyter notebook with all of the code. 46