<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samuele Bolotta on Medium]]></title>
        <description><![CDATA[Stories by Samuele Bolotta on Medium]]></description>
        <link>https://medium.com/@samuelebolotta?source=rss-d7523d3d796e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2TQJwivUvxy9NSBBzmliZA.jpeg</url>
            <title>Stories by Samuele Bolotta on Medium</title>
            <link>https://medium.com/@samuelebolotta?source=rss-d7523d3d796e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:19:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samuelebolotta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Probability for machine learning]]></title>
            <link>https://samuelebolotta.medium.com/probability-for-machine-learning-339ab0d575bc?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/339ab0d575bc</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 12:48:23 GMT</pubDate>
            <atom:updated>2022-11-28T19:52:59.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*as6guf3P4OP3c_OfQda5rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zHuGSwosBKFOZNKweIpWqw.jpeg" /></figure><h3>Probability theory</h3><p>Probability theory provides a consistent framework for the quantification and manipulation of uncertainty. In what ways do we have to deal with uncertainty?</p><ul><li>Uncertainty on my measurements, because there’s noise</li><li>Uncertainty related to the finite size of datasets</li></ul><p>When we talk about probability theory, we can take on:</p><ul><li>A <strong>frequentist interpretation</strong>, in which case probability is defined as the fraction of times an event occurs in an experiment. We’re going to observe random variables and we just count how many times a particular event happens — then this defines a probability which you use to make predictions for the future</li><li>A <strong>bayesian approach</strong>, in which case probability takes on a meaning as a quantification of plausibility or the strength of a belief — in a way this is a more modeling-based approach and it’s a bit more generic</li></ul><p>When we talk about probabilities, we’re dealing with <strong>random variables</strong>. These are stochastic variables sampled from a set of possible outcomes, which means that every time I make an observation of such an x, it takes on one of the values in this set of possible values x. This variable can be discrete, it can be continuous and it always comes with a probability distribution which assigns probabilities to a particular event x happening.</p><p>Probability is important to us in machine learning because the idea of generalization is that the past is predictive of the future. That is, we really believe that we can look at a bunch of training data and make interesting and useful predictions about data we have never seen before.</p><p>So, why is generalization possible? It’s possible because we’re willing to commit ourselves to structure in the data that we expect to see again and again. That is to say, in order to generalize we must make assumptions about the structure of the world. There are many different ways to specify these kinds of assumptions, but one of the most powerful frameworks is the calculus of probabilities</p><p>It’s helpful to think about all the different ways that noise and uncertainty can come into play in a problem like this.</p><ul><li>We might have noisy data</li><li>The environment might be stochastic</li><li>Uncertainty about what the optimal parameters should be, due to limited training data</li><li>Your model can’t be the perfect representation of what you’re studying</li><li>Limited amount of computation to make predictions</li></ul><blockquote>It turns out that it’s very helpful to reason about a lot of these processes in terms of random variables and probability.</blockquote><p>Even in relatively straightforward classification settings, we still like to talk about probabilities. For example, imagine building a simple image classifier for animals. It’s helpful both at training time and at testing time to be able to represent its predictions in terms of probabilities rather than saying “definitely a cat” or “definitely a dog”. Instead, these kinds of classifiers put probability distributions over the different possible labels. Ideally then, when encountering a legitimately ambiguous piece of data, the classifier can represent its uncertainty.</p><p>Regression provides another way to think about this. Imagine that we’re trying to model some true function represented by a dashed line. We’ve observed three data represented by black circles. Given that we only have three observations, there are many different functions that could explain these data. Rather than committing to only one function, it’s helpful to try to represent all the possible functions that are supported by the evidence. Then, when we make predictions, we account for all of these possible explanations of the world. It turns out too that this provides us with a really nice way to update old information with new observations and ideally we’d be able to boil all of these hypotheses off into distributions over things we might see at new locations.</p><h3>Probability density and mass functions</h3><p>Probability theory enables us to reason about our uncertainty. A key distinction that informs how we handle a particular random variable is if it’s discrete or continuous.</p><p>If we’re ever dealing with a finite set of possible values, say a categorical label from an animal classification model, then this is a discrete random variable. But discrete random variables can apply to infinite target spaces as well, specifically countably infinite, like the natural numbers.</p><p>Some of our intuitive notions of probability from everyday life transfer over to discrete probabilities, where we can think of the probability assigned to each possible state as the fraction of times that particular state is likely to occur. For example, say it’s late we’re tired and hungry and we’re randomly picking a piece of fruit out of the fridge, with an equal chance of picking any particular piece. If we have three apples, one pear and four oranges, the probabilities of picking each type of fruit are 3/8, 1/8 and 1/2, respectively.</p><p><em>We represent these with a probability mass function or PMF, essentially a list of probabilities for each possible state. For any discrete distribution, the probabilities must all lie between 0 and 1 inclusively and sum to 1.</em> A quick note on notation. We use both of these to refer to the probability of the random variable big X taking on a particular value little X:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*OmlIdQKZ6Ryw2v3PwIQIFQ.png" /></figure><p>When we have multiple discrete random variables, we can visualize the joint distribution as a table where entry “ij” contains the probability of both “Xi”and “Yj” occurring. If we define a new random variable Z as the tuple (X,Y), then Z’s target space is the Cartesian product of both x and y’s target spaces.</p><p>Continuous random variables can be slightly trickier than their discrete counterparts. We represent the distribution in a continuous setting with a probability density function or PDF. The probability density function tells us how to evaluate probabilities over intervals; we say the probability of X being between values A and B is the integral of the PDF from A to B — that is, the area under the function from A to B.</p><p><em>Like the probability mass function, the probability density function also comes with some constraints. The PDF must always be non-negative and in addition the integral of the PDF over all the reals must equal 1.</em></p><h3>Probability spaces and random variables</h3><p>We construct a probability space in order to formally reason about the kind of asymptotic frequencies of different outcomes. There are three main ingredients and, for that reason, probability spaces are sometimes referred to as probability triples.</p><p>The first ingredient is a <em>sample space </em>which we’re denoting as Omega and that’s the set of all possible things that can happen; it can be a finite or infinite set and, when it’s an infinite set, it can be countable or uncountable. The second ingredient is what we call the <em>event space</em>, denoted here as calligraphic A; this is a set of sets from the sample space Omega. The final ingredient is the <em>probability measure</em> and it’s a function that takes members of the event space and turns those into numbers between 0 and 1 that we interpret as probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*HdNXdMg1CH9CrYX_m-gH9Q.png" /></figure><ul><li>One example of a finite sample space is the set of all possible outcomes of rolling two six-sided dice; one example of an uncountably infinite sample space is the set of all points along the edge of a unit circle</li><li>An event space is a set of subsets of omega. Two critically important subsets of Omega are the empty set and all of Omega itself</li><li>The probability measure is just a function that takes members of the event space and assigns them a size that’s between 0 and 1. That notion of size needs to satisfy some properties that are kind of intuitive:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*tHf7rcp3pVh8h5qKnDufDQ.png" /></figure><p>Every event space contains the empty set and all of Omega and those need to have measure 0 and 1, respectively. The other property that we need is that if we have two disjoint sets, then the probability measure of their union must be equal to the sum of the two probability measures taken separately.</p><p><em>For a finite sample space, it’s pretty typical to take the event space to be the power set of the sample space, that is the set of all subsets of Omega. Then we can specify the probability measure completely just by assigning a probability to each of the members of Omega — that’s the thing we usually call the probability mass function.</em></p><p>The situation in a continuous sample space is of course a bit more complicated; here, we need some kind of function that can take any well-behaved subset of Omega and produce a number between 0 and 1</p><p>Now that we’ve constructed a probability space, we can finally construct a random variable. A random variable is a function from Omega to another space. The way we connect random variables to probability is we think about the preimage of any subset of T. The random variable maps from Omega to T; if there’s some subset s of T whose probability we want to reason about, then we think about its preimage in omega under the map X, that is, we look at the subset of Omega that if you applied X would lead to the set s. We denote this as the function X inverse, so then when we’re talking about the probability of the set s what we’re talking about is actually the probability of the preimage in omega and we tend to take it for granted that the preimage is a member of the event space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*-IAULbGYpnGo2qRbaa5nPQ.png" /></figure><h3>Basics of joint probability</h3><p>When talking about probability distributions over multiple variables, one of our most basic concepts is the idea of marginalization.</p><p>When we compute the marginal distribution of some subset of variables in a joint probability distribution, we’re computing the distribution that we would get if we restricted our attention only to that subset of the variables. That is, imagine that you had samples from both x and y together, but somebody came and threw away all the y’s. The resulting distribution would be the marginal distribution over X: what distribution would I get for X if I ignored Y?</p><p>If we had a joint distribution P(X,Y) over just two variables x and y, then the two marginals available to us are P(X) and P(Y). For discrete distributions we compute marginals by summing over the variables that we’re not interested in. This is sometimes called the sum rule of probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*2u667WZSHM4daFR-D2ITmg.png" /></figure><p>This orange surface represents a joint probability density function over x and y. If we were to separately integrate this PDF over its two axes, we would get two probability density functions representing the marginals P of X and P of y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*pSEuG4OrDYLQV814QBqe8g.png" /></figure><p>Having established the concept of a marginal distribution, we can now define conditional distributions. Conditional distributions fix a subset of variables and then ask what the resulting density is on the remaining variables. For both discrete and continuous variables, we get the conditional distribution by dividing the joint distribution by the relevant marginal. The only difference is whether we sum or integrate in order to compute that marginal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*HKgAF67y_s_6XFKYDaNsdw.png" /></figure><p>When we talk about conditional distributions we say something like: probability of X given Y and we use a vertical bar to denote that. P(X|Y).</p><p>The computation of a conditional distribution by dividing a joint distribution by a marginal can also be referred to as the product rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*SRVSIcbSZVHOBR52nrpjww.png" /></figure><p>We’ve multiplied both sides by the marginal P of Y and of course we also could have done this decomposition by conditioning on X instead. The celebrated Bayes’ rule is really just taking both bits on the right and dividing both of them by the marginal over Y:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*AK8_DaAieZzHY5r8x_O8iw.png" /></figure><p>The reason Bayes’ rule gets a lot of attention in statistics and machine learning is more about interpretation of random variables than it is about the equation itself. Specifically, when someone talks about being Bayesian, what they’re saying is that they’re willing to use Bayes’ rule to construct a distribution over parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*NX4fj8_PNBEQzkjRXpTrGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*mlRXTg2zYMn6BojPKc-UfA.png" /></figure><p>It’s also worth talking about expectations. The expected value of a function under a probability distribution is the average value of that function under samples drawn from that distribution. For discrete random variables, you take a sum over all possible values of f(X) weighted by P(X):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*PUJ9b1kDwBI0vtUweJpveA.png" /></figure><p>In the continuous case, you do an integration instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*V2G2dytRGFQHJJxLsaezZg.png" /></figure><p>There are some important properties of expectations that you should always keep in mind. The first is that expectation is linear. That is, the expectation of a weighted sum is the weighted sum of the expectations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*WmbQWKZ-9aFR6OYq8xKu1w.png" /></figure><p>Another thing to keep in mind is that the expectation of a product of two random variables is not in general equal to the product of the expectations. The important case when this is true is when the two random variables are independent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*tRbVtG8tALg8YARU-RlzPQ.png" /></figure><p>Another property of expected values that comes up a lot in machine learning is Jensen’s inequality. It says that a convex function applied to an expectation is always less than or equal to the expectation of that function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*sz3QTCTMRNQhLHAMod0p_Q.png" /></figure><p>Let’s also talk about properties of variances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*QL1Nhiy-dUzvl9ERIDircA.png" /></figure><ul><li>Variances are the expected squared deviation from the mean</li><li>The variance is equal to the difference between the expected square and the square of the expectation</li><li>Variances are always non-negative</li><li>Variance is not in general linear and if I take the variance of a random variable multiplied by a scalar, then I get the variance of that random variable multiplied by the square of the scalar</li><li>It’s also useful to know that the variance of a sum of independent random variables is equal to the sum of the variances of the two random variables taken separately now</li></ul><p>Finally, let’s talk about covariance. In probability, covariance is the measure of the joint probability for two random variables. It describes how the two variables change together. It is denoted as the function cov(X, Y), where X and Y are the two random variables being considered. Covariance is calculated as expected value or average of the product of the differences of each random variable from their expected values, where E[X] is the expected value for X and E[Y] is the expected value of y.</p><p>cov(X, Y) = E[(X — E[X]) . (Y — E[Y])]</p><h3>Independence and dependence</h3><p>Independence between random variables is the idea that these two variables don’t influence each other; formally, that means that the joint distribution over the two random variables factorizes into two pieces. Each of the two pieces is just a distribution over one of the variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*3H6gXT-SZ1OAEgER6cuPOg.png" /></figure><p>This also implies that the two conditional distributions are equal to their marginals. This is consistent with the intuition that knowing one of the two variables doesn’t tell anything about the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*bbGPYGXnVBQlPyAXrugVFg.png" /></figure><p>Why?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*iBbe8P7fp1tclxKu1ex5kg.png" /></figure><p>Independence also means that the expectation of the product of the two random variables is equal to the product of the expectations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*0wuGN9tYhtFfebldCi8Y2g.png" /></figure><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=339ab0d575bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep learning]]></title>
            <link>https://samuelebolotta.medium.com/deep-learning-3d22beb83edc?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d22beb83edc</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 15:44:07 GMT</pubDate>
            <atom:updated>2024-05-29T07:36:55.696Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.youtube.com/watch?v=aUNnGCxvAg0&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=4">Basic concepts in machine learning</a></p><p>Machine learning algorithms aim to model the relationship between two datasets, enabling the prediction of one dataset based on the other.</p><h3>Supervised Learning</h3><p>Supervised learning is a machine learning approach where the algorithm is trained on a labeled dataset. This means that each training example is paired with an output label. The model learns from this data to make predictions or decisions, rather than just capturing patterns. Supervised learning is commonly divided into two main types: classification (where the output is a category) and regression (where the output is a continuous value). The primary goal is for the model to learn the mapping from inputs to outputs, to accurately predict the output for unseen data.</p><h3>Unsupervised Learning</h3><p>Unsupervised learning involves training a model on data that has not been labeled, categorized, or annotated in any way. The model tries to learn the patterns and the structure from the data without any explicit instructions on what outcomes to predict. Common unsupervised learning tasks include clustering (grouping similar instances together) and dimensionality reduction (simplifying the data without losing essential information). The objective is to discover underlying patterns, distributions, or associations within the data.</p><h3>Parametric</h3><p>Parametric models assume a specific form for the function that maps inputs to outputs. These models are characterized by a fixed, finite number of parameters, regardless of the size of the data. The parameters of the model are learned from the training data. Once trained, the number of parameters does not change, making the model’s complexity fixed. Examples include linear regression and logistic regression, where the relationship between variables is defined by coefficients that are the model’s parameters.</p><h3>Nonparametric</h3><p>Nonparametric models do not assume a specific form for the mapping function and are characterized by their ability to adapt to the data’s complexity. The number of parameters can grow as the size of the data increases, allowing these models to become more complex and flexible with more data. Nonparametric approaches are useful when there is no prior knowledge about the underlying data distribution. Examples include decision trees and kernel density estimators.</p><h3>Discriminative Learning</h3><p>Discriminative learning models focus on directly modeling the boundary between classes or directly learning the relationship between the input variables and the output labels. They do not attempt to model how the data was generated but rather concentrate on the distinction between different categories of data. These models predict the probability of the output label given the input data. Examples include logistic regression, support vector machines, and deep neural networks used for classification tasks.</p><h3>Generative Learning</h3><p>Generative learning models attempt to model how the data was generated, aiming to understand the underlying distribution of the input data and the association between input and output variables. By capturing the joint probability distribution, these models can generate new data points that are similar to the training data. Generative models are useful in tasks such as density estimation, anomaly detection, and in scenarios where data augmentation is required. Examples include Gaussian mixture models and generative adversarial networks (GANs).</p><p>The combinations of learning forms — namely, supervised, unsupervised, parametric, nonparametric, discriminative, and generative — create a rich spectrum of machine learning methodologies, each suited for specific types of problems. Let’s explore how these can be combined:</p><ul><li>Supervised parametric models: these models use labeled data to learn a fixed number of parameters. Examples include linear regression and logistic regression, where the model structure is predefined, and the goal is to predict output labels from input data.</li><li>Supervised nonparametric models: these adapt their complexity based on the data and do not assume a fixed number of parameters. Decision trees and k-nearest neighbors (KNN) are examples. They can capture more complex relationships without a predefined form.</li><li>Supervised discriminative models: focus on modeling the boundary between classes or predicting the output directly from input variables. Most supervised learning models, including support vector machines and deep learning classification models, fall into this category.</li><li>Supervised generative models: though less common, there are instances where supervised learning approaches are used to build generative models. For example, a Conditional Generative Adversarial Network (CGAN) can be trained with labeled data to generate new data samples conditioned on specific labels.</li><li>Unsupervised parametric models: these models, such as Gaussian Mixture Models (GMM), use unlabeled data to learn a fixed number of parameters that best capture the underlying distribution of the data.</li><li>Unsupervised nonparametric models: these include models like DBSCAN for clustering, which adapts to the data’s complexity without a predefined number of parameters or model structure.</li><li>Unsupervised discriminative models: discriminative approaches are less common in purely unsupervised learning since there are no labels to discriminate between. However, techniques like clustering can be seen as trying to discriminate between different groups in the data without prior labels.</li><li>Unsupervised generative models: these are common and include models like Autoencoders and Generative Adversarial Networks (GANs) that learn to generate new data points that mimic the distribution of the input data, without requiring labels.</li><li>Semi-supervised learning: combines a small amount of labeled data with a large amount of unlabeled data during training. This approach can leverage both the discriminative power of labeled data and the generative capabilities to understand the data distribution from the unlabeled data.</li><li>Self-supervised learning: a form of unsupervised learning where the data itself provides supervision. This can be thought of as a creative combination where models learn to predict part of the data from other parts, effectively creating labels from the data itself.</li></ul><h4>Some probability theory</h4><p>Let’s define supervised learning a little bit more precisely. We’re going to assume that during training we are given a dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*qfVRFLT1_SXz91gJpSAsFQ.png" /><figcaption>Training set consisting of tuples; the<strong> y’s </strong>are the true labels corresponding to the <strong>x’s.</strong></figcaption></figure><p>For example, if we wanted to solve an image classification problem we would collect some pictures of dogs, cats and giraffes and then we would have humans go through each of those pictures and label them with their true label. We would use this as training data to learn how to classify new pictures. So, the goal in supervised learning is to learn this function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*-7ZV2ROHZgjnAtRzFALY0Q.png" /><figcaption>We want to learn theta (θ, the parameters) so that this function closely approximates the true label <strong>y.</strong></figcaption></figure><p>However, there are a few questions we have to answer to actually instantiate a supervised learning method. One important starting point is that <strong>predicting probabilities often makes more sense than predicting discrete labels.</strong></p><ol><li>If we’re allowed to have probabilities, we can much better express what we think is really going on; we might be able to capture the fact that a 4 is likely to be a 4, but it also has a pretty high chance of being a 9. This uncertainty might be useful for making decisions.</li><li>If we’re allowed to have probabilities, the problem is going to be smoother: intuitively we can’t change a discrete label a tiny bit, it’s kind of all or nothing. However, the problem of finding the optimal θ is made easier by the fact that we can change those probabilities by a tiny amount and see if they change in a direction that is closer to what we want.</li></ol><p>So, given a training set instead of learning a function that maps x to y, now we’re going to learn a function that maps x to a distribution over y:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*T9kvT0cq1-rhVWHUge1NVg.png" /></figure><p>Now, we’re going to be taking our input, for example the picture of a dog, and outputting a distribution over its corresponding label y.</p><p><strong>Refresher on conditional probabilities</strong></p><p>A random variable is a mathematical function that assigns a real number to each possible outcome of a random experiment. The primary purpose of a random variable is to quantify the outcomes of a random process, allowing for the application of mathematical operations and analysis. Random variables are categorized into two main types: discrete random variables and continuous random variables.</p><ul><li>Discrete random variables: these variables take on a countable number of distinct values. Examples include the number of heads in a series of coin tosses or the number of cars passing through an intersection in a given time frame. The probability distribution of a discrete random variable is described by a probability mass function (PMF).</li><li>Continuous random variables: these variables can take on any value within a continuous range. An example might be the amount of rain that falls in a day or the time required for a computer to complete a task. The probability distribution of a continuous random variable is described by a probability density function (PDF).</li></ul><p>We have:</p><ul><li>The input x</li><li>The output y</li></ul><p>We can write the joint probability of x and y as p(x,y). <strong>Joint probability</strong> is a statistical measure that calculates the likelihood of two events occurring together and at the same point in time. In other words, joint probability is the probability of event Y occurring at the same time that event X occurs.</p><p>Joint probability should not be confused with conditional probability, which is the probability that one event will happen <em>given that</em> another action or event happens.</p><p>In fact, joint probability p(x, y) can be decomposed using the chain rule of probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*UG5zW15m33T6zhXiYWykGg.png" /></figure><p>The <strong>chain rule</strong> of probability, not to be confused with the chain rule of calculus, allows the calculation of any member of the joint distribution of a set of random variables using only conditional probabilities.</p><p>In fact, you could also rewrite the above equation by dividing both sides by p(x) to get the definition of conditional probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*IOQFg8sQFjkyDetEdF4OJQ.png" /></figure><p>So if you know p(x) and p(x, y), you could recover your conditional probability.</p><p><strong>Supervised learning</strong></p><p>We’ll focus on learning p(y|x). In order to do this, we will use the “machine learning method”, which is a three-step program. This way of decomposing learning problems is closely related to Marr’s levels of analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*S30PEAWARzvcJfWZ5ozr7w.png" /></figure><p>I’ll now list the three steps of the machine learning method with their corresponding Marr’s level.</p><p><strong>1 Define your loss function:</strong> how will you measure how good a particular model is? This question relates to the computational level of the pyramid. This level concerns itself with what the system does and, importantly, why it does it. It involves understanding the problem from a high-level, goal-oriented perspective, without yet considering how the solution will be implemented.</p><p><strong>2 Define your model class:</strong> how will you represent your program? This question relates to the middle of the pyramid: the algorithmic level. In other words, what is the structure that is going to carry on our optimization? This level describes the representation and algorithms used to transform the inputs into outputs. It bridges the gap between the computational theory and the physical implementation, detailing the procedures that execute the system’s goals.</p><p><strong>3 Pick an optimizer: </strong>how will you search through the model class to find the model that minimizes the loss function? This question relates to the implementation level of the pyramid. In computational systems, it relates to how the algorithms are executed, including the hardware and software specifics.</p><p>The reason that we draw these distinctions is that when we have these different levels of analysis it can help us compartmentalize our thinking and help us to build abstractions so that we can solve the problems in isolation.</p><p>We’ll start from the middle of the pyramid, thinking about our representation of the problem.</p><h4>1 How do we represent p(y|x)?</h4><p>For example, say that we have this input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/67/1*4FgvoAfZ1AEz0DWPFx5OQw.png" /></figure><p>And our goal is to map it to the probability that it is an integer between 0 and 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*PIZIPdlj5Ky_ADcVurmD5Q.png" /></figure><p><strong>A valid probability distribution consists of positive numbers that sum up to 1.</strong></p><p>Let’s look at a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*RpHLxBRCZGw8Laj3dcu5oQ.png" /></figure><p>In the above image, we say that <em>the probability that y is a dog (conditioned on x) is constructed as “x” transpose “θ dog”; the probability that y is a cat (conditioned on x) is constructed as “x” transpose “θ cat”; the parameters are defined by the concatenation of “θ dog” and “θ cat”.</em></p><p>However, this program does not output a valid probability distribution: in general p(y = dog) + p(y = cat) will not sum to 1 unless the θs are chosen very very carefully. Therefore, we’re violating our constraint.</p><p>Let’s address this problem: instead of having “x” transpose “θ dog” be equal to p(dog), we’re going to define it as equal to some function f dog(x); we thus have some intermediate function inside of our program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*gCnjiHtm4fcmSJwFKaZjvg.png" /><figcaption>Take outputs from f dog and f cat, run them through a softmax</figcaption></figure><p>The softmax is going to take in f dog and f cat and it’s going to force those numbers to all be positive and sum up to 1. In theory, it could be any bijective (one-to-one and onto) function, because you want a function that uses the inputs you give.</p><p>A function f from the domain to the range is bijective when (1) No element of the range is the image of more than one element in the domain (2) All elements in the range are used.</p><p>But apart from this condition, why is it that we can use lots of different functions that make those numbers positive and sum to 1?</p><p><strong>The choice of your function in machine learning is not meant to produce the right answer; you produce the right answer by choosing the right parameters. </strong>The function just needs to be general enough so that there exists a choice of θ that represents the right answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*4MvduiPNgQHeXtlBk-Hx3Q.png" /><figcaption>It takes all of its inputs. it exponentiates them and then it divides by their sum; in this example, we see the dog output.</figcaption></figure><p>In general, you might have n labels (not just a dog) and p (y|x) might be a vector with n elements, one element for every possible label:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Jdz5g8YC1_4RU22_PmVl8A.png" /></figure><p>You have some function f θ(x), which is a vector-valued function with n outputs that might not be positive and might not sum to one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*E3VgC6eUsOYrEUmNJ7nDmQ.png" /></figure><p>So the softmax takes care of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*TSuxZuU3SCZBM5BDwdsBJg.png" /></figure><p>Its sole job is to make the numbers positive and to make them sum to 1.</p><h4>2 How do we select our parameters θ?</h4><p>So far, we have our picture of a computer program that maps our inputs to our outputs; we’ve decided that our outputs should be probabilities and we’re going to use the softmax to produce those probabilities.</p><p>To start thinking about defining our loss function, let’s start with a with a more basic question: how is our dataset generated? If our dataset consists of pictures and their corresponding labels, the actual process that gave rise to those pictures was probably pretty complex, involving photons and people making decisions about what to photograph and so on.</p><p>When it comes to trying to model it, we can come up with a very crude model: we’re going to represent that as a random process; there exists some p(x) distribution over photographs and humans randomly sampling from p(x) when they take photographs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*3stbtoEzZSHVHyHy_L9fOg.png" /></figure><p>And the label “dog” is sampled from some distribution over labels, which is not completely random and depends on the photograph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*flnhzTxZh_PSG4Gc9PZ1dg.png" /></figure><p>By the chain rule of probability, we can compose these two and generate samples (x, y) from their joint distribution p(x,y):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*Qx-NUAic8umtoCkV4MI97Q.png" /></figure><p>Our dataset is sampled from this distribution and consists of many tuples (x, y), which are generated according to the distribution p (x, y).</p><p>To make this a little more formal, what is the probability of seeing a particular training set? We need to make an assumption about how different data points relate to one another. <strong>The assumption we’re going to make is that we are dealing with independent and identically distributed data.</strong></p><ul><li>Independent means that every (x, y) tuple is independent of every other (x, y) tuple, meaning that if you observe a cat for x1, this doesn’t change how likely you are to see a cat or a dog for x2</li><li>Identically distributed means that every (xi, yi) comes from the same distribution.</li></ul><p>If we have this assumption, we know we can write the probability p(D) of seeing a particular training set as a product over all i of p(xi, yi).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*Msg6M1JFoe7ymSxIFt8tcA.png" /></figure><p>Why? Because “independent” means that the joint p(D) is formed as a product of the marginals p(xi) and p(yi).</p><p>In other words, if you flip a coin twice, the probability of seeing heads on the second flip doesn’t depend on the probability of seeing heads on the first flip. So if you want to know the probability of getting heads twice in a row you just multiply the probability of heads on the first attempt by the probability of heads on the second attempt. And because it’s identically distributed that’s the same as just taking the probability of heads and squaring it.</p><p>We have a probability associated with our dataset. Since we’re learning p(y|x), we can decompose the above formula using the chain rule of probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*7_kp2Q_nP_aG3zdIiLP87g.png" /></figure><p>Now we have a probability associated with our dataset expressed as a product over all of our data points of p(xi) by p(yi|xi). What we are learning is pθ of (y|x). It is important to notice that this is the learned function, which depends on our parameters: this is a model of the true p(y|x). Of course, it’s not the real process by which labels get associated with images, it’s a model of that process. And we’re going to try to get that model to be as accurate as possible.</p><p><strong>A good model should make the data look probable: one θ is better than another θ if the corresponding p θ(y|x) makes the entire data set look more probable and increases p(D)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*dcYw_SuWo_3TQ4gnfFPBbQ.png" /></figure><p>However, the issue here is that we express this probability p(D) as a product of a bunch of other probabilities that are between 0 and 1: if you multiply millions of numbers that are between 0 and 1, you’re going to get something very very close to zero. Essentially, this objective is numerically challenging.</p><p>What we can do instead is we can take the logarithm of p(D). When you take the logarithm of a product, you get a sum of logarithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*ESjvTeovPXId-SWVsWXTAw.png" /></figure><p>But since p(xi) doesn’t depend on θ, we can just treat is a constant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*0MC--4Qx7RFo5YDP_4PzoA.png" /></figure><p><strong>We can equivalently say that our objective is a sum over all of our data points of the logarithm of p θ(yi|xi) plus some other stuff that does not depend on θ.</strong></p><p>We can formulate the problem of learning θ as our attempt to find the θ that maximizes the log p(D):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*hlTcsUEx5XcyFKOVJfqfPw.png" /><figcaption>This is called maximum likelihood estimation (MLE), because this log probability is the likelihood and we are choosing θ to maximize the likelihood</figcaption></figure><p>Often times, we will see this written as a minimization (this is just a convention):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*0epNMapoWMF7l9BENm7c8A.png" /><figcaption>This is also called the cross-entropy</figcaption></figure><p>We still want to maximize the log p(D), which is the same as saying that we want to minimize the negative log probability. So, this is our loss function, which quantifies how bad θ is.</p><p>There are other ways to quantify how bad θ is. For example, you could have a zero-one loss: it just says that you get a a loss of one if you got the wrong answer and you get a loss of zero if you got a right answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*Yo7vjjIyZxLLJnDzn9qU1Q.png" /></figure><p>If you’re doing a continuous regression problem, you might have a mean squared error loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*E3whlQ2tzgujHGZVDUPd2g.png" /></figure><p>If you’re predicting a continuous value number, you might want to be as close to that number as possible.</p><h4>3 How do we pick our optimizer?</h4><p>Now we have to figure out how to find the setting of θ that minimizes our loss function. One of the things that it helps to think about when imagining optimization algorithms is what’s called the loss landscape. You can think of the loss landscape as a plot of the loss function. L(θ) denotes the loss function.</p><p>Let’s say that θ is 2D: you could imagine a plot where the horizontal axes are θ1 and θ2. The vertical axis represents the function L(θ). Just from glancing at it you know where the best θ is: it’s right there at the bottom of that bowl.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*v-IC3sUjQO4Tf8WQaEqKVg.png" /></figure><p>We want to find the direction in which the loss function decreases and move our θ in that direction. A very general sketch of an algorithm would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*GJ9pp3EtdMRQl3C5SByYAw.png" /></figure><p>Find the direction v such that L(θ) decreases and then pick the new θ to be the old θ plus some rate α times v. α is some small constant that is also called the learning rate. Then, we repeat this process enough times and we’ll hopefully settle down at the minimum.</p><p>Interestingly, the direction of steepest descent is not actually always the best choice, but what all these methods will have in common is that they will all move in the direction where L(θ) decreases at least locally.</p><p>Mathematically speaking, we represent a direction as a vector with n entries that points in the direction where L(θ) will decrease. It is easier to visualize in 1D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*2DxIwHCCq5a6qkp7U_gnEQ.png" /></figure><p>If I’m located at a certain point, the slope of the function at that point tells me in which direction it decreases. If the slope is negative, the function decreases to the right; if the slope is positive, the function decreases to the left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*0dSGFmrO42xfjdiWlGb25A.png" /></figure><p>Just from looking at the slope, we can therefore tell which way to go to decrease the function and the same intuition applies in higher dimensions. In general, for each dimension we should go in the direction opposite to the slope along that dimension.</p><p>What is a slope? A slope is just a derivative. All we do is we just set the direction for every dimension to be the negative of the partial derivative of our function L with respect to that dimension of θ.</p><p>In 2D, V1 is then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*Hk-5IVTNhZB55eUNWT6FuQ.png" /></figure><p>V2 is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*UvqID4A9819wIzBcV0Z_lQ.png" /></figure><p>These are not the only directions in which θ decreases: in fact, there’s an entire half space of vectors that encodes directions in which θ decreases. So, these partial derivatives give you the direction of steepest decrease, but if you go a little to the left or to the right, θ will still decrease. Of course, if you go in the opposite direction, θ will increase. As long as you have a positive dot product with v, you will go in a direction where L(θ) decreases. This is to say that it’s not a unique degree structure: it’s the steepest one, which doesn’t necessarily mean it’s the best one.</p><p>A very useful concept for doing this is something called the gradient, whose symbol is ∇. The ∇ is a vector; every dimension of that vector is the partial derivative of our function with respect to the corresponding dimension of θ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*8e5g7hNVCCIOcSrWWafNkQ.png" /><figcaption>The gradient is formed by taking partial derivatives and stacking them up in a vector</figcaption></figure><p>Here’s a sketch of the gradient descent algorithm:</p><ol><li>Compute the gradient step</li><li>Set θ to be:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*TirYe75wrUm3skCdrMfZ3A.png" /></figure><p>We have therefore selected our optimizer.</p><h4><a href="https://www.youtube.com/watch?v=PBYWWM9We-0&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=8">Empirical risk minimization</a></h4><p>Some people, when doing supervised learning, say they are minimizing empirical risk.</p><p>Let’s think back to the zero-one loss, which assigns 0 to loss for a correct classification and 1 for an incorrect classification</p><p>You can think of risk as the probability that you will get it wrong. Think back to our generative process: someone takes a picture. This is a randomly sampled picture from the distribution of pictures. It has a label sampled from the true distribution of labels. Given that picture, what’s the probability we’ll get it right or wrong?</p><p>The probability you get it wrong is just the expected value of the zero-one loss. Generalizing to other losses, the risk is the expected value of that loss.</p><p>If we’re using the negative log likelihood, we could say the risk is the expected value under the true distribution over x and the true distribution over y of the loss that we’ll get for that x and y and our learned θ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*9oKE2vg20RQtQ5btpRhdEA.png" /></figure><p>The risk is what we want to minimize. However, we can’t calculate true risk, because we can’t get infinite samples. Instead, we’re given a dataset D. So what we can calculate is the empirical risk, which is a sample-based estimate of the true risk. You get this sample-based estimate by averaging your loss over all of your samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*IlES_ppde_bb98_t1on37w.png" /><figcaption>The empirical risk approximates the true risk</figcaption></figure><p>Is the empirical risk a good approximation of the true risk? There are two situations where we might have trouble.</p><ol><li><strong>Overfitting </strong>happens when the empirical risk is low, but the true risk is high. This means that your average loss on your training set is low, but the true expected value of your loss is not low.</li></ol><p>Say that I’m trying to fit this line and the dots correspond to my training data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*clKoF0NZZcvLDHRBBHPjOw.png" /><figcaption>Overfitting</figcaption></figure><p>A high degree polynomial would perfectly fit the dots and result in very low empirical risk, as it passes right through the points. However, its true risk is going to be quite high. This can happen (1) if the dataset is too small or (2) if the model is too powerful and has too many parameters</p><p>2. Underfitting happens when the empirical risk does match the true risk, but they are both high.</p><p>For example, the true function here is some kind of curve, but we chose to fit a line to it and the line is not a powerful enough fit to that curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*AEVIGgCRSAiWvqcv2IJ2tw.png" /><figcaption>Underfitting</figcaption></figure><p>This can happen (1) if the model has too few parameters or (2) if your optimizer is not configured well.</p><p>Let’s try to mathematically understand what overfitting and underfitting are. In order to do so, we’ll focus on regression — this means that you are predicting a continuous variable or a continuous distribution based on your input.</p><p>Regression is basically curve fitting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*xis8XN1bUbsABMHrz1tmKQ.png" /></figure><p>You have some continuous or discrete inputs, you have a continuous output and you want to predict that output. For example, you’re predicting how big the dog is, how much it weighs, how expensive the house is, and so on.</p><p>If we want to adopt a probabilistic approach, in order to do regression we need a probability distribution over a continuous value to output y. There are many probability distributions that we could use to represent real numbers, but a very simple choice is the normal or gaussian distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*RBtXIjb1Dss_gStcPdg9MQ.png" /></figure><p><strong>The normal distribution is defined by two parameters: a mean and a variance.</strong> But of course, we want to solve a prediction problem — we want to predict a distribution over y given x. In our case, we are going to have a conditional gaussian distribution; in other words, the mean and perhaps the variance of this gaussian distribution are themselves functions of x. The log probability of a normal distribution can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*2IuqYxrARU3FuoprC2ZMkw.png" /></figure><p>It looks like a big equation, but it really consists of three simple things:</p><ul><li><strong>The first term</strong> is just the difference between f θ(x) and y, but under a particular norm defined by sigma. <em>It’s asking how close the mean f θ(x) to the true label y.</em></li><li><strong>The second term</strong> (negative 1/2 log of the determinant of sigma) tries to get the variance to be lower. What it’s saying is: <em>if you can fit the the true y’s accurately, try to use a lower variance.</em></li><li><strong>The third term</strong> is a <em>constant </em>that does not depend on x or y</li></ul><p>If we don’t bother learning sigma and fix it to be the identity matrix, then the normal distribution reduces to the square of the difference between f θ(x) and y, plus some constant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*y6gLCgFulPhXGbp9xdSWkA.png" /></figure><p>Often times, when we talk about regression, the particular distribution that we choose is a normal distribution, but we choose sigma to be the identity and then the log of this normal distribution just corresponds to the square of the difference between f θ(x) and y.</p><p>After this simplification, it is the same as the mean squared error (MSE) loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*KSiq1IMb2zsLyEHATI81pA.png" /></figure><p>The MSE loss is also the log probability for a normal distribution with the covariance sigma set to identity. If you have a linear model, then minimizing the MSE loss just corresponds to conventional linear regression. The analysis in the present article will therefore be for MSE, but keep in mind that it could be extended to other losses.</p><p>Now, let’s try to understand overfitting and underfitting more formally. The question here is: <strong>how does the error change for different training sets?</strong></p><p>This question is justified by the fact that intuitively we’d like to do our analysis in such a way that we understand the overfitting or underfitting tendencies of our algorithm somewhat independently of which particular dataset it’s trained on — because with a given dataset we could get lucky or unlucky. We want to know, on average, for datasets sampled from a particular data distribution, will our algorithm produce the right answer or not?</p><p>Here’s why this question could be important. Let’s say that this black curve is our true function and these blue dots represent a particular training set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*LcB3-mmJeOfJt8Jlx1E8Yg.png" /></figure><p>When I fit my model to that training set, I get the orange curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*euCx6BOXfBJk4AVnmrWRlQ.png" /></figure><p>Here, the empirical risk low is because the orange curve goes straight through the blue circles. However, the true risk is high, because the orange curve is very different from the black curve. This is overfitting.</p><p>Now imagine that I have a different set of blue dots. I have the same true function, the learning problem didn’t change, the distribution over x and y didn’t change either. The only difference is that I have a different dataset sampled from the same distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*spGabp3bqpo2NbvgNBYyzA.png" /></figure><p>If you look at both the second and third datasets, these are some polynomial regressions you might get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*PHdekaeQI_Zwj69D8E0jiQ.png" /></figure><p>They’re all overfitting, they all have low empirical risk and high true risk, but critically all the orange curves are different from one another. This is a very important observation. <strong>When we are overfitting, we see that different training sets — even though they come from the same distribution — will lead to very different solutions</strong>. This is kind of inevitable, because in order to overfit we have to get low empirical risk (the orange curve has to go through the blue dots) and high true risk (it can’t match the black curve); so as we move the blue dots around, the orange curve has to be in different places. In summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*3avL-RcViClUWwrkwhzstg.png" /></figure><p>On the other hand, if you’re getting underfitting, your empirical risk is high and your true risk is high. You’re getting a fit that is not going to vary nearly as much between different training sets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*d1hmPC2n41Kovj8U4DWmYw.png" /></figure><p>In fact, if you aggregate all of these three datasets together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*h9rgmWxK0S15QQUgBQ6OIA.png" /></figure><p>The linear fit to this aggregated dataset will probably look pretty similar to the fits that it had to the individual datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*ru5-__R2pVEyXnv3QBDnVg.png" /></figure><p>If we’re getting underfitting, that means that our model is not powerful enough; it doesn’t have enough free parameters to fit our function accurately and it’s not utilizing all the information that’s present in the training set. So, as the training set changes, it’s not going to change very much because it’s not pulling out all the information</p><p>To recap, in overfitting:</p><p>(1) The training data is fitted very well (2) The true function is fitted poorly (3) The learned functions will look different each time</p><p>In underfitting:</p><p>(1) The training data is fitted poorly (2) The true function is fitted poorly (3) The learned function looks similar, even if we pull together all the datasets</p><p>Now let’s make this more mathematically precise. We’re going to write down the expected value of the error given a distribution over datasets. So, we’re not taking an expected value with respect to x or y, we’re going to be taking an expected value with respect to the dataset D. If we can write a probability of D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*vxK_G0hMSwik3GrUAHUSGg.png" /></figure><p>Then we can take an expected value of a function of D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*NaNkWnof9kjUWgaP1OCmqw.png" /></figure><p>What is the expected value of the error between fθ(x) and y?</p><p>fθ(x) here is trained on D, but D is a random variable. This is not an expression that measures the average error for a particular fθ(x), it’s actually measuring the expected error of your training algorithm. For every value of D, you get a different fθ(x): this is really a function of D. Now, D goes in your learning algorithm, produces a θ and then we’re going to look at the error of that.</p><p><strong>In other words, in expectation, if I give you infinitely many datasets and you train on each of those datasets separately, what will your error be on average? </strong>Of course, this is just a theoretical exercise: in practice, when we do machine learning, we only get one training set.</p><p>The above equation can also be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*XjGJcCM_CFxQ0aL7Y9gW3g.png" /></figure><p>F(x) is the true function; fD(x) is the function I get from training on D.</p><p>As you might know, the expected value of some function is just a sum over all the values of your random variable, of the probability of that value times the value of that function. In this case, the expected value is a sum over all possible datasets of the probability of that dataset times the squared difference between fD(x) and f(x).</p><p>We can then take this expected value of the error and we can break it up into two terms, assigning blame to those terms. We can blame one of them for overfitting and we can blame the other one for underfitting.</p><p>For a little bit of notational convenience, I’m going to use f bar (x) to denote the expected value of fD(x). Importantly, f bar (x) is the average over all possible functions you would get for all possible datasets weighted by the probability of those datasets</p><p>That’s not to say that fD(x) is what you would get if you had infinite data, because every individual fD(x) is still fitted to a particular finite size training set, but you’re averaging their predictions together.</p><p>Now, we’re going to take this equation for the expected error and, inside the square, we’re going to subtract f bar and add f bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*akAt1nTvA6PS0dwRNajgZg.png" /></figure><p>Then, I’ll put parentheses around the first two terms and parentheses around the third and fourth term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*5aQcTMiFjLI-Qigzk3mQCg.png" /></figure><p>Now I’m going to evaluate the square of this quantity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJDk8wMPxyhatv3uN0vnvw.jpeg" /></figure><p>The third term ends up cancelling out, because this term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*WYSOYXmcOjIWvTVpDIBXng.png" /></figure><p>Does not depend on D. Therefore, by linearity of expectation, we can take it out. Moreover, this term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*-75jXjeHa4zRBuqcJPxdXw.png" /></figure><p>Also ends up equalling 0, because f bar (x) denotes the expected value of fD(x); therefore, the expected value of fD(x) minus f bar (x) equals 0.</p><p>Now, we are left with the first two terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*h93Xb1lUXeZFRwcoy9jjRg.png" /></figure><p>The first term is the variance. Notice that this first term doesn’t actually have f(x) in it, so this is regardless of what the true function is; this is quantifying how much our prediction changes with the dataset. In other words, how much does fD (x) vary for different training sets?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*9ZD1-HKhzLBqeZ_lLhrsRA.png" /></figure><p>In the second term, we can remove the expectation altogether, as f bar (x) minus f(x) don’t depend on D. It’s just the squared difference between the average over all of your predictions (f bar (x)) and the true function f (f(x)). We call this the bias, technically the square of the bias. The bias essentially quantifies how far off is the average prediction you get from the true function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*Myl_Qu_vQCbdlETYS_XusA.png" /></figure><p>In this case, the bias is pretty high. This error doesn’t go away no matter how much data we have, as it is quantifying how under-parametrized we are.</p><p>The full error is just the variance plus the squared bias. These two terms thus account for overfitting and underfitting.</p><p>So, if the variance is too high, then you have too little data or too complex of a function class: <strong>overfitting</strong>. On the other hand, if the bias is too high, then you have an insufficiently complex function class: <strong>underfitting</strong>.</p><p>Once we recognize that our error consists of variance and bias, then we know that getting an algorithm that works well requires regulating the trade-off between bias and variance. It’s very important to understand which term is big and which term is small, because many of the troubleshooting techniques we have for reducing variance will actually increase bias and vice versa</p><h4>Regularization</h4><p>Let’s talk about how we can trade off bias and variance: a key idea of neural nets, is that they use models that are “too complex” — complex enough to fit all the noise in the data. One then needs to “regularize” them to make the models fit complex enough, but not too complex. The more complex the model, the better it fits the training data, but if it is too complex, it generalizes less well; it memorizes the training data but is less accurate on future test data.</p><p>Regularization is one of the strategies we have to reduce overfitting:</p><ol><li>Getting more data addresses variance. The more data you have, the less you will overfit and the less variance you will suffer from. Getting more data doesn’t generally improve bias.</li><li>You can change your model class. For example, you can take your 12th degree polynomial and change it to be a linear function; this will probably reduce variance and increase bias. But this is a very discrete choice. <strong>Ideally, we’d like something that more smoothly restricts the model class. </strong>We’d like to construct a continuous knob for complexity. This is where regularization comes in.</li><li>Averaging many different models (bagging)</li><li>Informally, regularization is something we add to the loss function, typically to reduce variance, although not always. <em>One of the easiest ways to understand regularization is through the Bayesian interpretation, which regards regularization as a prior belief about our parameters.</em></li></ol><p>The high level intuition for the Bayesian perspective is that, when we have high variance, it’s because the data doesn’t give us enough information to identify the parameters. If we only have five data points and we have a 12th degree polynomial, the function is underdetermined: there are many different 12th degree polynomials that fit those five data points really well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*HJQDnkeg9TxLWAjDIQoCpQ.png" /></figure><p>We therefore need to somehow provide a little bit more knowledge to the algorithm; as there’s not enough information in the data, we can provide some through the loss function. We need to answer the question: <strong>given the dataset D, what is the most likely parameter vector θ?</strong></p><p>In other words, this question relates to your knowledge about the domain. In this case, you might have reasons to believe that, for your problem, the third function is more likely to be a good choice. <strong>The Bayesian perspective then tries to frame the entire learning problem of how to get θ from D probabilistically.</strong></p><p>D is just a set of (xi,yi) tuples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*OgdfF5gCe-W6PnKr84YoOQ.png" /></figure><p>If you want the distribution over θ given D, you can just apply the definition of conditional probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*ceyPB10rtkvo1hnMYZ9Vpg.png" /><figcaption>Up to a constant, this is equivalent to p(θ,D).</figcaption></figure><p>By the chain rule of probability, we can factorize this as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*e0l5rf5kbPaSsW-duYCrzQ.png" /></figure><p>This should ring a bell. The probability of D given some θ, using the IID assumption, can be factorized as a product over all of your data points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*rtniigraLXVXDuTVVMQuDw.png" /></figure><p>What about p(θ)? This is our prior. This expresses how likely θ is a priori, before even seeing your training set.</p><p>For example, without even seeing your dataset D, if you believe that for your particular problem smoother functions are more likely, you might say the second function is a better candidate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*yrhRRcQm153luPgUits6Fg.png" /></figure><p>On the other hand, if you believe that spiky functions are more likely, the first function is a better candidate.</p><p>Let’s say we go with the second function. Based on this prior knowledge, how do we build a prior in such a way that the smooth function is made more likely? Before answering this question, notice we now have a different loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*DB0JG_YnkKcgqwxzgAUjoA.png" /></figure><p>The first part is exactly the negative log likelihood we are used to. Now, we simply subtract the prior from the negative log likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*fIjhkA7i1WZc9pm1poO0SA.png" /></figure><p>Again, we have to choose the prior — and this is a design choice that does not come from the data. It is our prior belief.</p><p>In other words, as polynomials with small coefficients don’t result in large spikes, what kind of distribution assigns higher probabilities to small numbers?</p><p>There’s a wide range of distributions we can choose from, but one very very simple choice is to use a normal distribution — which assigns most of the probability mass on small numbers, close to zero. How close? This is determined by the variance. The lower we choose variance to be, the less likely functions with spikes become.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*wKTQu_gc0zh6G5fXjevftQ.jpeg" /></figure><p>Here is the expression for the log probability of a normal distribution with a mean of zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*Ap1ICu2c1yGFr7I55B69Yg.png" /></figure><p>The second and the third terms don’t influence θ and we can thus disregard them and express them as a constant value. We can rewrite this prior like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*S37HnoTuIZaJ6mChL2cI8g.png" /></figure><p>Lambda is 1/2 times sigma squared, but we don’t care about its precise value as we’ll just keep it as a hyperparameter — we’ll have to select it in order for the algorithm to work well. Our new loss function is thus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*td-nIAGNAKVZs7X8o9lcfg.png" /></figure><p>This is the same objective we had before; all we’ve done is we added a quadratic penalty term to the Cross Entropy Loss Function L.</p><p>One common alternative choice is L1 (or “LASSO”) regularization, which adds a penalty equivalent to the absolute value of the magnitude of coefficients. In formula terms, it is expressed as the sum of the absolute values of the weights, multiplied by the regularization parameter. This can lead to sparse models where some feature weights are set to zero, effectively performing feature selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*pyRoqYxCKLQFo-STVABhdw.png" /></figure><p>This also favours small numbers, but it has constant slope (unlike the squared function, which has increasing slope): it encourages as many entries as possible in the vector θ to be zero — in other words, it encourages sparse solutions.</p><p>Unlike L1, L2 regularization adds a penalty equivalent to the square of the magnitude of coefficients. This tends to spread the error among all the terms</p><p>We are now going to take a look at a geometric interpretation of L1 and L2 regularization terms in the parameter space of a machine learning model. Specifically, investigating the effect of these regularization terms on the optimization of a quadratic loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQA7t8URGMvL9HLRUQip7w.png" /></figure><p><strong>L1 Regularization</strong> (also known as the Lasso): the contour lines represent levels of the loss function, with the center being the point of minimum loss without regularization. The diamond shape represents the L1 norm (or the ‘L1 ball’), which is the set of points where the sum of the absolute values of the parameters is constant. The corners of the L1 ball are along the axes, and the optimization process tends to converge to these corners. This is due to the shape of the L1 norm, which imposes a higher penalty for non-zero values. As a result, L1 regularization encourages sparsity in the model parameters, meaning that some weights will be driven to zero, effectively performing feature selection.</p><p><strong>L2 Regularization</strong> (also known as Ridge Regression): the circle represents the L2 norm (or the ‘L2 ball’), which is the set of points where the sum of the squares of the parameters is constant. Unlike the L1 norm, the L2 norm does not have sharp corners and is rotationally symmetric. Therefore, the optimization process that includes L2 regularization tends to have solutions where the parameters are non-zero but small in magnitude, leading to weight decay. The L2 norm does not naturally encourage sparsity, but rather distributes the weight values more evenly across the parameters.</p><p><strong>Geometric Interpretation of Optimization</strong></p><p>The point where the contour lines of the quadratic loss function first touch the L1 or L2 ball represents the optimal point under the regularization constraint. This touching point is the solution to the optimization problem that minimizes the regularized loss function.</p><p>In (a), because of the corners, the optimization is likely to converge to a point where either ( w¹) or ( w²) is zero, which corresponds to the idea of L1 regularization pushing some weights to become exactly zero.</p><p>In (b), the touching point is more likely to have non-zero values for both (w¹ ) and (w²), consistent with L2 regularization penalizing large weights but not necessarily driving them to zero.</p><p>L1 Regularization is then useful when you want a sparse model, where some features are completely ignored by the model. This can be advantageous when you have a large number of features and believe that only a small subset is actually important. L2 Regularization is typically used when you believe that all features may be relevant but you want to penalize the extreme values that might be due to noise or outliers in the training data. The choice between L1 and L2 regularization can be informed by these geometric interpretations, as well as the specific nature of the data and the problem being solved. Importantly, for smaller weights also the input of the activation function of a hidden neuron becomes smaller. For values close to 0 many activation functions behave linearly. If every layer of the neural network is linear, then the whole network behaves somehow linearly.</p><p>Early stopping is another form of regularization used to avoid overfitting when training a learner with an iterative method, such as gradient descent. The method involves stopping the training process before the learner passes beyond a point of diminishing returns, i.e., when it begins to overfit the training data. This is typically done by monitoring the model’s performance on a validation set and stopping the training when the performance begins to worsen.</p><p>Data augmentation is a strategy used to increase the diversity of data available for training models without actually collecting new data. This is achieved by applying a series of transformations that produce believable variations of the input data. For example, in image processing, these transformations can be rotations, translations, flips, or adding noise. In natural language processing, this could involve synonym replacement or sentence shuffling. However, the approach of data augmentation through input transformations is not universally applicable to all machine learning problems. It’s especially challenging to apply in tasks that are sensitive to the input distribution, such as density estimation. In density estimation, the goal is to model the distribution that the data comes from, and artificially augmenting the data can change the underlying distribution you’re trying to model. Creating new samples in a density estimation context often means generating new data points that accurately reflect the true data distribution, which cannot be accomplished without effectively solving the density estimation problem itself. This is more complex than merely transforming existing data points, as it requires a deep understanding of the data distribution that is often achieved through sophisticated generative models like Generative Adversarial Networks (GANs) or Variational Autoencoders (VAEs). These models can learn to generate new data points by capturing the underlying distribution of the input data, but this process is significantly more complex than the transformations used for augmentation in classification tasks. For images, classical data augmentation techniques include geometric transformations such as rotations, scaling, cropping, and flips. These are straightforward to apply as they do not alter the semantic meaning of the image. More advanced techniques include the use of Generative Adversarial Networks (GANs) to create new, synthetic images that are plausible additions to the dataset. Adversarial examples are another sophisticated technique; they are crafted by making minor perturbations to the image data that cause the model to make a mistake. These examples are particularly useful for increasing the robustness of models to small changes that are imperceptible to humans.</p><p>In the acoustic domain, data augmentation is often achieved by manipulating the sound in ways that occur naturally in the real world. Pitch shifting alters the perceived pitch of the sound without changing the tempo, while time stretching changes the duration of the audio without altering the pitch. Dynamic range compression is used to reduce the volume of loud sounds or amplify quiet sounds, thus compressing or expanding the dynamic range of the audio signal. These augmentations help a model learn to recognize sounds invariant to these transformations, which is important for robust speech and sound recognition systems.</p><p>For text, augmentation techniques are designed to simulate the variability and noise found in natural language. Simple text transformations include switching, deleting, and inserting letters, which can mimic typing errors or orthographic variations. More complex augmentations might involve using GANs to generate new sentences or altering sentences by using synonyms for certain words or changing adjectives. These methods can help models to better understand the meaning of sentences and be less sensitive to variations in wording or small errors.</p><p>Injecting noise into the training data or into the model’s parameters during training can improve the robustness and generalization of the model. Noise can be added to inputs, weights, or even to the output targets. Adding noise to inputs can be a form of data augmentation. Adding noise to weights during training is similar to L2 regularization but is done at each iteration rather than as a penalty on the loss function. More specifically, when noise is added to the inputs (or outputs), it’s represented as Gaussian noise. The Gaussian distribution is defined by its mean and variance, where the mean is zero, and the variance is proportional to the squared weights. This results in an additive contribution to the squared error loss function of the model. By minimizing the squared error in the presence of noise, the network indirectly minimizes the effect of the noise, which also leads to the minimization of the squared weights. This is similar to the effect of L2 weight decay, which explicitly penalizes the square of the weights in the loss function. The variance of the noise is amplified by the squared weight before it propagates to the next layer. This means that larger weights will lead to a larger variance of noise in the subsequent layer, which the network must contend with during training. Specifically, in neural networks with linear output units directly connected to the inputs, the added noise with its amplified variance contributes directly to the output. Thus, the network learns to be robust to this variance by not relying too heavily on inputs with large weights (since these inputs will contribute more noise to the output). In summary, a) introducing noise to inputs can smooth out the learned function. The model becomes less sensitive to small fluctuations and learns to focus on the underlying patterns, improving its generalizability. This is a common technique used in training neural networks, particularly in Denoising Autoencoders b) Adding noise to the weights during training can encourage the network to develop more robust features. It is akin to finding a local minimum in a flat region of the loss surface, where small changes in weights do not significantly alter the output. This flat region implies that the network is less sensitive to the exact values of the weights, indicating better generalization. This method is less common than input noise but can be seen in techniques such as dropout, where weights are randomly set to zero during training c) Adding noise to the labels, often referred to as label smoothing, is a regularization strategy that prevents the model from becoming overconfident. The cross-entropy (CE) loss tends to push the network to be very confident about its predictions, leading to large logit values for the correct class and small ones for incorrect classes. By adding noise to the labels, you discourage this behavior. For example, in classification tasks, you might replace a small portion of the true labels with random labels, which prevents the model from assigning full certainty to the labels and thus leads to a more cautious model that is less likely to overfit.</p><p>In Multi-Task Learning, a neural network is trained on multiple tasks simultaneously, using a shared representation. This method can lead to improved learning efficiency and predictive accuracy compared to training separate models for each task. <strong>Task-Specific Parameters</strong> are unique to each task and are typically found in the upper layers of the neural network. They are optimized based on the data and objective of their respective tasks. For instance, in a neural network designed for both image classification and object localization, the final layers responsible for each specific output would be task-specific. These parameters only benefit from the examples of their task and are crucial for capturing the nuances and details necessary for that task’s success. <strong>Generic Parameters</strong> are utilized across all tasks the network is learning. They are often found in the lower levels of the neural network. Shared parameters benefit from the pooled data of all tasks, leading to more general representations that capture the commonalities across tasks. For example, early layers in a convolutional neural network (CNN) might act as generic parameters, learning features like edges and textures that are useful for various tasks such as image classification, object detection, and segmentation. By training on multiple tasks, the network’s generalization is improved. The shared parameters are exposed to a more varied set of data, helping the network to avoid overfitting to a single task. This can be thought of as each task providing “soft constraints” on the parameters, guiding them to good values that work well across tasks. Additional training examples from different tasks create a kind of regularization, putting more pressure on the parameters to find solutions that generalize well. In summary, Multi-Task Learning is an effective way to improve the performance of neural networks by training on related tasks that can share common features. This shared learning process can help networks to better generalize, reduce overfitting, and often results in more efficient learning as it requires fewer resources than training multiple independent networks.</p><p>Parameter Sharing involves using the same parameters (weights and biases) for more than one function in a network. This is a strategy to reduce the memory footprint of the model by having fewer unique parameters that need to be stored and updated during training. Parameter sharing is commonly used in convolutional neural networks (CNNs), where the same filter (consisting of weights) is applied across the entire input space (like an image), which is an effective way to detect features regardless of their position in the input. Parameter sharing enforces some parameters within the network to be exactly the same. There is no flexibility here; the same weight values are used in multiple places in the network. One of the main advantages of parameter sharing over tying is that it reduces the model’s memory requirements. Since the same weights are used in multiple parts of the network, only one set of these weights needs to be stored. This is particularly beneficial when dealing with large-scale inputs like high-resolution images, where the model may otherwise have an enormous number of parameters. Parameter sharing is particularly effective because it allows the model to learn and recognize features across different parts of the input. In a CNN, for instance, if a feature like an edge is useful for making a classification decision, it’s likely useful regardless of where it appears in the image. By sharing parameters, the model can detect this feature throughout the input space. This approach is also inherently a form of regularization, as it imposes a constraint on the model’s architecture that it must learn a generalizable pattern that works across different parts of the input.</p><p>Model ensembles act as a form of regularization. By combining the outputs of several models, ensembles can smooth out individual models’ quirks and idiosyncrasies. When individual models are combined, the ensemble often exhibits greater robustness to overfitting compared to single models. This is because while a single model may become overly complex and capture noise in the training data, an ensemble can average out these complexities and result in a simpler “average” model. For instance, bagging is an ensemble technique that trains multiple models on slightly different subsets of the training data. Each model may overfit its particular subset of the training data to some extent. However, because the overfitting is different for each model due to the different training data samples, when their predictions are combined, the overfitting can cancel out. This leads to an overall reduction in variance without an increase in bias, a hallmark of good regularization. The ensemble method also aligns with the principle of Occam&#39;s razor, which states that among competing hypotheses that predict equally well, the one with the fewest assumptions should be selected. In machine learning terms, this means a simpler model that generalizes well to new data is preferable to a more complex one.</p><p>CNNs are specialized kinds of neural networks that are designed to process data that has a grid-like topology, such as images. The defining feature of CNNs is their ability to automatically and adaptively learn spatial hierarchies of features from input data. This learning process is conducted through the convolution operation, which involves sliding filter kernels over the input data to produce a transformed feature map. These filter kernels are small but learnable weights that are applied across the entire span of the input data. In the context of image processing, these filters can be understood as feature detectors. For instance, one filter might learn to detect horizontal edges while another might detect vertical edges. The convolutional layer’s shift invariance is a key property that makes CNNs very effective for image recognition tasks. It means that once a feature is learned at one location, the CNN can recognize it in another location, making it adept at dealing with the spatial hierarchies in images. For example, in image classification tasks, whether a cat is in the top left or bottom right of an image, a CNN can use the same learned features to identify it as a cat, thanks to translation invariance. a) <strong>Local Connectivity</strong>: neurons in a convolutional layer are connected only to a small region of the input. This means that in the first layer, each neuron does not see the whole image but only a small portion of it. This approach takes advantage of the local spatial correlations present in images, where nearby pixels are more likely to be related to each other. This property reduces the number of parameters, making the network more efficient and less prone to overfitting b) <strong>Parameter Sharing</strong>: a single filter kernel, with its learnable weights, is applied to the entire input, which means the same weights are used to detect features throughout the input space. This shared weight scheme means that rather than learning a unique set of weights for every location in the input, the model learns only one set, which is used everywhere. This is efficient because it drastically reduces the number of parameters in the model. The idea is that if a feature is useful to compute at one spatial position, it should be useful at another. Together, these properties allow CNNs to generalize well to the visual world, making them ideal for tasks such as image and video recognition, image classification, and many tasks involving large data with spatial relationships. They achieve this by learning filters that are robust to the location of features in the input, thus capturing the essence of the input data while maintaining a manageable number of parameters.</p><p>Another regularizer that is widely used in deep neural networks to address overfitting is called dropout. Dropout works by randomly deactivating a subset of neurons in the network during training, thereby forcing the remaining active neurons to adapt and learn more robust features independently. This approach helps to make the network more robust to slight variations in the input data.</p><p>During the training of a neural network, dropout is applied at each training step. A binary mask is created where each neuron’s presence is determined by sampling from a Bernoulli distribution; each neuron has a probability (usually denoted as <em>p</em>) of being kept or dropped. Typically, this probability is a hyperparameter that can be adjusted, with a common choice being 0.5 for hidden units. This means there is an equal chance that any given neuron will be turned off during both the forward and backward pass.</p><p>The key idea behind dropout is that it simulates training a large number of neural networks with different architectures in parallel. By randomly dropping out neurons, the network’s architecture varies with each forward pass. This variability ensures that neurons do not become co-dependent on the presence of particular other neurons, which promotes the learning of robust features. When neurons are dropped, their contribution to the activation of downstream neurons is temporarily removed, and their weight updates are not applied during backpropagation. This effectively reduces the network’s capacity and complexity temporarily.</p><p>At test time, dropout is handled differently to preserve the computational efficiency while retaining the regularization effects observed during training. Instead of using stochastic dropout, the weights are scaled by the dropout probability <em>p</em>, an approach known as “dropout scaling.” This method is mathematically equivalent to averaging the outputs of all possible thinned networks, providing a way to integrate the benefits of multiple network architectures into a single model. Thus, dropout not only prevents overfitting but also enhances the model’s ability to generalize from the training data to unseen data.</p><p>In practical terms, dropout modifies both the forward and backward propagation algorithms during training. For each hidden layer, a binary mask is sampled, and the pre-activation is then computed as usual but is modified by the binary mask. During backpropagation, the gradients are also adjusted according to the mask, effectively zeroing out the gradients for the dropped neurons, preventing any gradient flow through them. This modification ensures that the learning process does not reinforce co-adaptation among neurons, fostering an environment where each neuron learns to function independently, thus enhancing the network’s generalization capabilities.</p><p>Incorporating dropout into a neural network training regimen can sometimes slow down the training process due to the dynamic changing of network architecture. However, the trade-off typically results in significantly better performance on new, unseen data, making dropout a valuable tool in the machine learning practitioner’s toolkit for effectively managing the overfitting challenge in complex neural network models.</p><p>This integration of dropout mechanisms not only mitigates overfitting but also aligns with the broader goal of building robust, generalizable models, effectively turning the theoretical understanding of dropout into practical, actionable insights for machine learning applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*vaAxtBvHIZb58mC2UXYveQ.png" /></figure><p><strong>Why many layers?</strong></p><p>The XOR problem is the problem of using a neural network to predict the outputs of XOR logic gates given two binary inputs. An XOR function should return a true value if the two inputs are not equal and a false value if they are equal. XOR is a classification problem and one for which the expected outputs are known in advance. A perceptron, which is a feed-forward network, is only capable of separating data points with a single line. This is unfortunate because the XOR inputs are not linearly separable. The solution to this problem is to expand beyond the single-layer architecture by adding an additional layer of units without any direct access to the outside world, known as a hidden layer. This kind of architecture is another feed-forward network known as a multilayer perceptron (MLP). In general, deep neural nets are often surprisingly powerful in learning complex functions without sacrificing generalization. And a core intuition behind deep learning is that deep nets derive their power through learning internal representations.</p><p>Deep learning is all about creating intermediate layers wherein each node in an intermediate layer represents the presence or absence of a different configuration of inputs. This way, if the input is a cat image, no individual pixel has to correlate with whether there’s a cat in the photo. Instead, the middle layer will attempt to identify different configurations of pixels that may or may not correlate with a cat (such as an ear, or cat eyes, or cat hair). The presence of many cat-like configurations will then give the final layer the information (correlation) it needs to correctly predict the presence or absence of a cat. You are going to train a neural network to learn patterns by observing all the individual datapoints and <em>searching for correlation</em>.</p><h4>How do we select hyperparameters?</h4><p>The idea is that we take the dataset and separate it into a training set and a validation set. Typically, the training set might be 80/90% of the dataset and is used to select (1) parameters θ (via optimization) and (2) those hyperparameters that affect optimization, like the learning rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*UuFjsVeIeNx1oZwkB5WK_w.png" /></figure><p>This is the training loss and it depends on D train:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*ZAYGh7i_RwIdp1mogpJpmg.png" /></figure><p>On the other hand, the validation set is not used for training; we will use it to make any other choices that are that are needed to design your method. Specifically, it is used to select (1) The model class (2) The hyperparameters of the regularizer (3) Which features to use. The validation loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*8qyK9RxUYbbvnb-tVhKj1Q.png" /></figure><p>This loss will allow us to diagnose overfitting and underfitting. Why? Because the training loss is your empirical risk, while the validation loss uses data that was not used for training and is thus an unbiased estimator of the true risk. By comparing these two losses you can determine if you’re overfitting or underfitting.</p><p>The machine learning workflow that you would typically use is:</p><p>1 Train your parameters θ on the training set.</p><p>If the training loss is not low enough, you are underfitting. To reduce underfitting, you can (1) decrease regularization (2) improve your optimizer.</p><p>If the training loss is low:</p><p>2 Look at the validation loss. If the validation loss is higher than the training set, you are probably overfitting. To reduce overfitting, you can (1) increase the amount of regularization (2) go out and get more data</p><p>Once you’ve done that, you can repeat the process.</p><p>In practice, we do something that is a bit more interleaved. We look at training loss and validation loss plotted on the same axis.</p><p>For example, this is stereotypical overfitting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*ncKVpMRjntQDx_1nun9J9Q.png" /></figure><p>Initially, both losses are going down, but later on the validation loss starts going up as the training loss drops further. Your learned function is fitting better and better those training points at the expense of actually deviating from the true function.</p><p>This is stereotypical underfitting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*h7RMM9BR1bS3vjmmwbDg3Q.png" /></figure><p>The validation loss and the training loss decrease at a similar rate, but they don’t decrease as much as we would like. That gap at the end is bias.</p><p>When looking at the overfitting case, one idea arises: would it make sense to hit the sweet spot before the validation error goes up and stop our optimization process? In fact, <em>this is called early stopping</em>. When the validation has been going up consistently for the past n iterations, you just rewind n steps and take whatever you had back then.</p><p>But does this mitigate all overfitting? No, because even if you can stop the optimizer at the right sweet spot, the validation error might never get as low as it could have if you had used appropriate regularization. So, early stopping is one way to combat overfitting, but it doesn’t solve all your problems.</p><p>Now, let’s say you followed this recipe: you don’t have underfitting, you don’t have overfitting, your losses are all good. How do you evaluate the final performance of your model?</p><p>We can’t really rely on the validation loss being unbiased anymore, because we used it to select (1) The model class (2) The hyperparameters of the regularizer (3) Which features to use. We can’t really rely on the training loss either, because we used it to select (1) parameters θ (via optimization) and (2) those hyperparameters that affect optimization, like the learning rate.</p><p>We could reserve another slice of the dataset for the final exam. We’ll call it the test set and we’ll use it only to report the final performance. Instead of partitioning our dataset into two parts, we’ll therefore partition it into three parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*968He5T1tQzn-tMK6sAmyg.png" /></figure><p>Hyperparameter tuning is a crucial step in the machine learning pipeline, as it involves finding the optimal configuration of the hyperparameters that govern the training process of a model. Given the potentially vast space of hyperparameter combinations and the significant impact these can have on model performance, this process can be both challenging and time-consuming.</p><p><strong>Grid search</strong> is a brute-force approach to hyperparameter tuning. This method involves defining a grid of hyperparameter values and evaluating every possible combination of these values. The primary advantage of grid search is its simplicity and the guarantee that, given enough time and computational resources, it can find the optimal combination within the defined grid. However, the main drawback is its inefficiency, especially when dealing with high-dimensional hyperparameter spaces, as the number of combinations grows exponentially with the number of hyperparameters. Example: if we have two hyperparameters, learning rate and batch size, with possible values [0.01,0.001][0.01,0.001] and [32,64,128][32,64,128] respectively, grid search would evaluate all 2×3=62×3=6 combinations.</p><p><strong>Random Search</strong> addresses some of the inefficiencies of grid search by randomly sampling the hyperparameter space. Instead of trying every combination, it selects a fixed number of combinations at random. This approach can be more efficient than grid search, especially when some hyperparameters are less important to the model’s performance. Random search has a chance of finding a good combination with far fewer evaluations, though it does not guarantee finding the optimal combination. Example: using the same hyperparameters as in the grid search example, if we limit the process to 3 evaluations, random search might evaluate the combinations (0.001,32)(0.001,32), (0.01,128)(0.01,128), and (0.001,64)(0.001,64) at random.</p><p><strong>Coordinate-wise Gradient Descent </strong>is a more targeted approach to hyperparameter tuning. Starting from a baseline set of hyperparameters, it iteratively adjusts one hyperparameter at a time while keeping the others fixed, searching for a reduction in validation error. This method can be efficient in practice, as it may quickly identify hyperparameters that have a significant impact on performance. However, its effectiveness is limited by the possibility of getting stuck in local minima. Example: starting with a learning rate of 0.01 and batch size of 64, this method might first vary the learning rate to find a minimum validation error, then adjust the batch size, iterating until no improvements are found.</p><p><strong>Bayesian Optimization / AutoML</strong> is a sophisticated technique that models the hyperparameter space using a probabilistic model (e.g., Gaussian processes) and uses this model to make intelligent decisions about which points in the space to evaluate next. This method can be particularly effective when evaluations are expensive, as it aims to find the optimal combination with as few evaluations as possible. AutoML frameworks often incorporate Bayesian optimization among other strategies to automate the hyperparameter tuning process. Example: after evaluating a few combinations, Bayesian optimization uses the performance of those combinations to predict which combination might perform best next, gradually focusing the search on the most promising regions of the hyperparameter space.</p><h4><a href="https://www.youtube.com/watch?v=RdoZWcXmXhk&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=11">Optimization in deep learning</a></h4><p>We’re going to talk about optimization algorithms. Let’s start with a recap of gradient descent.</p><p>We can formulate the problem of learning θ as our attempt to find the θ that maximizes the log p(D):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*hlTcsUEx5XcyFKOVJfqfPw.png" /><figcaption>This is called maximum likelihood estimation (MLE), because this log probability is the likelihood and we are choosing θ to maximize the likelihood</figcaption></figure><p>Often times, we will see this written as a minimization (this is just a convention):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*0epNMapoWMF7l9BENm7c8A.png" /><figcaption>This is also called the cross-entropy</figcaption></figure><p>We still want to maximize the the log p(D), which is the same as saying that we want to minimize the negative log probability. So, this is our loss function, which quantifies how bad θ is. To find the setting of θ that minimizes our loss function, we have to find the direction v such that L(θ) decreases and then pick the new θ to be the old θ plus some rate α times v. Then, we repeat this process enough times. In general, we set the direction for every dimension to be the negative of the partial derivative of our function L with respect to that dimension of θ.</p><p>We’ll discuss at length situations in which gradient descent works, situations in which it works poorly and how we can improve it. One type of picture that we’ll see a lot is a contour plot. The lines correspond to level set contours; so, for all θ values along one of these contours, the loss takes on the same value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*KwuOYhmEUozisCzwgXUW_Q.png" /></figure><p>We’ll visualize the optimization path for gradient descent with lines. The endpoint of each orange segment represents a value of θ on one of the iterations of gradient descent; the segment between those endpoints represents the step (which is the gradient direction multiplied by the learning rate).</p><p>Convex functions tend to optimize pretty well. Here’s a function in one dimension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*RVurtnQCl6cG1e-kqmalVA.png" /></figure><p>A function is convex if a line segment between any two points on that function lies entirely above the graph. In contrast, this function is not convex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*iVqCvGUn4gelrknlRRWuFw.png" /></figure><p>If I draw a line between the two points, it will intersect the graph. This function also happens to have two optima. In general, a function can be non-convex even if it has only one optimum. For example, this function has only one optimum, but, as it also has a plateau, if I draw a line between these two points it will intersect the graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*SVenSjLl7yANoJlaoaN-jg.png" /></figure><p>So, a function being convex implies that it has only one optimum, but a function being non-convex does not imply that it has more than one optimum.</p><p>It’s possible to prove that gradient descent on convex functions will find the global optimum in a number of iterations that is not too large. This doesn’t mean that gradient descent works well for all convex functions, because it doesn’t always move in the direction of the optimum. It will always take the steepest descent direction, but the steepest descent direction is not the one that goes directly towards the minimum point. For example, if we look at the first step we take from the starting point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*-m8cTYn2Nj0EqbqAgSaASQ.png" /></figure><p>We see that it is moving away from the optimum.</p><p>Imagine this kind of function. Each ellipse represents points with an equal value of the loss. The optimum is in the middle. The direction of steepest descent is always perpendicular to the tangent to the level set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*iAtQrH7B_gdX03c_W3hfTA.png" /></figure><p>At that point if we compute the steepest descent direction, we’ll go the other way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*B-5PWaEG74JxkweksB7ajQ.png" /></figure><p>And then the other way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*u_Ls3km8a5Mjpvykk_AqKg.png" /></figure><p>Eventually this will reach the optimum, but it might take quite a long time.</p><p>What about the loss surface of a neural network?</p><p>A neural network is a more complex function with many parameters and many layers of representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*12rv74KIsgvBUwnyEEdP_w.png" /></figure><p>It’s pretty hard to visualize the loss surface of a neural network, because neural networks have a very large number of parameters. Some networks’ loss is decent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*YnOw8sz4AU2dRIopF11q6w.png" /></figure><p>However, the loss generally looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*j5O4QU6iH7VePyq-vBoACA.png" /></figure><p>In general, neural networks’ loss landscapes are definitely not convex.</p><h4>What are some geographical features in a loss landscape that we should worry about?</h4><p>There are three features that are important to know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*QSkQosvueB-H4N-2M_Hyzg.png" /></figure><p>Local optima are the most obvious issue when it comes to non-convex loss landscapes. The issue is that you might have more than one point where the derivative is zero. At any of these local optima, the derivative will be zero, which means that there’s no improvement.</p><p>Local optima are very scary in principle, because gradient descent could converge to a solution that is arbitrarily worse than the global optimum and you have no way of knowing. A bit surprisingly, neural networks with many parameters definitely have local optima in their loss landscapes, but these optima tend to be not much worse than global optima.</p><p>You can visualize this in the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*5pTaf5V8BxVPUC92Lclf8w.png" /></figure><p>On the horizontal axis, we have the numerical value of the loss for the solution discovered by gradient descent. This is a histogram, so the vertical axis represents how many rounds of gradient descent, each starting from a different random location, achieved that loss. It’s kind of plotting the frequency of runs that got that loss. The different colours represent networks of different sizes; larger numbers here correspond to bigger networks with more parameters.</p><p>Roughly speaking, for the smallest networks shown in yellow there’s a wide distribution of different loss values. It’s still not that wide, all the numbers are between 0.08 and 0.10, but there there’s some variability, which means that the optimization is falling into local optima with a range of different loss values. But as the networks get bigger and bigger, the frequency of networks that achieve different losses becomes much tighter; for the red, the largest networks, you can see that there’s still some variability in the loss, but the solutions are clustered much more densely in the range of 0.072 and 0.078, roughly.</p><p><strong>What this means is that bigger nets do have local optima, but those local optima are all fairly similar to each other and they’re all pretty good.</strong></p><p>Let’s move to the second issue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*X7dgA-DcF0l0zzmsffZbzw.png" /></figure><p>We could imagine a loss landscape where we don’t have a local optimum, but we have a large region where the gradient of the loss is very small. If it weren’t for these plateaus, we could just use small learning rates and would be able to make slow and steady progress towards the optimum. But when these plateaus are really flat, a small learning rate might mean that it essentially takes you forever to get through the plateau. So you need learning rates that are large enough not to get stuck in a plateau like this.</p><p>Third issue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*4ngCECUfoco0jG_x4YMU0Q.png" /></figure><p>Saddle points are something that doesn’t really exist for one-dimensional functions, but for functions in higher dimensions they are fairly common. Intuitively, you can think of a saddle point as a local minimum along some dimensions, but a local maximum along other dimensions. At a saddle point, the partial derivative with respect to each dimension of the function is zero, but the function is increasing in some of the dimensions and decreasing in other dimensions.</p><p>This is where our intuition about functions from thinking about low dimensions is very misleading.</p><p><strong>What’s a critical point?</strong></p><p>A critical point is any point where the gradient is zero, meaning that all partial derivatives of the loss with respect to every dimension of θ are 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/1*qZKl1Bk7PNIROKMTanL0fg.png" /></figure><p>There are different types of critical points; for a given critical point, is that a maximum, minimum or saddle point? The way that you know is by looking at the second derivatives.</p><p>In 1D, if you’re at a critical point and the second derivative is positive, that means the the graph is sloping upwards. That means you have a local minimum. On the other hand, if the second derivative is negative, then that means that you’re at a local maximum. But in higher dimensions, you could have some second derivatives be positive and some be negative</p><p>In general, we can construct a matrix, called the hessian matrix. The hessian matrix is basically the second derivative equivalent of the gradient.</p><p>The gradient is a vector where every entry is the partial derivative with respect to the corresponding dimension of theta; the hessian is a matrix where every entry is the second derivative with respect to two entries in theta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*lBidCPtc1uWNwNiRQHacYA.png" /><figcaption>Hessian matrix</figcaption></figure><p>The hessian matrix at a saddle point is going to have diagonal entries that are 1 for some dimensions and -1 for others.</p><p>The point is a maximum or minimum only if all of the diagonal entries have the same sign. Otherwise, it’s a saddle point. Imagine what happens in higher dimensions: how often is it going to be the case that all of the 100’s of diagonal entries have the same sign? In higher dimensions, it seems pretty unlikely that every single diagonal entry will be positive or every single diagonal entry will be negative. <strong>So, most critical points in higher dimensions are saddle points.</strong></p><p><strong>Improvement directions</strong></p><p>Are there methods that accelerate gradient descent without requiring second derivatives (which would imply a very long runtime)?</p><p>1 Momentum is exactly what it sounds like. If we remember this picture from before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*GN-4qG1DAA7lRCcWoju5Vw.png" /></figure><p>Gradient descent is going to oscillate back and forth, but if we look at a couple of successive gradient updates, we’ll notice that they tend to point in opposite directions. It’s thus very tempting to think that if we can just average them together, we’re going to get exactly the direction we want.</p><p>The intuition is that if successive gradient steps point in different directions, we should cancel off the directions that disagree and just keep the directions that agree; on the other hand, if successive gradient steps point in similar directions, we should go faster in that direction.</p><p>The update rule we’re going to use with momentum is very much like gradient descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*33lRjmYiPlDDvTodsXqU3w.png" /></figure><p>The difference is that we also take the previous direction and multiply it by a decay factor between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*cuI-GF1_Vb8kcT4xmSH70w.png" /></figure><p>The velocity at time step <em>t</em> is updated by combining the current gradient ​ with the velocity of the previous time step​, scaled by a momentum factor, often set between 0.9 and 0.99. This factor determines how much of the previous update directions are retained. A higher <em>γ</em> retains more of the previous direction.</p><p>The parameters are then updated by subtracting this velocity from the current parameters.</p><p>If the previous direction and the new one point in opposite ways, they’ll cancel off. If they point in similar directions, they’ll actually add up together and go even faster in that direction. The advantages are that updates are smoothened as it reduces oscillations by aligning the updates to point more directly towards the minimum. Moreover, there is faster convergence, especially in flat regions of the error surface or when the gradient has a consistent direction. The disadvantages are that it has potential for overshooting: the momentum might carry the updates past the minimum, especially if <em>α</em> is too high.</p><p>Nesterov Momentum, also known as Nesterov Accelerated Gradient (NAG), is a refinement of the standard momentum method. It incorporates a “lookahead” by making a preliminary step based on the accumulated velocity, then computes the gradient and makes the correction. This anticipation allows for more informed updates, improving convergence.</p><p>The key difference from standard momentum is the gradient calculation, which is evaluated after the preliminary step based on the current momentum. This effectively means the gradient is computed not at the current parameters but at the lookahead parameters.</p><p>First, compute the look-ahead by temporarily updating the parameters using the previous velocity scaled by the momentum factor <em>γ</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*_SylF2Gj1XfU6wkoMJaGCQ.png" /></figure><p>Then, calculate the gradient at this look-ahead position, and update the velocity based on this gradient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*K0tWT-N-kmifJ4CtSQb2iQ.png" /></figure><p>Finally, update the parameters using the newly computed velocity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*35VHHO1JJiJPz1lkHR5OXA.png" /></figure><p>Advantages 1) By evaluating the gradient after the lookahead step, Nesterov Momentum can avoid potential pitfalls that standard momentum might fall into 2) Improved convergence: generally achieves faster convergence and better stability, especially in the context of overshooting.</p><p>Both Momentum and Nesterov Momentum are designed to overcome some of the limitations of SGD, such as its susceptibility to oscillations and slow convergence in certain areas of the error surface. By intelligently incorporating information from previous gradients, these methods achieve smoother and more rapid convergence towards the minimum of the loss function.</p><p>The next issue I’m going to talk about is the scale of the gradient. The sign of the gradient is important, because it tells us whether the gradient points left or right; but the magnitude, which tells us how far it goes along each dimension, is a lot less informative.</p><p>Even worse, the overall magnitude of the gradient can change drastically over the course of optimization, which can make learning rates hard to tune. The explanation is that the more f θ(x) differs from y, the larger the gradient will be. So, if initially f θ(x) is very different from y, then your gradients will be huge and when your gradients are that huge you’ll almost certainly overshoot the optimum and come out the other side. But as your function f θ(x) gets closer and closer to y, the gradient will become tiny and at that point you might be taking really small steps and you might want a better learning rate.</p><p>One idea that could help us mitigate this is to normalize out the magnitude of the gradient along each dimension. If you can somehow figure out roughly how big the gradient tends to be on average along each dimension and divide by that, then you’ll remove these annoying scaling factors.</p><p>RMSProp is one algorithm that does this. The idea is to estimate the per dimension magnitude of the gradient, on average:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*hl353f59T-a1Sa5U8BrqWw.png" /></figure><p>Every step, we are going to take the old value of Sk and multiply it by some factor β (a factor between 0 and 1). Then we’ll take 1-β and multiply it by the square of every entry in the gradient. This is roughly the squared length of each dimension.</p><p>When we update θ, we take a step in the direction of the gradient, but we divide it by the square root of Sk, which is its average squared length. So, each dimension is divided by roughly its magnitude:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*FD2It6casePFIvR7JvjU8w.png" /></figure><p>AdaGrad is a more theoretically principled version of RMSProp. With AdaGrad, we also estimate per-dimension magnitudes, but we estimate them cumulatively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*FgyuuRfxXHeNjVNbP48Kpw.png" /></figure><p>As you can see, it is precisely the same as RMSProp, but without β and 1-β. This implies that Sk is going to keep getting bigger and bigger.</p><p>So, how do AdaGrad and RMSProp compare?</p><p>AdaGrad has some very appealing guarantees for convex problems. However, for non-convex problems, the fact that we keep dividing by bigger and bigger Sk’s means that the learning rate decreases over time — and this can be a problem. AdaGrad only works if you find the optimum quickly, before Sk gets so big that your updates become tiny.</p><p>On the other hand, RMSProp tends to work a bit better than AdaGrad for non-convex problems, because unlike AdaGrad, it forgets. Over time, the fact that you’re multiplying Sk-1 by β means that the algorithm will forget the gradients that it’s seen a long time ago.</p><p>Adam combines momentum and RMSProp. We use momentum to accelerate gradient descent and we divide by a running average of the squared lengths to normalize out the lengths.</p><p>First step, similar to momentum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*ADeJvNwuqvYRB5dwz57wuA.png" /></figure><p>In a similar way to momentum, we’re accumulating our gradients as we go. You can think of mk (where “m” stands for mean) as a running average of the gradients.</p><p>Second step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*y56G-hbuq8xkUS9q6pHMHg.png" /></figure><p>vk is the second moment estimate: a running average as well, but of the squared lengths of the gradient.</p><p>Third step, as we initialize m0 and v0 to be zero, we want to prevent the steps we’re taking to be small at the beginning and big over time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*AhoAxBYbe9dd4EOTRZvh0w.png" /></figure><p>Fourth step, our update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*dgtJd48OPiCxnlTmctGDnA.png" /></figure><p>Adaptive learning rate methods like Adagrad, RMSProp, and Adam provide sophisticated mechanisms to adjust the learning rates of parameters throughout the training process. By doing so, they address the limitations of using a uniform learning rate across all features, leading to more efficient and effective convergence. Adam, in particular, has become very popular due to its robust performance across a wide range of neural network architectures.</p><p><strong>Stochastic optimization</strong></p><p>All the versions of gradient descent I’ve described so far are actually not suitable for use with deep learning. For example, negative log likelihood loss requires summing over all the data points in our training set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*EsmMj2-Fq_amzIzdZoxJHg.png" /></figure><p>However, in deep learning things tend to work best when the dataset is very large. Effectively optimizing a neural net might thus require millions of gradient steps and this would be pretty prohibitive.</p><p>One of the things we can recognize is that this sum is really a sample based estimate of an expected value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*Y28-dQ_Gnn7yWR3jA8xKMQ.png" /></figure><p>If you consider the expected value under the data distribution of the log probability of y given x, the sum that you’re actually computing for your loss is just a sample based estimate of that. And a sample based estimate of an expected value is unbiased for any number of samples. If you use fewer samples, you’re going to get a worse estimate, but it’s still an unbiased estimate.</p><p>One of the things we can do if we want gradient descent to be computationally faster is we can simply use fewer samples than the entire training set for each update. We could pick a subset of B samples and just average together those B samples — where B is much less than n:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*q23FeWM7Vod191I8_K1HhA.png" /></figure><p>Of course, if we just pick those samples once and we use them for the entire optimization process, that’s pretty wasteful because we’re not using most of our data. What we can do is we can pick a different subset of size B every single gradient step and this way our estimated gradient with a small number of samples will look like the true gradient — with some noise, because just by random chance every single gradient step will get a slightly different group of B samples.</p><p><strong>Stochastic gradient descent with mini-batches</strong></p><p>1 Sample a subset B of your entire training set D</p><p>2 Estimate an approximate gradient direction by averaging the gradient over all the points in your batch B. This is approximately going to be the gradient of your loss, but the reason it is not exactly the same is that you’re using many fewer points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*NW36Zg7W2f6uUMpSppzWeQ.png" /></figure><p>3 Use gradient descent with the approximate gradient. Of course, you can also use momentum, ADAM, etc.</p><p>Each iteration samples a different mini-batch. This is the ideal version of stochastic grading descent, but in practice you can actually do things a little more efficiently.</p><p>Sampling randomly every single step is pretty slow due to random memory access. If you have very complex data, it would be laid out sequentially in memory; so if you index into a random image every single time, then you’re doing a lot of random memory access which is going to trash your cache coherence. Instead, you can shuffle our dataset in advance, the same way you shuffle a deck of cards, and then index into that data set sequentially. Technically, this is not quite the same as regular gradient descent because you’re only shuffling once in the beginning, but the order with which you loop through the batches is random, so in practice this turns out to be pretty much just as good as the true stochastic grading descent and way cheaper computationally.</p><p><strong>Learning rates</strong></p><p>How can we adjust learning rates for these algorithms?</p><p>In this graph, the vertical axis is the training loss; the horizontal axis is the epoch — an epoch is just how many times you’ve gone through the whole dataset. With regular gradient descent, the number of epochs is equal to the number of optimization steps; with stochastic gradient descent, the number of epochs is the total size of your dataset divided by the size of your mini-batches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*UIsJOLJuMFV0ASCDdkQbEQ.png" /></figure><p>The red curve shows what you would expect to see for your training loss if you had a well-chosen learning rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*z7J0t7le_8sKr50XgG29WQ.png" /></figure><p>The green curve is descending a lot slower, so that means that our learning rate is probably lower than it should be. In deep learning, low learning rates can result in slow optimization and in convergence to worse final results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*idPRKUpBIIzCTjqDM9mKWg.png" /></figure><p>The yellow curve starts off really fast, but then it gets stuck, so that means that our learning rate is probably too high. When we’re going too fast, we’ll tend to go really quickly at first, but then you get stuck at a worse value.</p><p><strong>Learning rate decay</strong></p><p>One of the things you might be thinking at this point is: if high learning rates go quickly at first, but then get stuck, why don’t we start with a high learning rate and then switch to a lower learning rate?</p><p>Here’s a plot of a neural network, AlexNet, being trained on ImageNet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*-qRzSsu565YQNHQ_Pt5Klg.png" /></figure><p>It’s being trained with a learning rate decay schedule, where the learning rate is divided by 10 every once in a while. What you can see is that initially, with a learning rate of 0.01, accuracy improves rapidly, then it kind of plateaus. The learning rate gets decreased more and now your accuracy improves further and then it plateaus. Once again, the the learning rate is decreased and then accuracy improves further and plateaus. Eventually, you get close enough to the local optimum and then you stop improving. It is worth noticing that typically you don’t need learning rate decay with ADAM.</p><p><strong>Tuning stochastic gradient descent</strong></p><p>Hyperparameters to tune:</p><ul><li><strong>Batch size B</strong>. Usually, larger batches lead to less noisy gradients, which is safer but more expensive.</li><li><strong>The learning rate </strong>α<strong> </strong>is a somewhat tricky thing to choose. Generally, it’s better to use the biggest learning rate that works. You might want to decay it over time.</li><li>For momentum μ, good settings are 0.90 or 0.99, but you have to adjust it to fit your problem</li><li>ADAM parameters β1 and β2; usually, keep the defaults.</li></ul><p>How do you tune these hyperparameters? Technically, you want to tune these parameters on the training loss, because unlike regularization they’re not trying to give you better generalization to new points.</p><p>However, in practice, stochastic gradient descent hyperparameters are often also tuned on the validation set and it’s kind of an interesting choice. There’s a complex relationship between stochastic gradients and regularization; conventionally, we would separate out optimization from generalization. But recently there’s been quite a lot of research studying how great stochastic gradient descent itself can actually act as a sort of regularizer. The intuition is thus that if you start overfitting, you would expect the gradients to look very different for different batches, so you don’t want to average those out — you don’t want to get to the very bottom of your loss landscape. So, this is the crude intuition for why some people think that stochastic gradient has a desirable regularizing effect and therefore when you tune the hyperparameters of stochastic gradient descent you should actually be looking at the validation loss.</p><p><strong>Computation graphs for deep learning</strong></p><p>All machine learning algorithms are a program with some parameters. One of the ways that we can visualize that program is by drawing a graph that represents the flow of computation.</p><p>Here’s what a computation graph looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*DnO3hp2MwL8V1ZU1VGMCyA.png" /><figcaption>Computation graph for linear regression</figcaption></figure><p>This computation graph represents linear regression. We compute x1 times θ1 plus x2 times θ2; then we subtract y and square the difference and this gives us the mean squared error (MSE) loss. Generally, when we draw computation graphs for neural networks, we’re drawing the graph combined with a loss function.</p><p>Neural networks are generally much more complex and much larger computation graphs than the one that I have drawn above. Before we can draw computation graphs for neural networks, we need to talk about vectors and matrices; after we do that, we can design generic tools for computation graphs and use those tools to train many different kinds of neural networks with minimal additional engineering.</p><p>Let’s draw the same linear regression graph as before, but in a much simpler way, by using vectors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*ZbnE50qYaH2ruYmMjnFX_g.png" /><figcaption>Computation graph for linear regression</figcaption></figure><p>Now we have a node x that represents a vector of two entries x1 and x2; we also have a node θ that represents θ1 and θ2; after multiplying the two vectors, we subtract the label y from them and square the difference. This is exactly the same computation graph that I showed before, only written in a much more concise way by using vector notation.</p><p>On a similar note, we can look at this elaborate graph for logistic regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*88hajJUVWxLwVjVv3wmx0Q.jpeg" /><figcaption>Computation graph for logistic regression</figcaption></figure><p>And make this one simpler as well, by using matrices. We can write logistic regression in matrix notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*Fi_9znMB_12Su3H4dMzdKQ.png" /></figure><p>As some matrix θ times the vector x. And thus our computation graph becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*r5dJV6C4UL_DX7EIS_Kmpg.png" /></figure><p>We could draw logistic regression even more concisely. Notice that we have two types of variables in these calculations. We have data variables like x and y, which are the input and the target output; and we have parameters (θ), which usually affect one specific operation (although sometimes there is some parameter sharing). If we notice these properties we can summarize this combination graph a little more. As we know that θ is only going to affect what happens in one place, we can think of it as a parameter of that multiplication and fold it into the multiplication node. We could draw the same picture, but more concisely, by saying that x goes into a linear layer (linear because it’s a matrix-vector product), then it goes into the softmax and then the softmax goes into the loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*116FRdXP6iigJdppNhoZcg.png" /></figure><p>Now we have this heavily simplified computation graph diagram and we can compare it to other common ways to visualize neural networks.</p><p>A common way to draw a neural network diagram is to visualize variables in the network as boxes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*vCVC2l9sf044TCdbrf_Onw.png" /></figure><p>The first variable that everything starts with is the input x; then we have a linear layer, which by default has parameters; this linear layer transforms x into some intermediate representation that we will call z(1). z(1) is the result of applying the first linear layer — the superscript one denotes that it’s the first layer. Then we take this z(1) and we feed it into the softmax.</p><p>An even simplified drawing would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*G9HXkgA2tvvVaQIJ5Ip9hQ.png" /></figure><p>Here, we cut off the loss, because we know that a cross entropy loss always follows the softmax. We also remove the green trapezoids and instead just label the arrow. We also remove the parameters because a linear layers always has parameters. This is the kind of graph that you’ll see very often in research papers.</p><p><a href="https://www.youtube.com/watch?v=lKRatcD9hEg&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=14"><strong>Backpropagation step by step</strong></a></p><p>The expression for logistic regression is pretty simple and we could write the equation on a piece of paper. Then, we could just use the rules of calculus to derive the derivatives of that expression with respect to each of the parameters. We could do the same thing with neural networks, working out the derivatives with respect to every in every weight matrix and construct our gradient. But given that a neural network contains many functions, it could take a really long time to work out those derivatives. Plus, if you change your network, for example by adding another layer, you have to re-derive all of your derivatives and that’s going to take a really long time.</p><p>The following ideas for learning weights in neural networks touch upon some fundamental and exploratory strategies before converging on the most efficient and widely used method: backpropagation. Let’s go through each idea, its problems, and how backpropagation addresses these issues more effectively.</p><ul><li>Idea 1: This method involves randomly perturbing one weight at a time and observing if the change improves the performance of the neural network. If performance improves, the change is kept; otherwise, it’s discarded. However, this method is highly inefficient as it requires many passes over the dataset to evaluate the effect of changing a single weight. Given the potentially millions of weights in deep neural networks, this approach is computationally prohibitive. Moreover, as the learning progresses and the network starts to converge, finding beneficial weight perturbations becomes increasingly difficult, making fine-tuning near the end of training particularly challenging.</li><li>Idea 2: Instead of perturbing one weight at a time, this method suggests perturbing all weights simultaneously and correlating each weight’s change with its impact on performance. While this method attempts to overcome the inefficiency of serially perturbing weights, it introduces its own set of complexities. It’s challenging to implement and still requires extensive computation to determine the individual contributions of each weight perturbation to performance changes. Moreover, given the intertwined effects of weights in a neural network, isolating the impact of each weight’s change on overall performance is non-trivial and can lead to ambiguous interpretations.</li><li>Idea 3: This approach focuses on perturbing the activations instead of the weights, leveraging the fact that there are typically fewer activations to manipulate than weights. Although perturbing activations directly can be somewhat more efficient than perturbing weights, it still doesn’t offer a computationally viable path to training deep neural networks. The method remains indirect and inefficient for adjusting weights based on their contribution to the error. Plus, since this method does not adjust the weights directly, its capacity to fine-tune the network’s behavior and learn complex patterns is limited.</li></ul><p>What we would really like is an algorithm that can compute derivatives through neural networks automatically, without us having to work out all the calculus by hand. Then, we could implement any neural network we want, run this algorithm and get a gradient. This algorithm is called backpropagation. Backpropagation provides a more efficient and effective solution for learning weights in neural networks. It addresses the inefficiencies and challenges of the previous ideas by directly computing the gradient of the loss function with respect to each weight in the network.</p><p>As an aside, we need to recap how the chain rule of calculus (not to be confused with the chain rule of probability) works. Neural networks consist of compositions of many functions. Taking derivatives through compositions of functions is what the chain rule of calculus helps us figure out.</p><p>If you have the expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/1*4kmZHOxtkhQ-H__GHrxVhA.png" /></figure><p>That means you have an input x, you apply a function g to x, you get y and you apply another function f to y. Eventually, you get z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*XSxVit38W5xeXpLB1XUqIA.png" /></figure><p>Let’s say you would like to differentiate this whole expression with respect to x. The chain rule tells you that the derivative is given by the product of the derivative of g times the derivative of f:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*MzV1cDsPvhoErq1gCltmnQ.png" /></figure><p>The same exact expression applies to multivariate functions — we just have to be a little careful with the order, because the order in scalar multiplication is exchangeable, while the same is not true for matrix multiplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*WuWEaG_1KrZ-EvHxJ54vqw.png" /></figure><p>The same chain rule holds: dz/dy is a vector and dy/dx is a matrix.</p><p>Let’s look at this neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*Pyw51iEzX_LnKkvAOCehYg.png" /></figure><p>We could use the chain rule to write out, for example, the derivative of the loss with respect to W(2). That’s equal to the derivative of z(2) with respect to W(2) times the derivative of the loss with respect to z(2):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*31ED8sQJvgQvH3XIUZxXsA.png" /></figure><p>In the same way, we can write out the derivative with respect to W(1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*Gafgg75UkqWqhPIpoDFxhA.png" /></figure><p>Here’s how we could try to do things a little more efficiently. All these jacobians in the middle are going to be about nxn, but the very last jacobian is always going to be about nx1 — because the loss is always a scalar value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*3cNCWMvytRrSJdOFBjdIlw.png" /></figure><p>So, these products in the middle are pretty expensive, because they are going to be O(n³), while the last product is pretty cheap, because it’s always going to be roughly O(n²).</p><p>Here’s how we can use this intuition to actually build a much more efficient algorithm. The idea is that we’ll start on the right, so that we always keep our computations at O(n²). First, we compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*NuGYVQ9q2COk12OFUnTgEQ.png" /></figure><p>This is a matrix times a vector and it’s cheap to compute. We call it delta (δ). Now let’s update our derivatives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*QvA_fnRm7Iggt6ZYBxR_dA.png" /></figure><p>Once again, we start on the right. We compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*EFHFP3WiBNGJF_X4Wab7lQ.png" /></figure><p>This is a matrix times a vector and it’s cheap to compute. We call it gamma (γ). And finally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*iMdFsNCrqY7pv2ORRmpapQ.jpeg" /></figure><p>Again, this last product is cheap.</p><p>Based on this intuition, we can derive the classic backpropagation algorithm. Let’s say we have this network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*NQrF1dPS6aaz9m1SX0OHNA.png" /></figure><p>First, we’re going to do a forward pass and we’ll calculate every a(i) and z(i). Then, we’ll do the backward pass and this is what backpropagation refers to. We’ll first initialize our delta vector to be the derivative of the loss with respect to the last z. Then, we’ll go from the end of the network back to the front and for every function (both linear and non-linear layers) with input xf and parameters θf, we’re going to perform this operation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*QTmejlGwhwUuYa8sznMcxw.png" /></figure><p>And update delta this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*8BRA5YN2bBy468C350U0-g.jpeg" /></figure><p><strong>Problems with backpropagation</strong></p><ol><li>Backpropagation requires that all operations in the forward pass of a neural network be differentiable. This constraint limits the kinds of functions and operations that can be used within the network. While most common activation functions and operations used in neural networks are differentiable, this requirement can still restrict the architecture’s design, especially when exploring novel kinds of neural network models that might include non-differentiable components.</li><li>In deep networks, gradients propagated back through many layers can become very small, effectively preventing weights from updating in the initial layers. This makes it hard to train deep networks effectively, as the earlier layers learn very slowly, if at all. Conversely, gradients can also grow exponentially through layers, causing large updates to weights and leading to numerical instability. This issue is particularly prevalent in networks with recurrent structures.</li><li>Backpropagation’s inherently sequential process can be a bottleneck for parallel computation. While forward passes can easily be parallelized across batches of data, the backward pass requires sequential computation of gradients from the output layer back to the input layer. This characteristic limits the potential for exploiting parallel processing architectures to their fullest extent during training.</li><li>Backpropagation, as implemented in artificial neural networks, is criticized for its lack of biological plausibility. The brain’s neural networks do not perform explicit backpropagation of error signals. This discrepancy raises questions about whether backpropagation is the best model for learning in computational systems inspired by biological brains. Researchers are exploring alternative learning mechanisms that could be more closely aligned with biological processes.</li></ol><p><strong>Internal representations</strong></p><p>Earlier, we saw that deep neural nets are often surprisingly powerful in learning complex functions and that they derive their power through learning internal representations.</p><ol><li>Learning through gradient descent seems very alike to the evolution of a dynamic system. They both are described by a set of differential equations. Dynamical systems often have a “time-constant” which describes the rate of change, similar to the learning rate, only instead of time, gradient descent evolves through epochs. Saxe et al. (2013) showed that to analyze and to understanding the nonlinear learning dynamics of a deep LNN, we can use Singular Value Decomposition (SVD) to decompose the matrix of weights into orthogonal vectors, where orthogonality of the vectors would ensure their individuality (independence). This means we can break a deep wide LNN into multiple deep narrow LNN, so their activity is untangled from each other. A quick intro to SVD: any real-valued matix A can be decomposed to 3 matrices:</li></ol><p>A=UΣV⊤</p><p>where U is an orthogonal matrix, Σ is a diagonal matrix, and V is again an orthogonal matrix. The diagonal elements of Σ are called singular values.</p><p>2. Representational Similarity Analysis (RSA) is an approach that could help us peek inside to see how the net has structured its internal representations. The main idea is that the activity of hidden units (neurons) in the network must be similar when the network is presented with similar input. If we perform RSA in every training iteration, we may be able to see whether the narrow nets are learning the representations.</p><p><strong>Practical implementation</strong></p><p>Before we can train it with backpropagation and gradient descent, we need to answer a few questions about our neural network:</p><ul><li>How many layers should the network have?</li><li>How big are these layers?</li><li>What type of activation function should we use?</li></ul><p>With regard to activation functions, one particularly popular choice is something called the rectified linear unit or ReLU. The ReLU takes the previous activation, let’s say z(1), and it sets a(1) to be the max between zero and the corresponding entry of z(1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*AGapYVCoMqyRrFbGyLNd4Q.png" /></figure><p>It has a positive branch that is fully linear and then it has a negative branch that is flat. One might assume that it’s insufficiently non-linear, but actually it ends up working really well. It has a number of very appealing properties:</p><ul><li>It’s computationally extremely cheap to implement, which means that for very large neural networks it can speed them up considerably</li><li>Its derivatives are really simple and that also makes them computationally efficient and easier to work with</li></ul><p>Another detail that we have to talk about for implementing neural networks is the bias term. This is a classic linear layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*qp5xQKZGgzplNFOiGMwg-A.png" /></figure><p>But this layer has a major limitation. Let’s imagine that a(i) is a vector of zeros. In this case, the linear layer can never produce any output that is not zero, which means that you will always have zeros everywhere. This kind of neural network can never represent certain functions — it’s not a universal function approximator.</p><p>A solution to this is to add a bias vector, which turns linear layers into this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*sBqhWLqEVXnr_ulDaZ5O0w.png" /></figure><p>This is also called an affine layer. It turns out that if you have a neural network that has these kinds of layers and a non-linearity, like a sigmoid, as long as these layers are big enough you can approximate any function to an arbitrary level of precision. You cannot do that if you don’t have biases. So now the parameters of your neural net will consist of the weight matrices W1 and W2 and the bias vectors b1 and b2.</p><p>What else do we need to actually implement backpropagation? We need to be able to compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*6d4QVAdTMZKGLjF5PDhW2Q.png" /><figcaption>Parameters θf for every function f</figcaption></figure><p>And:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*yhZBxP3Bi0sXcpN1A95_GA.png" /><figcaption>Input xf for every function f</figcaption></figure><p><strong>PyTorch AutoGrad</strong></p><p>Deep learning frameworks such as PyTorch, JAX, and TensorFlow come with a very efficient and sophisticated set of algorithms, commonly known as Automatic Differentiation. AutoGrad is PyTorch’s automatic differentiation engine.</p><p>Everything starts with the forward propagation (pass). PyTorch tracks all the instructions, as we declare the variables and operations, and it builds the graph when we call the .backward() pass. PyTorch rebuilds the graph every time we iterate or change it (or simply put, PyTorch uses a dynamic graph).</p><p>For gradient descent, it is only required to have the gradients of cost function with respect to the variables we wish to learn. These variables are often called “learnable / trainable parameters” or simply “parameters” in PyTorch. In neural nets, weights and biases are often the learnable parameters.</p><p>In PyTorch, to indicate that a certain tensor contains learnable parameters, we can set the optional argument requires_grad to True. PyTorch will then track every operation using this tensor while configuring the computational graph. It is important to appreciate the fact that PyTorch can follow our operations as we arbitrarily go through classes and functions.</p><p>Here is where all the magic lies: in PyTorch, Tensor and Function are interconnected and build up an acyclic graph, that encodes a complete history of computation. Each variable has a grad_fn attribute that references a function that has created the Tensor (except for Tensors created by the user - these have None as grad_fn). At this point, we kick off the backward pass to calculate the gradients by calling .backward() on the tensor we wish to initiate the backpropagation from. Often, .backward() is called on the loss, which is the last node on the graph.</p><p><strong>Important Notes</strong></p><ul><li>Learnable parameters (i.e. reguires_grad tensors) are &quot;contagious&quot;. Let&#39;s look at a simple example: Y = W @ X, where X is the feature tensors and W is the weight tensor (learnable parameters, reguires_grad), the newly generated output tensor Y will be also reguires_grad. So any operation that is applied to Y will be part of the computational graph. Therefore, if we need to plot or store a tensor that is reguires_grad, we must first .detach() it from the graph by calling the .detach() method on that tensor.</li><li>.backward() accumulates gradients in the leaf nodes (i.e., the input nodes to the node of interest). We can call .zero_grad() on the loss or optimizer to zero out all .grad attributes (see autograd.backward for more).</li><li>Recall that in python we can access variables and associated methods with .method_name. You can use the command dir(my_object) to observe all variables and associated methods to your object, e.g., dir(simple_graph.w).</li></ul><h3>Convolutional networks, recurrent neural networks and transfomers</h3><h4><a href="https://www.youtube.com/watch?v=jNW1Hi7Yi4c&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=17">Convolutional networks</a></h4><p>Let’s say you have the picture of a cute puppy. You want to classify whether it’s a picture of a puppy, of a cat, of a hippopotamus or of a giraffe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*vGYG1ZPsJmKMcPbzyGCb_Q.png" /></figure><p>You could train a fully connected network to solve this task:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*39xw8P27QF0v98xfEvvOSQ.png" /></figure><p>However, there are at least two problems:</p><p><strong>1 Computationally intractable</strong></p><p>If we look at the first linear layer in such a network, we see it reads in an image and produces the first vector of activations. The number of weights in this linear layer is going to be equal to the number of activations in the first hidden layer z(1) times the number of numerical values in the entire image. For every pixel in the image and for every colour channel, we need a number of weights equal to the number of outputs.</p><p>Let’s say:</p><ul><li>This image is 128x128x3 (49.152 numbers)</li><li>Our first hidden layer has 64 dimensions, which is actually a pretty small hidden layer</li></ul><p>Even then, the total number of parameters in this first weight vector will be 64 times 49.152, which is over 3 million:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*FvEMCXm2r61v3KItJ9Y7kQ.png" /></figure><p>That’s just in the very first layer for this tiny 64-dimensional hidden layer.</p><p><strong>2 Not robust to shifts</strong></p><p>If the photograph of the puppy is shifted to the left or to the right by even a single pixel, it’ll look totally different to the network.</p><p><strong>An idea</strong></p><p>A lot of the visual features that we care about are, in some sense, local. If we wanted to recognize that this is a picture of a puppy, first we would extract edges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*_9NE1FgYvGL5bXd6ZZbg9A.png" /></figure><p>And then we would extract some local regions like ears and noses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*hAq_dmd9ue_aPWwPVO4YEg.png" /></figure><blockquote><strong><em>The interesting thing about these properties is that they’re all local features: to determine if there’s an edge in a particular location, you only need to look at nearby pixels.</em></strong></blockquote><p>We can use this observation to design a type of neural network that can get away with having many fewer parameters, by first doing local operations and then performing global operations only when the amount of information has been reduced to a much more manageable level. Convolutional Neural Networks are simply neural networks that use convolution in place of general matrix multiplication in at least one of their layers</p><p><strong>Convolution</strong></p><p>We will build a small detector for edges and will apply it to every region in the image — because the way you recognize an edge in an image doesn’t change depending on where you’re looking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*YzbtWZSQqtz0_BjYnuGiTw.png" /></figure><ul><li>Our small detector will be called filter (or kernel). This is a small matrix of numbers that are learned during the training process. Filters are designed to detect specific types of features in the image, such as edges, corners, or textures. Each filter in a convolutional layer is responsible for creating a feature map that emphasizes the presence of specific visual features in the input image.</li><li>It will have the same depth as that of the input image (3 colour channels, in this case). The filter depth is matched to the depth of the input image. For a color image with three color channels (Red, Green, Blue), the filter will also have a depth of three. This ensures that the filter can apply transformations that consider the full color information of the image.</li><li>Since there are 64 features, we will stack 64 filters together for every 3x3x3 region. Here I drew only four:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*e33L7BoIfaRz8kT2MncAYQ.png" /></figure><ul><li>We have 64 filters for each position in that input image, which produces a little vector of length 64 for each 3x3x3 region.</li><li>We will apply this 3x3x3 (27 numbers) filter to every patch in the image and compute 64 features. Now, 64 times 27 is only 1728, and not 3 millions. As the convolution filter slides along the input matrix for the layer, the convolution operation generates a feature map, which in turn contributes to the input of the next layer. Each feature map is essentially a representation of the input image but transformed to highlight or enhance certain features identified by the filter.</li><li>After that, we apply non-linearity to each of them, just like we did in the regular neural network</li><li>We now get another box, which has a depth of 64 and a width and height of also 128.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*-YscRgumFlO6ztP3mEpUeg.jpeg" /></figure><p>We have now turned our 128x128x3 image into a 128x128x64 map of activations. It’s as if every pixel has become a vector of 64 features. What do filters look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*tyR6ZuzHR4_yAdFQzHBvlQ.png" /></figure><p>You can imagine passing each of those filters over the image and for the corresponding filter the activation will be the degree to which that feature is present.</p><p>As an aside, one advantage of convolutional neural networks is that the network learns to optimize the filters through automated learning and they are therefore independent from prior knowledge and human intervention.</p><p>Convolution leverages three important ideas that can help improve a machine learning system: sparse interactions, parameter sharing and equivariant representations.</p><ol><li>Traditional neural network layers use matrix multiplication by a matrix of parameters with a separate parameter describing the interaction between each input unit and each output unit. This means that every output unit interacts with every input unit. Convolutional networks, however, typically have sparse interactions (also referred to as sparse connectivity or sparse weights). This is accomplished by making the kernel smaller than the input. For example, when processing an image, the input image might have thousands or millions of pixels, but we can detect small, meaningful features such as edges with kernels that occupy only tens or hundreds of pixels.</li><li>Parameter sharing refers to using the same parameter for more than one function in a model. In a traditional neural net, each element of the weight matrix is used exactly once when computing the output of a layer. It is multiplied by one element of the input and then never revisited. As a synonym for parameter sharing, one can say that a network has tied weights, because the value of the weight applied to one input is tied to the value of a weight applied elsewhere. In a convolutional neural net, each member of the kernel is used at every position of the input (except perhaps some of the boundary pixels, depending on the design decisions regarding the boundary). The parameter sharing used by the convolution operation means that rather than learning a separate set of parameters for every location, we learn only one set.</li><li>In the case of convolution, the particular form of parameter sharing causes the layer to have a property called equivariance to translation. To say a function is equivariant means that if the input changes, the output changes in the same way.</li></ol><p>But there’s a problem here: we haven’t made things any smaller. We’ve reduced the number of parameters, but our activations are still these giant maps that have the same resolution as the original image and potentially more depth because we might want more features than there were colour channels in the original image.</p><p><strong>Pooling</strong></p><p>To reduce the resolution of the layer, we’re going to take every 2x2x64 patch and turn it into a 1x1x64, by taking the maximum activation for each channel over each region. Why max? Intuitively, if the activations in this map represent the degree to which that feature is present, it makes sense that we would evaluate the presence of that feature in that region by taking the maximum activation. This makes it robust to small translation changes too: if the image moves by a small amount, the max in each region will probably remain the same anyway.</p><p>After the pooling, you can perform another convolution, apply another non-linearity and then perform another pooling. In general, a typical layer of a convolutional network consists of three stages.</p><ol><li>In the ﬁrst stage, the layer performs several convolutions in parallel to produce a set of linear activations.</li><li>In the second stage, each linear activation is run through a nonlinear activation function, such as the rectiﬁed linear activation function. This stage is sometimes called the detector stage.</li><li>In the third stage, we use a pooling function to modify the output of the layer further</li></ol><p><strong>Convolution and pooling</strong></p><p>Recall the concept of a prior probability distribution. This is a probability distribution over the parameters of a model that encodes our beliefs about what models are reasonable, before we have seen any data. Priors can be considered weak or strong depending on how concentrated the probability density in the prior is. A weak prior is a prior distribution with high entropy, such as a Gaussian distribution with high variance. Such a prior allows the data to move the parameters more or less freely. A strong prior has very low entropy, such as a Gaussian distribution with low variance. Such a prior plays a more active role in determining where the parameters end up. An inﬁnitely strong prior places zero probability on some parameters and says that these parameter values are completely forbidden, regardless of how much support the data give to those values. We can imagine a convolutional net as being similar to a fully connected net, but with an inﬁnitely strong prior over its weights. This inﬁnitely strong prior says that the weights for one hidden unit must be identical to the weights of its neighbor but shifted in space. The prior also says that the weights must be zero, except for in the small, spatially contiguous receptive ﬁeld assigned to that hidden unit. Overall, we can think of the use of convolution as introducing an inﬁnitely strong prior probability distribution over the parameters of a layer. This prior says that the function the layer should learn contains only local interactions and is equivariant to translation. Likewise, the use of pooling is an inﬁnitely strong prior that each unit should be invariant to small translations.</p><p><strong>What does a CNN look like?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*F3_G28DEh20Cn-3wL58Q6Q.png" /></figure><p>For example, this is LeNet, a network that was used for handwritten digit recognition. It consists of three convolutional layers with 5 × 5 kernels convolved with a stride of 1. The first convolution layer produces 6 feature maps of size 28 × 28, the second convolution layer produces 16 feature maps of size 10 × 10, and the third convolution layer produces 120 feature maps of size 1 × 1 (which are flattened into a 120-dimensional vector). The first two convolutional layers are followed by subsampling (aka pooling) layers, which perform a local averaging and subsampling of the feature map, thus reducing the resolution of the feature map and the sensitivity of the output to shifts and distortions in the input. A pooling kernel of size 2 × 2 is applied, reducing the feature map size to half its original size. Every feature map is followed by a tanh activation layer. This introduces nonlinearity into the network, increasing its expressive power because it can now model the output as a nonlinear combination of the inputs. If we did not have a nonlinear activation function, no matter how many layers we had, the neural network would still behave as a single-linear-layer network because the combination of multiple linear layers is just another linear layer. While the original LeNet paper used tanh as the activation function, several activation functions such as ReLU and sigmoid can also be used. The output feature map is passed through two fully connected (FC, aka linear) layers, which finally produce a 10-dimensional logits vector that represents the score for every class. The logits scores are converted into probabilities using the softmax layer. CrossEntropyLoss is used to compute the difference between the predicted probabilities and the ground truth.</p><p><strong>Implementing convolutional layers</strong></p><p>Imagine we want to implement a vertical edge detection kernel. It would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*d6dZKydeTA9DSEX1ZTdsFQ.png" /></figure><p>If we convolve this 3x3 kernel with this 6x6 image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*eISVzTphxv1cqd4ZnK1cpA.png" /></figure><p>What we’d get is a 4x4 output. The mathematics behind this is that if you have a nxn input convolved with a fxf filter, the output is going to be n-f+1 x n-f+1.</p><p>An important note: in machine learning, we do not bother flipping horizontally and vertically the kernel. However, by not doing this, we are technically doing cross-correlation rather than convolution.</p><p>At first the kernel would focus on the top 3x3 portion of the input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*333zyKEZdMYoP1zPYsR8Lg.png" /></figure><p>The output would be -5.</p><p><strong>Padding and edges</strong></p><p>What if, with your kernel, you go two steps to the left and you go off the end of the image?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*e_Nn-5qSX2mHLsQr_djE6w.png" /></figure><p>You have two options:</p><p><strong>1 Cut off the edges</strong></p><p>You disallow the filter from ever being evaluated at a point where some of the indices become negative or larger than the image width</p><p>If the input is 32x32x32 and your filter is 5x5x6, the output is going to be 28x28x6.</p><p>Here’s how we can think about it. We could imagine that the filter has a radius, which we can calculate by dividing by two its height minus one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*LOKjxx6-XPGzs-DhQoOPjg.png" /></figure><p>In our example, the radius is therefore 2. If that radius goes off the end of the image, then it’s invalid — this is why we cut off on each side (bottom, up, left, right) a number of locations that is equal to the radius. 32x32 will thus become 28x28.</p><p>However, when you cut off the edges like this, our activations shrink with every layer. Some people don’t like this, especially once these activation maps get pretty small towards the end of your network. Moreover, the filter would inevitably focus much less on information at the edges of the input. This is why we have padding.</p><p><strong>2 Zero padding</strong></p><p>With zero padding, you do evaluate the filter on the corners and the edges: any point that goes off the end of the image or activation map is replaced with a zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*HFHZ95m_r72ObL-3SY7oaw.png" /></figure><p>It’s important to remember to subtract the image mean first, because these zeros that you put in will be lower than any activation in the original image. Typically, you take the average pixel intensity and you subtract it from the pixel intensity at every location, so that the image is kind of centered.</p><p>One advantage of zero padding is that it is in some sense simpler: the size of the activation map is preserved and you don’t have to worry about things getting smaller.</p><p>In terms of dimensions, the output is going to be n+2p-f+1 x n+2p-f+1.</p><p><strong>Strided convolutions</strong></p><p>As we said, the standard structure at each layer consists of three steps:</p><p>1 Convolution<br>2 Activation function<br>3 Pooling</p><p>However, the first step can be computationally very expensive, because it doesn’t require many parameters but you’re repeating matrix multiplication many many times.</p><p>Here’s an idea to make it a little cheaper: what if you skip over some of the positions? Instead of evaluating the filter at every point in the input image, you could skip by an amount called stride.</p><p>Importantly, strided convolutions are not the same as pooling, because in pooling you do compute the activations at every location and then you take the max, whereas in strided convolution you skip some locations all together.</p><p>The dimension of the output is now going to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*yaRwvlju5SwgfirHk_el7Q.png" /></figure><p><strong>Examples of convolutional neural networks</strong></p><h3><strong>AlexNet</strong></h3><p><strong>AlexNet</strong> is a classic medium depth convolutional neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*cO4ekyk2CBqy-D0eyAhDCQ.png" /></figure><p>The reason why it’s drawn this way is that the net was implemented to run on two GPUs and was manually split into two parts. This doesn’t have any bearing on the functionality of the network.</p><ul><li>The input is a 224x224x3 image</li><li>The first convolutional layer is 11x11x96</li><li>These filters are applied with a stride of 4. You’ll reduce the size of the image by about a factor of four minus the edge effects due to the padding on the sides; that gives us an activation map that is 55x55x96</li><li>ReLU activation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*ri-TfxWVc0p6M6jQk_8a2g.png" /></figure><ul><li>3x3 max pooling layer, with a stride of 2. You get down to 27x27x96</li><li>Normalization layer. This is not widely used anymore.</li></ul><p>Pop quiz: how many parameters are there in the first convolutional layer? The number of parameters depends only on the filter and the filter is 11x11x96.</p><p>Remember that the size of the W matrices in each of those convolutional layers is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*1kEOPoHV1859Ei9RD2b4ig.png" /></figure><p>So you end up with 11x11x3x96, which amounts to 34.848 parameters. We are missing the number of parameters in the bias vector, which just depends on the number of outputs (96).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*c-_mqrUpllhwdm98-z1J6g.png" /></figure><p>These are quite a few parameters, but it’s still much much lower than what we would need if we had a fully connected layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*0jMwEN2lgQlMDTocOvS0kQ.jpeg" /></figure><p>Finally, we have fully connected layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*0gErWPV_cLpxBCYR2rGL8w.png" /></figure><p>You can see a few patterns:</p><ul><li>Pooling layers reduce the size of the activations</li><li>The number of features tends to go up as you go deeper: we’re trying to summarize all the information in the image with lower resolution activation maps that are deeper, which helps us represent more abstract features.</li><li>Once things get small enough, we flatten them and put them through a few fully connected layers to produce an answer</li></ul><p>Before the advent of deep learning, feature extraction in computer vision largely involved hand-engineered methods. These include Local Binary Patterns (LLC), Gabor Filters (GIF), and other filtering techniques that were designed to capture texture, shape, or edge information from images. These features were manually selected based on domain knowledge and were used for tasks like image classification using traditional classifiers (e.g., Support Vector Machines).</p><p>AlexNet was one of the first deep architectures that demonstrated the power of CNNs in large-scale image recognition tasks. While being a deeper and more complex architecture compared to its predecessors, it offered several innovations:</p><ul><li>ReLUs (Rectified Linear Units) for non-linear operations which helped in faster training by addressing the vanishing gradient problem.</li><li>Dropout as a regularization method to prevent overfitting in the fully connected layers.</li><li>Overlapping Pooling which reduced the size of the representation and prevented overfitting.</li></ul><p>A critical insight from the use of AlexNet was the transferability of features learned by CNNs. It was observed that features extracted from the initial layers of AlexNet could be repurposed for other visual recognition tasks beyond the ones they were originally trained for, without the need for retraining the entire network. This property was instrumental in advocating the use of CNNs, as it suggested that once a network is trained on a large and diverse dataset like ImageNet, its features can be generalized to other datasets and tasks (e.g., SAN dataset).</p><p>Further studies, such as those by the PTH group, systematically compared the performance of traditional hand-engineered features versus features extracted by CNNs across various tasks. These studies typically found that even without fine-tuning, CNN-extracted features outperformed traditional methods by significant margins. This not only confirmed the robustness and versatility of CNN features but also showed that additional enhancements, like data augmentation, could further improve performance.</p><p>In fine-grained recognition tasks, such as distinguishing between different species of birds, traditional methods relied heavily on localizing and extracting features from specific parts of an image and then modeling their spatial relationships using complex models like the deformable parts model. However, CNNs simplified this process significantly. By passing images through a CNN, a holistic representation that captures both local and global information could be obtained, leading to better performance. Moreover, integrating traditional designs (like part-based models) with CNN features could further enhance the accuracy, demonstrating a hybrid approach where deep learning complements traditional techniques.</p><p>But AlexNet is not used anymore and the best nets for processing visual inputs these days tend to be quite a bit deeper.</p><h3><strong>Deconvolutional networks</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*BBgJoaVmWB6rAIUEfKY4eQ.png" /></figure><p>Zeiger and Zellweger built upon the architecture similar to AlexNet, which includes multiple convolutional layers with pooling followed by fully-connected layers. The similarities to AlexNet likely provided a basis for direct comparisons in performance and interpretability between the original model and their modifications.</p><p><strong>Innovations in Network Design and Visualization</strong></p><p>Their key innovation lies in the methods for visualizing the activations within the CNN, offering a groundbreaking approach to what we now refer to as explainable AI (XAI) in deep learning. This approach involves mapping the activation maps from intermediate layers back to the input pixel space, enabling visualization of what each part of the network “pays attention to” when it sees an input image.</p><p>To achieve this, they implemented a reverse mapping process that involved:</p><ul><li>Unpooling: this step reverses the max pooling operation. During forward max pooling, the maximum value within a pooling window is retained and the rest discarded. To reverse this, the locations of these maxima (stored during the forward pass) are used to place the max values back in their original positions in the feature map, reconstructing the spatial structure prior to pooling.</li><li>Applying Non-Linearity: the same non-linear function used in the forward pass (e.g., ReLU) is applied again, ensuring that the activation remains non-negative and retains the model’s behavior.</li><li>Transposed Convolution: also known as deconvolution, this step involves using the transposed version of the convolutional filters to project the feature maps back to the higher resolution space of the previous layer.</li></ul><p><strong>Importance of Visualizing CNNs</strong></p><p>The ability to visualize what each layer of a CNN is learning is crucial for several reasons:</p><ul><li>It helps in identifying what features the network is focusing on, which can be critical for debugging and improving model performance.</li><li>In applications where decision-making needs to be interpretable (e.g., medical imaging, autonomous driving), understanding the model’s focus can build trust and provide legal and ethical justifications for the AI’s decisions.</li><li>This approach opens new avenues in neural network research, including better architectural designs and training methods, by providing insights into the model’s operation.</li></ul><p><strong>Broader Impact on AI</strong></p><p>The work of Zeiger and Zellweger spurred further research into XAI, encouraging more systematic and rigorous approaches to understand and explain AI models. This has led to a variety of techniques in the AI community, such as feature importance mapping, attention mechanisms, and other methods that aim to make AI decisions more transparent and understandable.</p><p><strong>Difficulties in Understanding CNN Internals</strong></p><ol><li>Complexity of Feature Hierarchies: CNNs, especially deep networks, learn hierarchies of features at multiple levels. The lower layers may capture simple features like edges and textures, while deeper layers interpret complex patterns that are often difficult to relate directly to human-understandable concepts.</li><li>High Dimensionality: CNNs can involve millions of parameters (weights and biases) distributed across various layers. This high dimensionality makes it challenging to intuitively grasp what each parameter is doing.</li><li>Black-Box Nature: By default, CNNs do not offer insights into their decision-making process. Without visualization tools or other forms of interpretative methods, they act as black boxes where only input-output relationships are observable.</li></ol><p><strong>Visualization Techniques</strong></p><p>Visualization is a powerful tool to mitigate the opacity of CNNs. Here are some prevalent methods:</p><ul><li>Feature Map Visualization: This involves displaying the activations of various filters across different layers of the network, helping to understand what features activate certain filters.</li><li>Class Model Visualization: This technique, often referred to as “activation maximization,” involves numerically generating an image that maximally activates a particular output neuron. This method can show what patterns or features the model associates most strongly with a given class.</li><li>Layer-wise Relevance Propagation (LRP): This method backpropagates the prediction output back to the input layer to reveal the relevance of each input pixel in making the prediction.</li></ul><p><strong>Adversarial Examples</strong></p><p>Adversarial examples are inputs to machine learning models that an attacker has intentionally designed to cause the model to make a mistake; they are often indistinguishable to humans from legitimate inputs. These examples exploit the ways that AI models, including CNNs, process input data, highlighting that they don’t perceive inputs in the same way a human would. The generation of adversarial examples involves:</p><ul><li>Adding Perturbations: Slight, often imperceptible changes to the input images can lead to dramatically different outputs. These perturbations are typically calculated by taking the gradient of the model’s loss function with respect to the input image, indicating the most effective changes to the input image to fool the model.</li><li>Investigative Purpose: Beyond their use in malicious attacks, adversarial examples can also help researchers understand the limitations and vulnerabilities of their models, guiding improvements in robustness.</li></ul><p><strong>Grad-CAM</strong>, short for Gradient-weighted Class Activation Mapping, is an interpretability technique that helps visualize which parts of an input image most influence the output classification decision of a Convolutional Neural Network (CNN). This method leverages the gradients of any target concept (like a class output) flowing into the final convolutional layer of a CNN to produce a coarse localization map highlighting the important regions in the image for predicting the concept. Let’s break down how Grad-CAM works in a detailed step-by-step process:</p><h3>Grad-CAM Procedure</h3><ol><li>Choose a class c for which you want to visualize the model’s decision making process</li><li>Process the input image through the CNN until the final convolutional layer to obtain the feature maps. Let’s denote the output feature maps by <em>A</em>, where each feature map is indexed by <em>k</em>. So, <em>A^k</em> refers to the <em>k</em>-th feature map.</li><li>Perform a backward pass with respect to the chosen class <em>c</em> from the softmax layer (just before applying softmax), back to the final convolutional layer. This step computes the gradients of the class score <em>y^c</em> (before softmax) with respect to the feature map activations.</li><li>For each feature map <em>k</em>, perform global average pooling (GAP) over the width and height dimensions (indexed by <em>i</em> and <em>j</em>) of the gradient matrix to compute the weights for the target class <em>c</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*RKcVYGupV_bonNdjuNyd5g.png" /></figure><p>where <em>Z</em> is the total number of elements in the feature map <em>A^k</em>. These weights​ are essentially capturing the importance of feature map <em>k</em> for the class <em>c</em></p><p>5. The final step is to compute the class activation map <em>Lc</em> for class <em>c</em>, which is a weighted sum of the forward activation maps, scaled by the weights computed from the gradients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*Jk2Z9RqWgTp-r8oZH-mOdw.png" /></figure><p>The ReLU function is applied to the linear combination of maps to only focus on the features that have a positive influence on the class of interest <em>c</em> — i.e., pixels where the intensity should be increased to increase <em>y^c</em>.</p><p>The resulting heatmap can be overlaid on the original image to show the regions most important for making the class decision. This visualization effectively highlights what the network is paying attention to. Grad-CAM can be used for debugging the decision-making process of CNNs, improving model architecture, searching for potential biases in the data, or simply improving the understanding of convolutional networks’ behavior. While originally developed for image classification tasks, Grad-CAM can be adapted for other tasks like object detection and segmentation, by targeting different layers or scores in the network. Grad-CAM provides a compelling balance between high-resolution visualization and class-discriminative localization, enabling clearer insights into CNN models without requiring architectural changes or retraining. This makes it a valuable tool for researchers and practitioners looking to interpret the behavior of their convolutional networks.</p><p>AlexNet, introduced in 2012, was one of the first deep architectures that used a relatively deep structure with 5 convolutional layers followed by 3 fully connected layers. It has approximately 60 million parameters. <strong>VGG</strong> (Visual Geometry Group), developed by Simonyan and Zisserman from Oxford, further deepened the architecture, especially with the VGG19 model which includes 16 convolutional layers and 3 fully connected layers, totaling around 130 million parameters. VGG was significant for its use of very small (3x3) convolutional kernels throughout the network.</p><p>One of VGG’s key features is its simplicity and uniformity; the network uses the same size convolution filters (3x3) and max pooling size (2x2), repeated through the layers. With the depth increase from AlexNet to VGG19, the network’s ability to capture more complex features improves, but it also leads to a massive increase in the number of parameters.</p><p>As the depth of the network increases, so does the number of parameters. This growth leads to several issues:<br> — Overfitting<br> — Computational Demand<br> — Training Difficulty</p><p>The realization that continually increasing depth and parameters was unsustainable led to the development of more efficient architectures.</p><p>More specifically, <strong>VGG </strong>is built trying to pursue standardization and modularization, which really helps when we have to build very deep networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*kAIQpMA3xBSfQ5U6a4MG1Q.png" /></figure><ul><li>The input is a 224x224x3 image and we hit it with stride 1 and zero padded convolutions: there is no resolution reduction. These are gigantic activation maps, but the filters are very small (3x3x64).</li><li>Non-linearity</li><li>2x2 max pooling layer to reduce resolution.</li><li>Two layers of convolution</li><li>Non-linearity</li><li>2x2 max pooling layer</li><li>Three layers of convolution</li><li>2x2 max pooling layer</li><li>Three layers of convolution</li></ul><p>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*FZhUZIU7pIRJmXskS9CG1g.png" /></figure><p>You can see the motifs here: we have two to three layers of convolutions that don’t reduce the resolution at all, interspersed with pooling layers that reduce the resolution by half. Each time we reduce the resolution by half we typically increase the number of filters and at some point it’s small enough that we could construct our first fully connected layer.</p><p>A few observations:</p><ul><li>More layers means more processing and that’s why we see these repeated blocks</li><li>Most memory is actually used at the beginning, because at the beginning we have these gigantic activation maps</li><li>The number of parameters is largest in the fully connected layers in which we flatten the activations into a giant vector</li></ul><p><strong>GoogLeNet</strong>, also known as Inception v1, marked a significant advancement in Convolutional Neural Network (CNN) architecture when it won the ImageNet challenge in 2014.</p><p>It introduced key innovations that enhanced both the efficiency and effectiveness of the network:</p><p>1. Despite its depth of 22 layers, GoogLeNet significantly cut down the number of parameters to approximately 4 million from the 60 million used in AlexNet. This reduction was achieved through the efficient use of convolutions, which minimized redundancy without sacrificing network capability.</p><p>2. This architecture incorporated parallel convolutional paths with varying kernel sizes within a single module. These paths allow the network to capture correlations across different scales within the feature maps, providing a richer and more nuanced understanding of the input data.</p><p>3. In deep neural networks, particularly those with many layers, a common challenge encountered during training is the “vanishing gradients” problem. This occurs when the gradients (which are derivatives of the loss function with respect to the network weights) become increasingly smaller as they are propagated back through the network during the backpropagation phase. As a result, the weights in the earlier layers of the network receive very small updates, if any, making it difficult to effectively train these layers. This problem can slow down the training process significantly and may lead to suboptimal performance. To mitigate this issue, GoogLeNet employs a clever technique involving auxiliary classifiers. Auxiliary classifiers are typically placed at points within the network where the depth starts to have a potential negative effect on the training dynamics due to vanishing gradients. These points are usually deep enough that meaningful features have already been extracted, but not so deep that gradients would have diminished entirely. During the training phase, these auxiliary classifiers perform a similar task to the main classifier at the end of the network. They take the intermediate features generated by the layers up to their point of attachment and make a separate prediction of the output. Each auxiliary classifier has its own loss function. When the network is trained, these classifiers contribute their own gradient signals in addition to those propagated back from the main classifier at the end of the network. Essentially, this means that rather than relying solely on the gradients derived from the final loss function (which can be very weak by the time they reach the early layers), the network also benefits from stronger, more direct gradients from these auxiliary classifiers. The additional gradient signals provided by the auxiliary classifiers help to reinforce the update signals in the earlier layers, ensuring that these layers learn more effectively. This counteracts the effects of the vanishing gradients, leading to a more stable and robust training process across all layers of the network. It’s important to note that these auxiliary classifiers are typically used only during the training phase to aid in convergence and learning. During the inference or testing phase, these auxiliary classifiers are usually removed, and only the main classifier’s output is used for making predictions.</p><p>4. A 1x1 convolution, despite its simple structure, acts as a linear transformation of the depth (i.e., the number of channels) of the feature map. Each 1x1 convolutional filter processes every pixel of the input feature map individually but considers all the channels at that pixel. Essentially, for each location in the input data, a 1x1 convolution provides a new value that is a weighted sum of the input values at that location across all channels. In the context of CNNs, increasing the number of channels (depth) increases the model&#39;s ability to represent information but also its computational complexity and number of parameters. 1x1 convolutions are used to reduce the number of channels in the feature maps. By applying a set of 1x1 convolutional filters that is fewer than the number of input channels, the network compresses or &quot;projects&quot; the data from a higher-dimensional space (more channels) to a lower-dimensional space (fewer channels) while still attempting to preserve important information. This reduction in dimensionality directly decreases the number of parameters in the network. For instance, reducing the channels before applying more expensive 3x3 or 5x5 convolutions significantly cuts down the computational load. Consider a layer in the network that transforms an input volume with a very high channel count using a larger convolutional filter (like 3x3); the computational cost can be prohibitive due to the multiplicative factor of the dimensions involved (input channels x output channels x filter height x filter width). By first reducing the channel dimensionality with 1x1 convolutions, subsequent layers require fewer computations. By integrating 1x1 convolutions, GoogLeNet can maintain a deep architecture—necessary for learning complex features—without an excessive increase in computational requirements. The strategic placement of these convolutions allows the network to efficiently manage resource usage while preserving or even enhancing the representational capacity of the network. This is because these layers enable more complex interactions between channels, potentially leading to better feature representation. In GoogLeNet, these 1x1 convolutions are not just used for reducing dimensionality; they also serve as a method for increasing non-linearity in the network without additional cost. Each 1x1 convolution is typically followed by a nonlinear activation function (like ReLU), which helps to introduce non-linear properties into the decision function, enhancing the network&#39;s ability to learn complex patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*bacbT1YpZoAp0lYwf8Zevg.png" /></figure><p>5. Batch Normalization (BN) was employed to stabilize and speed up the training of deep neural networks, including GoogLeNet. The benefits of batch normalization are particularly impactful. By normalizing the inputs across the mini-batches, BN allows for the use of higher learning rates. This accelerates the training process by mitigating the issue known as internal covariate shift, where the distribution of network activations changes during training. BN also introduces a slight regularization effect. This can sometimes reduce the need for other regularization methods like dropout, leading to simpler and more efficient network configurations. Models incorporating BN have been shown to achieve similar levels of performance as the original GoogLeNet but require fewer training steps, highlighting their increased training efficiency.</p><p>The principles behind GoogLeNet have significantly influenced the design of later CNN architectures. These include focusing on the efficiency of the network and improving performance without excessive computational costs. The inception modules and batch normalization techniques introduced by GoogLeNet are now foundational elements in designing deep networks that are both powerful and computationally manageable.</p><p><strong>Design Principles</strong></p><ul><li>Ensure that the reduction in size across the network happens gradually to avoid performance bottlenecks.</li><li>Processing high-dimensional representations locally within the network facilitates the learning of disentangled features, which can simplify the training process and enhance network performance.</li><li>It’s often possible to reduce the dimension of input data before spatial aggregation without significant loss of information, making the network leaner.</li><li>Distribute the computational resources judiciously across both the height and the width dimensions of the network to maximize efficiency and effectiveness.</li></ul><p>These strategies contribute to the robustness and adaptability of CNNs, making them suitable for a wide range of complex image recognition tasks.</p><p><strong>ResNet</strong></p><p>A common expectation in neural network design is that increasing the number of layers (depth) should improve performance. However, research from Microsoft indicated that deeper networks often performed worse than shallower ones due to optimization difficulties. This led to the innovative design of ResNet, which incorporates identity mapping to help preserve the performance across layers. ResNet uses pathways that act as identity mappings, which allow the network to bypass certain layers when necessary, effectively addressing the degradation problem typically seen in very deep networks.</p><p>ResNet was originally introduced with 152 layers, but since then people have used similar ideas to scale up networks. I will show a diagram of a heavily simplified 18-layer prototype: the full 152 layer version is analogous to this, except that everything is stretched out quite a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*R4UCKPpv__xjFcCcs1PlGg.png" /></figure><ul><li>We start off with one 7x7 convolution, which gets us down to a lower resolution. Then, we have these repeated blocks of 3x3 convolutions with resolution reduction in between them; the number of filters goes up by a factor of two as we go until you hit 512 and then you stay there.</li><li>We have generic blocks with many layers, interspersed with a few pooling operations.</li><li>The other notable feature of this model is that instead of having this giant fully connected layer at the end, we simply take our last convolutional response map and we average the feature vectors at every location</li><li>Then we have one linear layer going right into the softmax</li></ul><p>Let’s see why ResNet can train with such a large number of layers. These are some experiments that were conducted by the authors of the ResNet paper, studying the effect as we increase the number of layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*HmPmC7xe8H0RO9o5WxyMAw.jpeg" /></figure><p>On the left you can see their experiments with a standard convolutional network as you increase the number of layers from 20 to 32 to 44 to 56. What you can see here is that the error rate increases as the number of layers increases. What the the ResNet people figured out is that with a modification to the neural net architecture, you could reverse this trend and see accuracy increasing as the number of layers increases.</p><p><strong>What is the main idea?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*RGhizyp2O4sE_Rm8OpYUfA.png" /></figure><p>In the regular network on the left, you have your weight layers, which can be convolutions or fully connected and you apply them in series. On the other hand, for a residual network you take every group of two convolutions and you add the input to the first one to the output of the second one.</p><p>So if in the regular net you consider every group of two convolutions computing some function h(x), in the residual net that group of two convolutions will be computing h(x), where h(x) equals what happens in the regular network plus x. X gets to bypass those convolutions and gets added at the end. The intuition is that you compute a change to x instead of computing an entirely new x.</p><p>To understand this intuition, we have to reconsider why it’s so difficult to train very deep networks. The chain rule just looks like a multiplication of a bunch of jacobians; for some arbitrarily deep network, the derivative of the loss with respect to the weight matrix of the first layer will be a product of a huge number of jacobian matrices. Then at the end you multiply that number dL / dz(n):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*qzvIu05tmvO5jzkIMhuD2w.png" /></figure><p>These jacobian matrices can be all sorts of different things. Derivatives of non-linearities, derivatives of linear layers, derivatives of convolutions. If we simplify for a second and think about scalars, the problem with multiplying many numbers together is that there are two possible outcomes: if most of the numbers are less than one, we’re going to get zero, whereas if most of the numbers are larger than one, then we get infinity. There’s a very small set of cases where the answer is more interesting and that small set of cases is when all the numbers are close to one: the only time that you get a reasonable answer from multiplying together many scalars is if they’re all close to one.</p><p>By the way, this is why we prefer ReLUs instead of sigmoids; the derivative of a rectified linear unit is the indicator of whether the input is positive, which means that a large fraction of those derivatives are just 1.</p><p>For matrices, being close to one doesn’t mean that every entry is one, it means that the eigenvalues of the matrix need to be close to one.</p><p>If we look back at our image, with the residual layer dH/dx is given by dF/dx plus identity, because you’re just adding x. As long as the weights in the convolutional layers are not too big, you might hope that this dF/dx would not be too big either. At that point, this sum would be pretty close to identity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*IHr1n-QZN4zYMRi6mUtaAw.png" /></figure><h4>Key Innovations in ResNet</h4><ul><li>Skip connections carry forward the input to deeper layers without modification, adding it to the output of layers that have been skipped. This approach helps in mitigating the vanishing gradient problem by allowing gradients to flow through the network more directly and freely during backpropagation, which facilitates training deeper networks without performance degradation.</li><li>ResNet architectures typically employ layers of 3x3 convolutions repeatedly. The use of smaller kernels, as opposed to larger ones like 5x5 or 7x7, means that for a given receptive field, the layer can maintain a lower parameter count. Smaller kernels require fewer parameters and computations but can still capture complex features when stacked deeply, thanks to the network’s depth. This efficient use of parameters allows ResNet to deepen without a proportional increase in computational cost.</li><li>A smoother landscape, facilitated by skip connections, leads to more straightforward optimization paths, enhancing the training process’s effectiveness and efficiency.</li><li>In traditional CNN architectures, the final layers are often fully connected. ResNet can eliminate these in favor of Global Average Pooling layers, which take the average of each feature map from the previous layer. This method reduces the total number of parameters significantly and decreases the risk of overfitting, making the network more generalizable.</li><li>Batch Normalization also acts as a regularizer, reducing (or sometimes eliminating) the need for other regularization techniques like dropout or L2 regularization. By normalizing the inputs of each layer, it helps to maintain a more stable distribution of activations throughout the network, thus improving the training dynamics and sometimes allowing for higher learning rates.</li></ul><h4>Extensions and Variations of Network Design</h4><ol><li>DenseNet organizes its architecture into multiple dense blocks. Each block consists of layers where every layer receives the concatenated outputs of all previous layers within the block as its input [<a href="https://arxiv.org/abs/1608.06993">3</a>].</li><li>Feature Reuse: The input to each layer in a DenseNet includes the feature maps of all preceding layers. This architecture makes the network very parameter-efficient, reduces redundancy, and strengthens feature propagation throughout the network [<a href="https://amaarora.github.io/posts/2020-08-02-densenets.html">6</a>].</li><li>Improved Training: By reusing features, there is less need to relearn redundant feature maps. Each layer accesses all preceding layers’ outputs directly, leading to more diverse feature maps and generally more detailed learned features at multiple levels of abstraction [<a href="https://amaarora.github.io/posts/2020-08-02-densenets.html">6</a>].</li><li>Efficiency in Depth and Resolution: Dense connections allow the network to be deep yet efficient. Each layer contributes directly to the global state of the network, enabling effective training and feature use at different scales [<a href="https://arxiv.org/abs/1608.06993">3</a>].</li></ol><ul><li>Squeeze and Excitation Networks (SENet) introduce a sophisticated mechanism to enhance the representational capacity of convolutional neural networks by focusing on channel-wise feature recalibration. This architectural innovation is designed to improve network performance by adaptively adjusting channel-wise features in a learned manner.</li></ul><ol><li>Channel-wise Importance: SENet addresses the interdependencies between channels in a convolutional layer by focusing on the recalibration of channel outputs. This involves dynamically enhancing or suppressing features across different channels based on their relevance to the task at hand.</li><li>Squeeze and Excitation Block: At the heart of SENet is the squeeze and excitation block, which operates in two stages. <strong>Squeeze (Global Information Embedding).</strong> This stage aggregates the global spatial information of each channel into a single value. It is typically achieved by applying global average pooling across the spatial dimensions of the channel, resulting in a descriptor that serves as a summarized expression of the global distribution of features in the channel. <strong>Excitation (Adaptive Recalibration)</strong>. Following the squeeze operation, the excitation step uses these channel-wise statistics to produce a modulation signal. This signal is generated by a fully connected layer followed by a sigmoid activation function, which outputs a set of scalar coefficients between 0 and 1. These coefficients scale the feature maps channel-wise, effectively recalibrating the output of the convolutional layer.</li></ol><p>The recalibration process allows the network to emphasize more informative features while suppressing less useful ones. The application of a sigmoid function ensures that the recalibration factors are smoothly adjusted between 0 (full suppression) and 1 (full expression), providing a fine-grained control over how the features are highlighted or diminished.</p><p>This channel-wise recalibration mechanism leverages global contextual information, thereby enabling the network to make more informed decisions about which features are important for a given input. The result is a significant boost in the representational power of the network without the need for increasing depth or complexity.</p><p><strong>ConvNEXT</strong></p><p>The past decade has witnessed a continual evolution in convolutional neural network (ConvNet) architectures, with new models emerging approximately every one or two years, exploring various architectural designs. The late 2020s saw the introduction and adoption of vision transformers, representing a significant shift akin to the rise of transformers in natural language processing (NLP) since 2017. These transformers, inspired by non-visual transformer models, exhibit great scalability in image classification tasks. Unlike vanilla transformers, hierarchical vision transformers incorporate hierarchical structures, enhancing performance across various downstream vision tasks by restricting self-attention within local windows rather than globally. Recent communication conferences reveal a surge in transformer-titled papers, while convolution-based papers experience a decline, primarily due to the superior performance of hierarchical vision transformers. ConvNEXT is a novel ConvNet architecture inspired by transformers. Through meticulous experimentation and architectural modifications, ConvNEXT achieves comparable accuracy and scalability to hierarchical vision transformers, challenging conventional beliefs regarding the importance of convolution in computer vision.</p><p><strong>Regularization for CNNs</strong></p><p>Regularization techniques are fundamental in the training of Convolutional Neural Networks (CNNs) to prevent overfitting. Regularization methods help mitigate this by introducing some form of constraint or modification to the input or network architecture that promotes the generalization of the model. Below, I’ll detail some regularization techniques, explaining their mechanisms and applications within CNNs.</p><ol><li>CUTOUT</li></ol><p>CUTOUT is a simple, yet effective data augmentation technique for CNNs. It involves randomly removing (or “cutting out”) square regions of the input image during training. Specifically, you drop a 16×16 square in the input image with a randomly chosen center, replacing the pixels in this region with their mean value from the dataset. This technique forces the network to focus on less prominent features of the image, potentially reducing the reliance on specific features located in the cutout region. By doing so, CUTOUT encourages the model to generalize better, since it must make predictions without seeing parts of the image.</p><p>2. DropBlock</p><p>DropBlock is a structured form of dropout designed specifically for CNNs. Traditional dropout randomly deactivates individual neurons during training, which can be ineffective for spatially correlated data like images. DropBlock improves upon this by dropping contiguous regions (blocks) of the feature map. Notably, all channels in the selected block region are dropped, ensuring that the entire spatial structure is affected. The advantage of DropBlock over traditional dropout is that it maintains the structural integrity of the feature maps. By dropping whole regions, it prevents the network from depending too heavily on localized features, thus promoting spatial robustness and reducing overfitting. The authors noted that applying DropBlock across all channels uniformly tends to work better than doing it separately for each channel. This observation suggests that simultaneous regularization across all channels helps maintain the balance and dependency between them, enhancing the model’s ability to generalize across different spatial features.</p><p>3. CutMix</p><p>CutMix is another data augmentation technique that combines pairs of images and their labels in a way that introduces more robustness into the model. It works by:<br> — Sampling a mixing ratio λ uniformly from the interval (0, 1).<br> — Selecting a random image region and replacing it with a patch from another image.<br> — The labels are then mixed proportionally to the area of the patches from each image, calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*rC4WbBYQ-ZfBeA0GrEJWGA.png" /></figure><p>Where are yA and yB are the labels of the original and the patch image, respectively.</p><p>CutMix helps the model learn to generalize across different contexts by training it on a composite mixture of features from different images. This method not only brings diversity to the training data but also makes the model robust to occlusions and varying object sizes.</p><p>Consider a scenario where you mix an image of a dog with a bird. A portion of the dog image is replaced by a part of the bird image. The model then learns to associate features of both dogs and birds with the corresponding mixed labels, enhancing its ability to recognize and differentiate both even under partial occlusion or unusual contexts.</p><p>These regularization techniques are essential in complex visual tasks where CNNs tend to learn very nuanced and highly specific patterns that do not necessarily generalize well to new data. By implementing these techniques, researchers and practitioners can improve the robustness and accuracy of CNNs in real-world applications.</p><h3>Understanding Object Detection</h3><p>Object detection is a complex problem in computer vision that involves not only identifying objects within images but also predicting their precise locations. Unlike simple classification tasks where the output is a label, detection models output a bounding box and a label for each object in the image. This task is inherently more challenging due to the necessity of precise localization, which requires the model to understand and encode spatial hierarchies and object dimensions within the scene.</p><p>One of the primary challenges in object detection is the requirement for detailed annotation of training data. Each object in an image must be labeled with a bounding box, which specifies the coordinates of the object within the image. This process is significantly more labor-intensive and costly compared to labeling images for classification tasks.</p><p>Additionally, detection models need to handle a variety of object scales, poses, and occlusions, which can complicate the learning process. The models must also manage the vast number of potential object locations and scales, which can be computationally demanding.</p><p>Early object detection frameworks relied heavily on a technique known as Selective Search to generate high-quality region proposals where objects might be located. This method works by segmenting the image into a large number of initial regions and then recursively combining these regions based on similarity criteria such as color, texture, and size. The result is a reduced set of region proposals that are more likely to contain objects, dramatically decreasing the number of potential bounding boxes that the model needs to evaluate.</p><p>The integration of CNNs with region proposal methods marked a significant advancement in object detection. Initial approaches, such as the combination of Selective Search with AlexNet (a deep CNN), involved extracting around 2,000 region proposals per image and then independently classifying each region using CNN features. This approach, while pioneering, was noted for its inefficiency and high computational cost, especially during testing where each proposal needed to be processed separately.</p><p>To enhance efficiency, the Region-based CNN (R-CNN) framework was introduced. R-CNN improved on the previous methodologies by applying a high-capacity CNN to extract features from each proposed region independently, followed by a classifier that determined the presence of an object within each region. However, R-CNN requires a convolutional neural network (CNN) pretrained on a large dataset like ImageNet to initialize the weights, which are then fine-tuned on a smaller dataset specific to the detection task. This two-step training is computationally expensive and time-consuming. Moreover, instead of using the softmax layer typical in CNNs, R-CNN trains a set of binary Support Vector Machines (SVMs) for object classification. Each class requires a separate SVM, making this process cumbersome when scaling to datasets with many object classes. Also, After classification, a separate linear regressor is trained for each class to predict tighter bounding boxes around the detected objects. This additional training stage adds to the complexity and runtime of the model setup. Other problems are that each object proposal is processed independently, which significantly increases the computational load and storage requirements. Training R-CNN on a standard dataset can take approximately 2.5 GPU days, which is impractical for large-scale or real-time applications. R-CNN is notably slow during the testing phase. It performs around 2,000 forward passes per image to evaluate all object proposals. For instance, using a deep model like VGG16 for detection takes about 47 seconds per image, which is far from real-time performance. The selective search algorithm used for generating object proposals is fixed and heuristic-based. It does not learn to improve its proposals based on the detection performance of the network, which can lead to suboptimal proposal quality and an increased number of irrelevant proposals. This fixed nature limits the adaptability and efficiency of the model, especially in varied or dynamic environments.</p><p>Further refinements led to the development of Fast R-CNN, which introduced a streamlined process where a single CNN forward pass was used to extract features from the entire image. These features were then shared across all regions through a technique known as Region of Interest (RoI) pooling, significantly speeding up the process and improving detection performance. In summary, fast R-CNN is faster than R-CNN is because it is not required to fed 2k region proposals to the CNN every time. Instead, the convolution operation is done only once per image and a feature map is generated from it.</p><p>The evolution continued with Faster R-CNN, which replaced the slow and computationally expensive selective search method with a region proposal network that is fully integrated with the detection network. Faster R-CNN is an advanced object detection framework that evolved from the previous iterations of Region-based CNNs, such as R-CNN and Fast R-CNN. This model introduces significant improvements in both the efficiency of generating region proposals and the speed of detection, thus addressing some of the major limitations found in its predecessors.</p><p>— Similar to Fast R-CNN, the entire image is provided as an input to a Convolutional Neural Network (CNN). This network processes the image and outputs a convolutional feature map. This map contains rich feature representations of the original image across various locations and scales.<br> — In R-CNN and Fast R-CNN, the region proposals were generated using a selective search algorithm, which is slow and heuristic-based. Faster R-CNN introduces a Region Proposal Network (RPN) that shares full-image convolutional features with the detection network, thereby making the proposal generation nearly cost-free.<br> — The RPN is a fully convolutional network that predicts object bounds and objectness scores at each position. The RPN is trained end-to-end to generate high-quality region proposals, which are then used by the detection network. This integration dramatically speeds up the proposal generation process and improves the quality of the proposals.<br> —After the region proposals are generated, each proposed region (or RoI) is transformed into a fixed-size feature map using an RoI pooling layer. This process involves dividing the RoI into a fixed number of segments (e.g., 7x7), and then max-pooling the features in each segment to produce a compact feature map.<br> — This fixed-sized output is crucial for performing classification and bounding box regression on regions of varying sizes.<br> — The pooled feature maps are fed into a series of fully connected layers that output the class probabilities and bounding box offsets for each RoI. This step is similar to Fast R-CNN but benefits significantly from the faster and more accurate region proposals provided by the RPN.</p><p>By integrating the proposal generation with the detection network, Faster R-CNN achieves higher precision in detecting objects compared to its predecessors, as the system is more sensitive and accurate in identifying relevant features. The streamlined architecture allows for faster processing, substantially reducing the time required for detecting objects per image. It can operate in near real-time on modern GPU hardware, making it suitable for applications that require quick and accurate object detections. The RPN component allows Faster R-CNN to dynamically adapt to different object scales and aspect ratios, enhancing its utility across various scenarios without needing pre-defined proposals.</p><p><strong>YOLO (You Only Look Once)</strong></p><p>YOLO, or You Only Look Once, is a groundbreaking approach to object detection that significantly differs from region-based methods like R-CNN, Fast R-CNN, and Faster R-CNN. It simplifies the object detection process by treating it as a single regression problem directly from image pixels to bounding box coordinates and class probabilities. This unified approach allows YOLO to achieve high speeds in detection, making it particularly suitable for real-time applications.</p><p>Unlike methods that use region proposals to localize objects, YOLO applies a single convolutional neural network (CNN) to the entire image. This network simultaneously predicts multiple bounding boxes and class probabilities for those boxes, effectively capturing the entire object detection pipeline in one quick pass. YOLO divides the input image into a grid. Each grid cell is responsible for predicting bounding boxes and probabilities for objects whose center falls within the cell. The size of the grid is a design choice that balances between speed and accuracy.</p><p>Each grid cell predicts m bounding boxes. For each bounding box, the network outputs five predictions: the x and y coordinates relative to the cell, the width and height relative to the whole image, and a confidence score that reflects the accuracy of the bounding box and the likelihood that the box contains a particular class. Additionally, each grid cell predicts a class probability for each class conditioned on the object being present in the box. These probabilities are independent of the bounding box predictors.</p><p>Bounding boxes are filtered through a class-specific confidence threshold to determine which boxes are kept. This confidence score is a combination of the box’s objectness and the class probability. Boxes with confidence scores above a threshold are used to locate objects in the image.</p><p>YOLO’s architecture allows it to process images in real-time, achieving speeds much greater than those of region-based methods. This is due to the elimination of the proposal generation step and the efficient processing of the entire image through a single neural network. By framing detection as a regression problem, YOLO can directly predict bounding box coordinates and class probabilities without the need for a separate proposal or refinement stages, streamlining the detection process.</p><p><strong>Advantages</strong></p><p>YOLO’s speed is one of its most significant advantages, making it highly suitable for applications that require real-time detection, such as video surveillance and autonomous driving. Since each grid cell makes predictions with a global context in mind, YOLO is less likely to predict false positives on the background.</p><p><strong>Limitations</strong></p><p>YOLO may struggle with small objects that appear in groups or are close together, as each grid cell only predicts a limited number of boxes. Since the localization is tied to grid cells, the precision of bounding box predictions may not be as high as methods that focus more on individual regions or adjustments.</p><p><strong>Mask R-CNN</strong></p><p>Instance segmentation is a challenging computer vision task that involves identifying and delineating each distinct object of interest in an image. Unlike semantic segmentation, which categorizes each pixel into a class, instance segmentation not only classifies each pixel but also assigns it to a specific instance of an object. Mask R-CNN is a state-of-the-art model that extends Faster R-CNN to perform this task effectively by adding a branch for pixel-level segmentation.</p><p>Mask R-CNN builds on the architecture of Faster R-CNN by using its backbone for feature extraction and its Region Proposal Network (RPN) for generating object proposals. Alongside the bounding box and class label predictions typical of Faster R-CNN, Mask R-CNN introduces an additional output for predicting segmentation masks.</p><p>For each Region of Interest (RoI) identified by the RPN, Mask R-CNN adds a branch that outputs a binary mask at the pixel level. This mask indicates the shape of the object within the bounding box. This branch is essentially a small FCN applied to each RoI, predicting a segmentation mask independently of the class labels, allowing for greater flexibility and accuracy in shape detection.</p><p>While Faster R-CNN uses RoIPooling, which may cause misalignments due to quantization, Mask R-CNN implements RoIAlign. This method avoids quantization of coordinates altogether, ensuring that the extracted features align precisely with the regions of the image. RoIAlign significantly improves the accuracy of the segmentation masks by maintaining the spatial fidelity of the features, which is crucial for pixel-level predictions.</p><p>During training, Mask R-CNN uses a multi-task loss that combines the losses of the classification, bounding box regression, and mask prediction tasks. This unified approach optimizes the network for both detection and segmentation simultaneously. At inference time, Mask R-CNN processes images by first generating proposals, classifying them, regressing bounding boxes, and simultaneously predicting segmentation masks, providing detailed instance-specific segmentation.</p><p>Mask R-CNN achieves high precision in instance segmentation tasks due to its accurate localization of objects and detailed segmentation of object contours. It is widely used in various applications, including autonomous driving (for precise object localization), medical image analysis (for detailed anatomical segmentation), and video analysis.</p><p>Mask R-CNN represents a significant advancement in the field of computer vision by effectively combining object detection with pixel-level segmentation. Its ability to provide detailed instance-level segmentation makes it a powerful tool for many practical applications where understanding the context and shape of individual objects is crucial. Its architecture, while complex, provides a robust framework for addressing some of the most challenging tasks in image analysis today.</p><h3>Getting neural nets to train</h3><p>Remember that neural network optimization landscapes are problematic and the neural networks are messy. They require lots of tricks to train well and knowing those tricks is really important for good results, just as important as understanding all of the theoretical nuances. We’re going to talk about:</p><ul><li>Normalizing inputs and outputs</li><li>Normalizing activations (batch normalization)</li><li>Initializing weight matrices and bias vectors</li><li>Gradient clipping</li><li>Best practices for hyperparameter optimization</li><li>Ensembling, dropout</li></ul><p><strong>Normalizing inputs and outputs</strong></p><p>Let’s say that you have this neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*3D2-9hAPzIa6Phjc-aJkQw.png" /></figure><p>It takes in a 2D input and some of our data points look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*szWCR_CCc1vqnyv3yfKFKQ.png" /></figure><p>Here, everything looks normal. X1 and x2 vary and this is a standard setting where you’d expect everything would work well. But if we look at this scenario:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*XC-ZHqWI6O2iTh3PRqj-7Q.png" /></figure><p>The first dimension is on a very different scale from the second dimension. Its numerical value is larger and its range is larger. The actual information represented by these data points might be exactly the same and it could be that if you were to rescale the bars for the data points on the right, you might get things that look exactly the same as the distribution on the left. The resulting gradients will be poorly conditioned and the network will be biased towards paying attention to the larger numbers before passing into the smaller numbers, even though they’re not necessarily more important for the prediction problem.</p><p>Standardization is what we do to solve this issue: we transform our inputs so that they tend to have means of zero and standard deviations of one. All you have to do if you want the mean to be zero is subtract the mean from every dimension of x:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*tIqnZlJheY3umvEsJoOUiQ.png" /></figure><p>The expected value of x is the mean and you estimate it by averaging all the x’s in your data set.</p><p>If you want to also make the standard deviation one, then you do the same exact thing and you also divide by the standard deviation of x in the data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*nNF4FilQqDZBt6m80G6dpA.png" /></figure><p>It’s also a good idea to do this for outputs, if you’re solving a regression problem.</p><p><strong>Normalizing activations (batch normalization)</strong></p><p>While Stochastic Gradient Descent (SGD) is a powerful optimization tool for training deep neural networks, it’s not the sole element ensuring successful training. DNNs, particularly deep architectures, are notoriously difficult to train due to issues like vanishing/exploding gradients, slow convergence, and internal covariate shift (ICS). To address these challenges, various techniques and normalization methods have been developed to stabilize the training process, improve convergence rates, and enhance model performance. Let’s delve into the concept of ICS and the normalization techniques designed to combat it, including Batch Normalization, Layer Normalization, and others.</p><p>Internal Covariate Shift (ICS) refers to the phenomenon where the distribution of each layer’s inputs changes during training, as the parameters of the previous layers change. This shift can push the inputs into the non-linear regions of activation functions, where gradients are either too steep or too flat, leading to inefficient training. Batch Normalization (BatchNorm) directly addresses ICS by normalizing the inputs of each layer to have a mean of zero and a standard deviation of one. This normalization is done for each mini-batch.</p><p>To also standardize the activations, we will use mini-batches to estimate mean and standard deviation. Instead of estimating the mean by averaging the activations over every data point in the data set, which would be very expensive, we will estimate the mean by averaging together the activations of all the data points in the batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*7sl8L3cfvwXDA0rTcpMdkQ.png" /></figure><p>We do the same thing for the standard deviation. Instead of computing the standard deviation over the entire data set, we compute it only over the batch. In a practical implementation, we would also have two additional parameters for our activations (gamma and beta). After we subtract the mean and divide by the standard deviation, our activations will be in a particular range, but we might not want that going into the next layer. And we might want to have a transformation on them instead, by multiplying them by a scale and adding a bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*l-Y8nm3bLKSu4T1lKLIlLg.png" /></figure><p>You can think of batch normalization as a layer that calculates mean and std from all the activations going into the batch norm layer in the current batch and then has parameters gamma and beta.</p><p>A few practical details:</p><ul><li>If you do use batch norm, you can often use a larger learning rate because it’s going to make your derivatives more well conditioned and will prevent to some degree these really awkwardly scaled objective landscapes, where some dimensions have much bigger gradients than others.</li><li>Models with batch norm can train much faster and generally require less regularization</li></ul><p>Normalization techniques have been proposed to either extend or provide alternatives to BatchNorm, each with its specific use cases and advantages.</p><ul><li>Layer Normalization: normalizes the inputs across the features for each training sample within a layer. It’s particularly effective for recurrent neural networks (RNNs) and Transformers, as it doesn’t introduce dependencies between training samples.</li><li>Instance Normalization: applies normalization for each individual instance separately by computing the mean and variance for each instance. It’s found useful in style transfer tasks where instance-specific contrast normalization can simplify generation.</li><li>Weight Normalization, Normalization Propagation, Divisive Normalization, Batch Renormalization, …</li></ul><p><strong>Initializing weight matrices and bias vectors</strong></p><p>We’re not going to try to initialize our weights so that they’re close to a good solution, we’re just going to initialize them so that, at initialization, the derivatives of the neural network are of high quality — meaning they point in a direction of an optimum.</p><p>One very simple choice for small networks is to initialize the weights to some small random numbers; for example, we could pick a normal distribution with a mean of 0 and a standard deviation of 0.0001. But as your network gets deeper, this will quickly give you bad answers, because if the activations are zero, then the gradients are zero. And if the gradients are zero, then you’re not making any progress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*knVBMJZMPf6J-eV99v89Uw.png" /></figure><p>In fact, this corresponds to a really bad plateau.</p><p>To avoid this issue, we use Xavier initialization. The goal of Xavier Initialization is to initialize the weights such that the variance of the activations is the same across every layer. This constant variance helps prevent the gradient from exploding or vanishing. I won’t explain all the details of the mathematical justification, because it is not the purpose of this article. A rough description follows.</p><p>Let’s say that we’ll initialize our weights at some linear layer so that our weights are sampled according to a gaussian distribution with a mean of 0 and some variance sigma w squared</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*dygG4lI2DpzBBIHDeh2l_A.png" /></figure><p>What should we set the variance to be?</p><ul><li>The biases will be initialized to zero and this is the formula for every entry in z</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*kRKpAVkjofdK3N4ZxHsy8A.png" /></figure><ul><li>We standardize x and therefore the activations are gaussian.</li></ul><p>What will be the magnitude of these z’s? If the means are all zero, then the magnitude of the z’s is their standard deviation. If we write out the the variance of z, since z is zero mean, that’s just the expected value of z squared:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*83c52HFZS_8iVGB0u_2m9Q.png" /></figure><p>You take the expected value of the squared sum and you take each of the terms in the sum squared. This simplifies to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*Xx5XcdZTdOKvMlso9ys-Ow.png" /></figure><p>The dimensionality of a times sigma w squared times sigma a squared.</p><p>We got on this track because we were worried that our choice of initialization for the weights will either increase or decrease the magnitude of the activations. If the previous layer has activations with a variance of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*TZ8FoHWtD1wztMQXu4qHuQ.png" /></figure><p>And the next layer has activations of magnitude:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*Xx5XcdZTdOKvMlso9ys-Ow.png" /></figure><p>Then we know that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*s31JpYUfIk-oZAhhnXT82g.png" /></figure><p>If we want the magnitude of the activations to stay about the same layer after layer, we need to somehow make sure that Da sigma w squared is about one. We could choose sigma w squared to be one over Da:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*xGgezfzghWdJ4DwURbkpTQ.png" /></figure><p><strong>The basic principle is that we need the standard deviation to be 1 over the square root of the dimensionality of the incoming vector.</strong></p><p>There’s a detail that we missed: we forgot about non-linearities. After we apply this linear layer, we’re going to then apply some non-linear function to the z’s and that nonlinear function will change their magnitudes. One very commonly used nonlinear function is the rectified linear unit. Deeper networks will almost always use ReLUs, because they’re much better behaved than sigmoids. However, the problem is that the ReLU will zero out many of our activations; in fact, if our activations are normally distributed and have zero mean, the ReLU would zero out about half of them.</p><p>If half of our activations will be removed, this will indeed decrease our variance. To avoid this, we make the variance two times bigger or equivalently make the standard deviation square root of two times bigger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/88/1*i_dJUruMGfk0aM251GdgYw.png" /></figure><p>An even smaller detail: biases. Earlier, we said that we’ll initialize all these bias vectors to be about zero; but again, the ReLU would kill half of them. Oftentimes, especially when people don’t use that one half factor, it’s pretty common to initialize the biases to some small positive constant like 0.1 because dead units.</p><p><strong>Advanced initialization</strong></p><p>The basic initialization I have described so far is going to work well for most problems. However, we’ll now discuss a more advanced form of initialization, both because sometimes it works well and because it helps understand what’s going on with network initialization.</p><p>The derivative of the loss with respect to the weights at some layer is given by a product of lots and lots of matrices, specifically all the jacobian matrices between that layer and the loss. Without worrying what those matrices are we can just write it as a big product. If you multiply lots of stuff together and all that stuff is less than one, the product will be about zero; on the other hand, if it’s greater than one, it’ll be about infinity. You only get a reasonable answer if all of these jacobians are close to one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*FVXuIxaPfIV1fgV7rGGZFg.png" /></figure><p>For a matrix to be close to one, its eigenvalues have to be close to one.</p><p>We can write any of this jacobians as a product of three matrices (for example, with singular value decomposition):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*7kTXjVLWpN6H8KwqrAWkoA.png" /></figure><ul><li>U and V are scale-preserving transformations; they’re orthonormal bases. That means that when you multiply a vector by the matrix U or V, it will not change that vector’s length and it’ll just rotate it in various ways.</li><li>Lambda is diagonal and the diagonal entries of lambda are the eigenvalues of the jacobian. Roughly speaking, lambda captures all the rescaling that this matrix does and U and V capture all the rotations</li></ul><p>If we can force lambda to have scales of one along each dimension, that would be enough to ensure that this big product of jacobians doesn’t yield huge or tiny numbers. Remember that the jacobian for a linear layer is just the transpose of its weight matrix, so if we want these jacobians to have eigenvalues of around one, we have to take our weight matrices and perform something like singular value decomposition on them and then somehow force that lambda to be the identity matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*-UasbzhpVaeIvjdvbFii_g.png" /></figure><p>We could take some arbitrary initialization, run singular value decomposition on it, force the diagonal to be identity and then put it back together. Forcing the diagonal to be identity just means discarding that and constructing the the final matrix as U times V.</p><p><strong>Gradient clipping</strong></p><p>Sometimes, it might happen that you take the direction of steepest descent, everything is fine, you think you’re making good progress and then you get some monster gradient that completely messes up your network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*gvjMXEUcPnUjoH0dWkqXDw.png" /></figure><p>Gradient clipping can often be a reasonable kind of band-aid to patch this issue. There are two ways that you can clip your gradients.</p><ul><li>One way is you can clip every entry in the gradient so that it’s no larger than some constant c and no smaller than negative c.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*lb4cucppFcz0yR0scBovEA.png" /></figure><ul><li>Another thing you could do is you can clip the norm of the gradient : you maintain the direction and just clip the length.</li></ul><p>To choose c manually, you can run a few epochs of training and just look at what healthy gradient magnitudes look like. This is meant to be a measure of last resort.</p><p><strong>Ensembles and dropout</strong></p><p>We’ll go from talking about how to get neural networks to optimize better to talking about how to get them to generalize better.</p><p>When we’re doing machine learning, we worry about whether our model will make a mistake and presumably how to get it to make fewer mistakes. Neural networks are going to have many parameters and thus high variance. Here’s an interesting idea: if we have multiple high variance learners and we train many neural networks instead of one, maybe these multiple neural networks will all agree on the right answer, but they’ll disagree on the wrong answers.</p><p>This is another way of saying that tere are many more ways to be wrong than to be right. Those networks will hopefully make independent mistakes, which means that when one of the models makes a mistake, another one might too but the in different ways. That’s the basic intuition behind ensembles.</p><p>Let’s say that we are solving a regression problem and let’s say that this green curve represents the true function, while the blue points are my training set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*zPUHqHKpXJdOK3LLxbKASw.png" /></figure><p>I train a large neural network model and its solution is represented by this orange line so the orange line, which is pretty good in the vicinity of my training data but it’s pretty bad away from the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*TGRe4piCS6vKL-oAWSSEzA.png" /></figure><p>I can train another model with a very different initialization and get another solution. Both these models are good on the training set and both of them are pretty bad in the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*attmCzaL1We-PARe1VKOIQ.png" /></figure><p>I’ll train another one. And if I look at the average of all three of these models, it might be pretty good. They will all disagree, but on the whole their mistakes will be centered around the right answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*icxq-l7w6GJmbH9ZQFwWXg.png" /></figure><p>Of course, this picture is a little bit idealized, but that’s the basic intuition.</p><p>What I’ll describe next is the theoretically principled way to construct bootstrap ensembles. Variance is quantified as the expected value of the difference between the model that we get from training on some dataset D and the average of all models over all possible datasets from that training distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*qdiYC2QODKUU_8Ttrb-Xfw.png" /></figure><p>If variance is high, you would expect your error to be high. But if we can estimate f bar, then we should be able to eliminate a lot of our variance. Could we somehow get m different training, sets train a different model on each one and then average together those models? We would expect that if all these different models disagree and make different mistakes on test points, then their average will be forced to agree on something close to the right answer.</p><p>But where do we get these datasets? Can we cook up multiple independent datasets from a single dataset without having to deal with less data?</p><ul><li>A simple naive approach would be to take a big dataset and just chop it into m non-overlapping parts, but that’s wasteful because then you’re training each model on a much smaller amount of data</li><li>Maybe we don’t need those m data sets to be non-overlapping and we can somehow construct independent datasets out of one large dataset, with those independent days being the same size as the original</li></ul><p>That is possible and this is called resampling with replacement. We are going to resample data points from the original dataset. Let’s say our original dataset has three points (of course, in reality we would have a lot more).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*xTDMZNey3hosytMvIMBEVw.png" /></figure><p>We’re constructing our first resampled dataset; we roll a three-sided die and we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*H5wzOj-ry85SBjMwufsx9w.png" /></figure><p>Then again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*HfCHvj8dWVTr_FlsWBH4wA.png" /></figure><p>If we sample new data points i.i.d. from the original training set, they will also be i.i.d. samples from the original training distribution. And because they are sampled independently, they end up being i.i.d. samples from the same original distribution. These datasets are going to end up being independent.</p><p>What distinguishes these models from one another is that they have different parameter vectors, because they were trained independently of one another on different but closely related data sets. Once we have these different models, then we have to somehow combine their predictions when classifying a new test point.</p><ul><li>The principled approach is to average together their probabilities, so you run these models forward, get the probabilities out of their soft max and then you average together the probabilities to get the ensembles’ predictions</li><li>A slightly simpler but still effective approach is to simply do majority voting. Instead of looking at the actual probabilities coming out of these networks, we could also just ask them to predict what they think the right answer is and then output the answer corresponding to the majority vote of the networks</li></ul><p>In practice, when we do deep learning, we rarely use this kind of resampling with replacement approach, because there’s a simpler approach that is very commonly used and that seems to work just as well. The purpose of resampling with replacement is to get enough variability between the different models, so intuitively we don’t want all the models to end up with the same incorrect solution. Resampling the data with replacement is one way to get them to differentiate, but the methods that we typically use for training deep networks already have a lot of randomness (different random initializations, random minibatch shuffling, stochastic gradient descent). No two training runs, even for the same exact model and the same exact data, are going to look the same, because of all these sources of randomness. In practice, we therefore get much of the same benefit of the ensemble without even generating these separate datasets. If we just take m different models and we train them on the exact same training set, we’ll get sufficiently different models.</p><p>The practical way to construct an ensemble out of a deep network is to simply train m different models on the same training set and then average together their probabilities or do majority voting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*JOjdEZla3Ts33ETY3E1UxA.png" /></figure><p><strong>Even faster ensembles</strong></p><p>These networks can be very large and they can be very costly to train. But remember, deep learning is all about representations, and the last layers are those that are generally task-specific and are trying to figure out the representation. That means that we can try to only ensemble those last few layers. We can train multiple different networks, but have them share the trunk that performs feature extraction and then have a different group of fully connected layers for each head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ecmNas8YhPubNmao-WsAFA.png" /></figure><p>That’s not quite as good as real ensembling, but is a lot faster to train and often easier to set up</p><p>Usually, ensembles work better when they’re bigger, but making huge ensembles is really expensive, especially if you’re training m independent models. That computation is easy to parallelize, but it still costs you something. So, can we make a huge ensemble out of just one network.</p><p>That’s what a technique called dropout tries to do. The idea behind dropout is that you’re going to take your neural network and you’re going to randomly kill some of the activations — you’ll go into each of the hidden layers and, with some probability, you would just delete some units setting them to zero.</p><p>What does this have to do with ensembles? You can think of this process of killing off some of the activations as constructing a different network out of the old one; every group of activations corresponds to a different network, so by selecting different random groups of activations to delete, you’re constructing new networks. But these networks don’t have separate weights, they actually share all of them, they just have different architectures.</p><p>The way we implement this is: during each forward pass, each time we come to some layer, we’ll compute the activations of that layer by deleting half of them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*uLpYZxUwDIBoUL5IIrYKbA.png" /></figure><p>The backward pass works exactly the same way. The gradient is an outer product with a, so if the activation was set to zero, its derivative will also be set to zero. In effect when you do this, you delete that activation from your network.</p><p>The intuition behind why dropout works is that it forces the neural network to build redundant representations and to deal with the fact that every feature has some probability of being deleted — so it can’t make predictions based on only a single feature. It forces the networks to be robust and to be more reliable. When you train in this way, you get something that looks like a really really huge ensemble, because every combination of feature deletions can be thought of as a different model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*NbQAoNhG2vcOiC3NMhijRA.png" /></figure><p><strong>What happens at test time?</strong></p><p>At training time, half of dimensions are forced to 0. At test time, we don’t use any dropout, so the product between weights and activations is twice as big. We thus divide the weights by two to compensate and get them back to their original scale.</p><p><strong>Hyperparameters</strong></p><p>With all these tricks that we’ve talked about, we’re going to end up with a lot of hyperparameters. Some of them affect optimization:</p><ul><li>Learning rate</li><li>Momentum</li><li>Initialization</li><li>Batch normalization</li></ul><p>Some of them affect generalization:</p><ul><li>Ensembling</li><li>Dropout</li><li>Architecture</li></ul><p>How do we select all these parameters? One important thing to do is to recognize which type of parameters are supposed to affect what.</p><p>For example, bad optimization hyperparameters are going to show up early in the training process. We can therefore adjust them, start training the network, look at the training error and see how it evolves in the first few epochs. Other hyperparameters are going to affect the validation error. It’s often a good idea when adjusting hyperparameters to start with a very broad sweep over hybrid parameters, train for only a little while and see how basic training progresses. Then you adjust your hyper parameters again, narrow down their range and repeat.</p><p>In grid search, parameters are defined and searched exhaustively. In random search, not all the specified parameters will be tried. Compared to exhaustive search, this method is advantageous because you can choose the maximum number of trials wanted for this search.</p><h4><a href="https://www.youtube.com/watch?v=PyZvbaC5oQY&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=30">Recurrent neural networks</a></h4><p><strong>What if we have a variable size input?</strong></p><p>A sequence input can be of variable length. For example, they might be sentences in English (the first sequence has four elements, the second one has three elements and the third one has five elements):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*-tP6xKHNeK2JL2KfxmmcDw.png" /></figure><p>This could involve:</p><ul><li>Sequence of words → The problem of sentiment classification: you have a review online and you want to guess whether this is a positive or a negative review.</li><li>Sequence of sounds → The problem of recognizing a phoneme from a sound</li><li>Sequence of images → The problem of classifying the activity in a video</li></ul><p>You need a network that can:</p><ul><li>Accommodate multiple inputs and multiple different numbers of inputs</li><li>Share features</li></ul><p><strong>One idea</strong></p><p>The number of layers becomes the same as the number of inputs. In other words, you get a separate input for every layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*MsJmtun9KfDFDNAujVZuRQ.png" /></figure><p>If you have a sequence of length four, then you’ll have four layers; if you have a sequence of length three, then you’ll have three layers; if you have a sequence of length five, then you’ll have five layers.</p><p>At each layer, we have two inputs now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*zNVNpqfGqw-obwsx5cGwsg.png" /></figure><ul><li>The activations of the previous layer</li><li>The new input x</li></ul><p>Then we apply a regular linear operation to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*TZDk_SymQyDfgrDa-Qt1MA.png" /></figure><p>As usual, we apply a non-linearity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*A_cH3UJ905kxAGGLYuHnFw.png" /></figure><p>This is very much like the standard linear layers; the only difference is that, instead of applying the linear layer to the previous layer activations, now you concatenate the new input to those previous layer activations and then pass them through the linear and non-linear operations.</p><p>What happens to the missing layers? If you have a sequence of length five, then you’re gonna have five layers, whereas if you have a sequence of length three, then you’re gonna have three layers.</p><p>Here’s a funny trick: if we have a shorter sequence, we’ll just pretend that the activations at the layer prior to the first input (this layer doesn’t exist) are all zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*g8iGGEeGKwBE79_my6_KZw.png" /></figure><p>In fact, we’ll do this regardless of the length of the sequence; even for the longest sequence, we’ll still have a virtual preceding layer where the activations are all zero. When performing our usual operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*fxM3gMYsgJtj4zODtgHFyg.png" /></figure><p>At the very first layer, we will just concatenate the input to a big vector of zeros</p><p>One big problem with this design is that we still have a different weight matrix at every layer. Really long sequences will end up requiring many of those weight matrices. However, the last few layers will be trained for all the sequences, whereas the the very first layer that is only used for the longest sequences might have been trained very rarely.</p><p>The one additional modification that we need to turn this design into a full-fledged recurrent neural network is to share the weight matrices.</p><p>What that means is W(l) will be the same for all of these layers</p><ul><li>Everything about how you evaluate this network doesn’t change</li><li>At test time, everything is exactly the same. We just initialize this virtual first layer to zero and then we proceed with these operations:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*HWFgBZXBMKOGWvDD9Ws5Zg.png" /></figure><ul><li>This only affects training. During training we have to force the matrices W(l) to be the same for all the layers:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*yX3j8oLPQR4auVo-Par6eA.png" /></figure><p>The very long sequences might require those weights at the very early layers (that we only see for very long sequences), but now those weights are the same as the ones used in the later layers and they have already been trained pretty well.</p><p>If we force the weight matrices to be exactly the same at every layer, we can have as many layers as we want</p><p>Basic design of a RNN:</p><ul><li>Very deep network whose depth is equal to the length of your sequence</li><li>Every layer gets a different input: it concatenates the previous layer’s activations with the input at that time step, it passes them through a linear layer and then a non-linearity</li><li>The very first layer gets a zero as input from the from the virtual previous layer</li><li>The weight matrices are shared at all the layers, which means that we don’t need a number of weight matrices equal to the length of the longest sequence</li></ul><p><strong>How do we train RNNs?</strong></p><p>The short answer is that we’re going to slightly modify backpropagation.</p><p>When we run backpropagation, the basic design is the same. First, we run a forward pass to calculate all the a’s and z’s at each step. Then, for the backward pass we proceed in the same way. We initialize delta to be the derivative of the final loss with respect to the last layer output and then for every linear layer and for every ReLU we calculate the derivative with respect to its parameters and the derivative with respect to its inputs (which is the previous layer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*_fyDZZ91U7RAWw8TkbtavA.jpeg" /></figure><p>The issue is that the parameters are now the same at all these layers. That means that θf at layer 4 is the same variable as θf at layer 3. If we were to run this algorithm on the following layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*kGEkfPiPbvEBSiF4HPQwqA.jpeg" /></figure><p>Starting on the right, we would compute delta to be the derivative of the loss with respect to the output at layer four and then at layer four we would compute the derivative of the loss with respect to the weights and with respect to the bias. Then, we would compute the new delta, we would go back to layer 3 and at layer 3 we would override the gradient with the gradient of the w and b at layer 3. So, taken literally, the gradient at layer l-1 will overwrite the gradient of layer l — and we don’t want that. <strong>We want the derivative of the loss with respect to w and the derivative of the loss with respect to b to account for the effect of w and b on every layer, not just the first layer.</strong></p><p>It turns out to be very very simple to fix this problem. Instead of setting the derivative “df / dθf” to be “df / dθf” x “δ”, you just need to add it to the value of the derivative:</p><p>You’ll do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*FU-VOF1R7ltpH_Pp6WT-Gw.png" /></figure><p>Instead of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*_OZvemdw6gi3qRjayZiyOA.png" /></figure><p>At the beginning of backpropagation, you initialize all your gradients all your derivatives to zero and then at every step of backpropagation, for every layer you add “df / dθf” x “δ” to the current value of the derivative.</p><p><strong>What if we have variable-size outputs?</strong></p><p>For example, we may want to generate a text caption for an image, to predict a sequence of future video frames or to generate an audio sequence. Before, we had an input at every layer; now, we are going to have an output at every layer.</p><p>One immediate thing that comes up is that each of these outputs has their own loss. At each step, just like before, we’re going to perform these operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*khTCELv42FiuX-4qFA3ZzQ.png" /></figure><p>Now, y hat at that layer will be some function applied to a (l) and that’s some kind of readout function — sometimes referred to as a decoder. The parameters of f are going to be shared across all the time steps, just like the parameters of the linear layer. We’re going to have a loss on each y hat(l) and our total loss will just be the sum of the losses at every step. That’s a very simple way to combine the losses.</p><p>The problem we have is that it’s not completely obvious how to use backpropagation at this point, because regular neural networks are a chain — where you get your delta from the next layer and you backpropagate it into the previous layer. Now, we’re in a situation in which a neural network has branches; at every time step, we’ll have a delta coming in from the loss of that step and we’ll have another signal coming in from the next step. We then need to produce a delta going back into the previous step.</p><p>We’re going to draw the computation graph for this procedure.</p><p>You have your input x, which goes into a linear layer, then a non-linearity and then we have our first readout function f1 — which could be a linear layer followed by a softmax and goes into the loss of the first time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*UYQZuz4iM24Roy_MVdbBdg.png" /></figure><p>Sigma 1 also goes into the second linear layer. So, it produces a value, let’s say a1, and that same a1 is used by two downstream functions: f1 and lin2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*MIneWJM9b5ZAbaYVovH06g.png" /></figure><p>Then lin2 goes into sigma 2 and again, same mechanism. The losses at all time steps are added up and that’s what ends up producing the final loss value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*tzSWFMEQnFTB5yZ60zhMdg.png" /></figure><p>We can think of each layer as a function f that takes as input xf and produces as output yf. We always start backpropagation at the last function, where initial delta is just one. This is a graphical way of representing backpropagation for regular neural networks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*cokkdap1nAqCe562y3kWFg.jpeg" /></figure><p>The algorithm for regular nets is just a loop that starts at the last layer and proceeds backwards, and in each of those layers it’s going to calculate these delta “yf’s” and use them to calculate delta “xf’s” and “dL/dθ’s”.</p><p>Now, we’re going to generalize this a bit. The issue we have to deal with with RNNs is that we have some nodes whose output goes into multiple nodes. If you have a look at the computation graph I drew above, you’ll notice that the output of sigma1 goes into f1 and also goes into lin2. <strong>During backpropagation, there’s going to be one delta coming in from one of those outputs and another delta coming in from another one of those outputs. All we do is we just add them together and then we just plug them into the same algorithm.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*SKvo45LtJneyx3WehoexKw.jpeg" /></figure><p>This is also sometimes referred to as “reverse mode automatic differentiation”</p><p><strong>What if you have multiple inputs and multiple outputs at each step?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*qv1QKOugAlgTn7nXXhCn6w.png" /></figure><p>We simply combine the two concepts we saw before. At each step, we:</p><ul><li>Concatenate the activations of the previous layer with the new inputs</li><li>Apply linear layer</li><li>Apply non-linear layer</li><li>Have some readout function (which could be just a linear layer and a softmax) to produce the output y hat at that step</li></ul><p><strong>What makes RNNs difficult to train?</strong></p><p>RNNs at their most basic level are very deep networks</p><p>We have to reconsider why it’s so difficult to train very deep networks. The <a href="https://medium.com/mlearning-ai/backpropagation-6a2575f09537">chain rule</a> just looks like a multiplication of a bunch of jacobians; for some arbitrarily deep network, the derivative of the loss with respect to the weight matrix of the first layer will be a product of a huge number of jacobian matrices. Then at the end you multiply that number dL / dz(n):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*bG2s-1JilZCN6wuS" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/0*TR9Idwr00CnwCRcx.png" /></figure><p>These jacobian matrices can be all sorts of different things. Derivatives of non-linearities, derivatives of linear layers, derivatives of convolutions. If we simplify for a second and think about scalars, the problem with multiplying many numbers together is that there are two possible outcomes: if most of the numbers are less than one, we’re going to get zero (vanishing gradients), whereas if if most of the numbers are larger than one, we get infinity (exploding gradients). There’s a very small set of cases where the answer is more interesting and that small set of cases is when all the numbers are close to one: the only time that you get a reasonable answer from multiplying together many scalars is if they’re all close to one. By the way, this is we we prefer ReLUs instead of sigmoids; the derivative of a rectified linear unit is the indicator of whether the input is positive, which means that a large fraction of those derivatives are just 1.</p><p>For matrices, being close to one doesn’t mean that every entry is one, it means that the eigenvalues of the matrix need to be close to one. Exploding gradients are not too difficult to deal with because we can always clip our gradients to prevent them from exploding; the big challenge with RNNs comes from vanishing gradients. An intuitive interpretation is that if your gradient vanishes, the gradient signal from later steps never reaches the earlier steps: when that happens, your neural network becomes unable to maintain memory</p><p><strong>Promoting better gradient flow through an RNN</strong></p><p>At each layer, we’re going to concatenate the new input to the previous layer activations and then pass them through the linear and non-linear operations. We call this the “RNN dynamics”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*EiR-iZsj8j-F6Gi3LyMyTw.png" /></figure><p>The particular derivative that we care about when we talk about vanishing gradients is the jacobian of the RNN dynamics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/71/1*x7enK3rO0UxH47YbdOYM4w.png" /></figure><p>This is the derivative of q with respect to previous activations. Of course, we don’t just want to force the derivative to always have eigenvalues that are close to 1 (or to be close to identity), because sometimes we do want to forget things and sometimes we want to transform them in various interesting ways. We only want it to be close to identity when we really want to remember.</p><p>In other words, don’t just force them to be identity, but come up with some design where the network can decide that it wants to remember something; when it decides it wants to remember, then this derivative really ought to be close to identity.</p><p>The intuition is that for each unit, we have a little neural circuit that decides whether to remember or to forget. If you’re remembering, you just copy the previous activation as it is and don’t change it; if you’re forgetting, then you override it with something else</p><p>We’ll have a cell state and multiply it by some number f(t), which is between 0 and 1. This is referred to as a forget gate, because if it’s set to 0 you forget what you had, otherwise you remember:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*F6HsWdgIJD0EaUnOWUU51A.png" /></figure><p>Then, we add some number g(t)to it.</p><ul><li>If f(t)is close to zero, then the cell state is replaced by g(t)</li><li>If f(t)is close to one and g(t)is close to zero, then the cell state is retained</li><li>if f(t)is close to one and g(t)is non-zero, then the cell state is modified in an additive way and that becomes our new cell state a(t)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*Ao0RsLRI1huZLG4YxWn-Cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*Mjsv8eVRGxC4pVlmd7sThg.png" /></figure><p>Where do we get these f(t) and g(t)?</p><p><strong>LSTM cells</strong></p><p>The way that we’re going to decide whether to remember or to forget is based on another temporal signal h (t-1). H (t-1) comes as an output from the previous time step, along with a (t-1).</p><p>Then we have our input at this time step, x(t). We’ll do the same thing that we did before: we concatenate x(t) with h (t-1) and we apply linear and non-linear layers to them. This linear layer is going to produce an output that is four times larger than the output we had before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*UxSiwV84UeErp4knus2EJQ.png" /></figure><p>Each of those 4 rows is going to serve different functions. One of them is the f(t) we saw as a forget gate earlier and one of them is the g(t) we added to the product earlier.</p><p>1. We take f(t) and pass it through a sigmoid, which puts it in the range of 0 and that becomes the forget gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*d2YmvDRv8acnHUdciCcc5g.jpeg" /></figure><p>2. We take i (t) and also pass it through a sigmoid. This is called the input gate and it controls the modification to the cell state</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*go5xXvHQ_YWy-t8RKooSgQ.jpeg" /></figure><p>3. We take g (t) and we pass it through some non-linearity. It could be a tanh or a ReLU</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*d1mN8DmGvhVtkGkncZNrLg.jpeg" /></figure><p>g (t) is multiplied point-wise by i (t) and then you add the product to the cell state after the forget gate. Intuitively, i (t) determines whether you want to have a modification of the cell state and g (t) determines what that modification will be. This is very nice because it allows the network to independently choose whether to modify or not and separately choose how to modify</p><p>4. o (t) is called the output gate, it’s also passed through a sigmoid and it controls the next h (t). After the forget gate and after the addition of g (t), we take our cell state a (t) and pass it through a non-linearity. Then, we point-wise multiply by o (t) and that becomes the new h (t)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*BHBARhZySsCmI5BzcIjsxQ.jpeg" /></figure><p>This new h (t) is also what we use if we want a readout function / a decoder at that time step.</p><p>What is going on here is: we’re trying to preserve the role of a (t) as a linear signal. All the non-linearities are applied to the h’s and as a result the gradients on a (t) are going to be pretty simple</p><ul><li>Not having non-linear functions affecting a (t) makes its derivatives very well behaved</li><li>At the same time, we still retain the benefit of non-linearity by having a non-linear modification through g (t) and a non-linear readout through h (t)</li></ul><p>Why do these LSTM cells work better? The simplest reason is that a (t) is modified in a very simple way at each step</p><p>You can think of a(t) as the long-term memory, while h(t) is the short-term memory — it changes all the time and performs complicated non-linear processing.</p><p><strong>Practical notes</strong></p><ul><li>RNNs almost always have both an input and an output at each step</li><li>Naive RNNs like the ones in part one almost never work; in practice, if you want an RNN you will probably be using something like an LSTM cell, even though it requires more hyperparameter tuning than standard fully connected or convolutional networks</li><li>There are also some alternatives to RNNs for processing sequences that can work a lot better in practice (temporal convolutions and transformers)</li><li>There are some variants of the LSTM that are a bit simpler and work just as well (gated recurrent units)</li></ul><p><strong>Autoregressive models and structured prediction</strong></p><p>Most RNNs that we actually use in practice have multiple inputs and multiple outputs, because most problems that require multiple outputs have strong dependencies between these outputs.</p><p>These kinds of problems are sometimes referred to as structured prediction, because the thing that you are predicting has structure, in contrast to something like a label. A classic example is text generation. Regardless of whether the output of text is the right answer or not, there are relationships between words and text that determine whether it’s a valid text.</p><p>Let’s say that you have a training set that consists of three sentences:</p><ul><li>“I think therefore i am”</li><li>“I like machine learning”</li><li>“I am not just a neural network”</li></ul><p>Let’s say for now that you don’t care about generalization: you just want your model to memorize these three sentences. We’ll treat words as categorical variables; every time step will be a different word and it’ll just be one of n possible words.</p><p>Your neural network will read as input the word “I”. Then we ask it to complete the sentence and it can complete it in three different ways: “think”, “like”, “am”. Then we have a softmax distribution that turns these words into probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*Z4yZhJOXLrzGAvhV_wSyOw.png" /></figure><p>We’ll sample randomly from this softmax distribution and pick the second word. Now the network is completing the sentence and says “I think”. We then proceed to the next time step; we we have a linear layer that uses the previous activations to compute the new activations and then we have our output at the second time step, which again goes through a softmax distribution.</p><p>The trouble is that the network doesn’t know which word was randomly sampled from that softmax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*T7H5X3rca49wHDP70Uo1hA.png" /></figure><p>The network thought it produced an output that is 30% “think”, 30% “like” and 40% “am”. The problem is that you’re trying to sample these words independently. At the second time step you might randomly get “machine” and then at the third time step you might randomly get “just”. This generation makes no sense, even though the network did a great job at learning this distribution. We thus get a nonsense output and that’s because in this task the covariances between the words matter just as much as the probabilities of getting the correct words.</p><p>This is why it’s so important to have networks that take in variable length inputs and variable length outputs. When we run this network to complete a sentence, we’re going to sample from the softmax of the first time step and then we will feed our sample as an input at the second time step. This will basically tell the network what we sampled. Now the network knows that it’s not just predicting the third word in any sentence: it’s predicting the third word in a sentence where the first two words are “I think”. It’ll therefore correctly predict that if the first two words are “I think”, the third word is probably going to be “therefore”.</p><p><strong>The key idea is that past outputs should influence future outputs and the way you get past outputs to influence future outputs is by treating yesterday’s output as today’s input.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*XR49nv2p8PYmNFdPXapYWw.png" /></figure><p>This basic design is used for all RNNs that have to output a structured sequence, like image captioning models or video prediction models.</p><p><strong>Autoregressive models</strong></p><p>The simplest way to train it is to set the inputs to be the entire training sequence and the ground truth outputs to be the same sequence, but offset by one step. Instead of asking the neural network during training to just dream up a sentence, you’re asking to complete a sentence. You’re saying: at time step t, take all the words from time step 1 to t and output the word at time step t+1.</p><p>Your x’s are going to be all the tokens in the sentence and your ground truth outputs are going to be all the tokens shifted back by one. The last one will be replaced with a stop token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*HXIOcsEzrhnGOeBTZrGM4w.png" /></figure><p>Basically this network is being taught that if it sees “I”, it should output “think”; if it sees “think”, it should output “therefore” and so on.</p><p><strong>Distributional shift</strong></p><p>There’s an issue with this. The basic design I showed is going to work well, but if you use it to train really complex networks for very long sequences, you might start seeing some problems, which are due to distributional shift.</p><p>Let’s say that you have the same example as before, but the network is making some small mistakes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/87/1*kPxuHgVTv-Ei2hpQ0cLiEQ.png" /></figure><p>Why is it doing that? Maybe it didn’t train very well. Let’s say you got unlucky and you sampled the 10% word. The problem is that now you’re going to use it as the input of the next time step. Since it’s just some random token, the network has never seen it before and is going to be completely confused. At the next time step, it will thus output some completely crazy thing and then it’s not going to produce anything reasonable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*QUbWmYeiXcYTHJsD29zBAg.png" /></figure><p>This is a discrepancy between training and test: the network always saw true sequences as inputs, but at test-time it gets as input its one (potentially incorrect) predictions. This is called distributional shift, because the input distribution shifts from true strings during training to synthetic strings at test time.</p><p><strong>Scheduled sampling</strong></p><p>The basic idea is that during training we’re going to make a random decision at every step in time. With some probability, we’ll give the network the true input at that time step and with 1 minus that probability, we’ll give it its previous output as an input. Crucially, we don’t differentiate through this edge, so the network doesn’t know that it’s getting its own output as an input.</p><p>You can think of this as randomly replacing the true input with the network’s own output of the previous time step with some probability. This really helps because now during training the network sees its own outputs as inputs and therefore, when it sees that a test time, it’s not completely confused.</p><p>How do we want to choose this probability for replacing the true input with the model’s own previous output? Intuitively, we want to mostly feed in the true inputs at the beginning and then once the network gets pretty good we want to mostly feed the model’s own predictions to mitigate this distributional shift. We therefore put a schedule on this probability: the probability of using the true input starts off really high and then gradually drops. And since the probability of using the model’s output is 1 minus that, over time you’re mostly training the network on its own previous outputs</p><p>One of the big advantages of RNNs is that they afford a great deal of flexibility:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*KKgPYHHOhUfL98G1HDrAwg.png" /></figure><p>With regular feed forward networks, you have one-to-one mappings, whereas with RNNs you can have one input to many outputs, many inputs to one output, many inputs to many outputs and so on.</p><p><strong>Implementation details</strong></p><p>One of the things that we often do with RNNs is that we have an RNN backbone in our model somewhere in the middle and then we use a non-recurrent encoder (a regular convolutional network which then feeds into the RNN). You could also have some kind of complicated decoder and take the output of your RNN or LSTM cell and feed that into multiple layers before producing the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*aUpnnvoykMu03CLZQenXdQ.png" /></figure><p>You could also have multiple RNN layers, take the output of your RNN at a particular time step feed it into another RNN layer and then eventually into a softmax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*-nUB51FnF8PG5jyF4c9YBg.png" /></figure><p>Another trick you can use with RNNs is something called bidirectional models. For example, in speech recognition your inputs are sequences of sounds and you want to produce the corresponding words. Mostly, the word at a particular time step will depend on the the sound at that time step, but sometimes the rest of the sound will influence what word you think it is. So, the word at a particular time step might be hard to guess without looking at the whole utterance. A bidirectional model is an RNN where you first have a layer of recurrent connections running forward and then another layer above it running backward. That means that you have information from both the past and the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*YUWoLz5l4kTxDfka8ieQ4Q.png" /></figure><h3>Sequence to sequence</h3><p>We’re going to talk about how we can use recurrent neural networks to solve some interesting problems; we will focus on how we can train and utilize sequence to sequence models.</p><p>Recurrent neural networks are very flexible and can be used to solve a wide range of different types of sequence processing problems:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*qbVaBmcmBjCk9v_UY0xh0A.png" /></figure><p>In this article, we’re going to focus on the many to many problems. Before that, let’s discuss how we can build a basic neural language model, which assigns probabilities to sequences representing text. Language models are a very important concept for a lot of what we’re going to discuss, because they can not only assign probabilities but they can also oftentimes generate text.</p><p>Here is an example of a neural network model that generates phrases. The training data for this would be a large collection of natural language sentences. Here I’m showing just three:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*22XWZxDfwAJCTAlAsclZag.png" /></figure><p>How are they represented? There are a few choices here and we’ll go into a lot more depth later on, but a very simple choice is to tokenize each of the sentences — which means that every word becomes a separate time step — and then encode that word in some way.</p><p>A very simple way to encode the word is a one hot vector. A one hot vector is just a vector of length equal to the number of possible words in the dictionary and every element in that vector is zero, except for the element corresponding to the index of the word, which is set to one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*8tc1dkJG2XL2DUhYBULoCg.png" /></figure><p>There are more complex ways to represent words. One example is a word embedding, which is a continuous vector-valued representation of words that is meant to reflect their semantic similarity — so that words that mean similar things are located closer together in terms of the euclidean distance.</p><p>For now, let’s just say that words are one hot vectors, which means that our natural language training data just consists of sequences of these one hot vectors</p><p><strong>A few details</strong></p><ul><li>We need to understand when the model is done outputting a sentence. For example, if you give the model “I” and you want it to complete the sentence with “I think therefore I am”, how do you know that you should stop at “m”? “I think therefore I am a hippopotamus” is also a valid sentence. We’ll thus include a special token in the training data at the end of all of our sentences. This is the end of sequence token, sometimes referred to as end of sentence token. It doesn’t represent any actual word, it just represents the fact that the model is done.</li><li>We need to somehow kick off the model. For the second time step, it will use the output of the first time step as input. But what do we use at the very first time step? We could simply compute the frequency with which each sentence starts a word, sample from that randomly and then feed that as the first time step into the model. A slightly more elegant solution, which doesn’t require us to have a special component, is to introduce a start of sentence token. The model will thus learn that it should output a random word with probability proportional to the probability of actually starting a sentence.</li></ul><p>With these start tokens and end of sentence tokens, we know how we can get RNNs to generate completely random sentences. But if we want an RNN to complete a sentence, for example “I think”, doing this does not require changing the training procedure at all. We still feed in the tokens one at a time. You feed in “start”, you let it make a prediction but then you don’t sample from that prediction; instead, you directly feed in the next word that you’re conditioning on, which is “I”. Then, you let it make some prediction, you ignore it and then you feed in “think”, make some prediction and then you actually sample from that and feed that as input to the fourth step. <strong>All you have to do in order to condition your generation on a particular starting snippet is to just force those first few inputs to agree with that snippet regardless of what the network was outputting.</strong></p><p>A conditional language model</p><p>So far, we discussed unconditional language models; now, I’m going to talk about how we can build conditional language models. For these conditional language models, the text is the output of the model, not the input. You’re going to condition this model on some input that’s going to tell it what text you want it to generate. For example, you could imagine a conditional language model for image captioning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*YRS693wPfsHqF6wTRTClPg.png" /></figure><p>We can have some kind of encoder model, read in the conditioning information (the picture of the puppy) with a convolutional network, which will produce a vector representing the starting state of the RNN. This vector, a0, is the initial state of the RNN. This whole thing will then be trained end-to-end — the CNN and the RNN together will be trained together to produce the correct text.</p><p>To summarize, this is one big neural network that consists of a few convolutional layers, maybe some fully connected layers, one of which goes into an RNN. We refer to the RNN part of this network as a RNN decoder, because its job is to decode the information contained in a0 into english text; we call the convolutional part a CNN encoder, because its job is to take the input and encode it into a0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*F7028jUHKS-IYz9uk1M1VQ.png" /></figure><p>Our training data is going to contain pictures and it’s going to have labels.</p><p>If, for example, you want to translate French into English, you could have an RNN that reads in French text and produces the initial hidden state activations for another RNN that produces English text. Now, instead of a CNN encoder, you have an RNN encoder and whatever happens at the last step of the French sentence goes directly to the first step of the English sentence.</p><p>There are a few details to get this to actually work. First, sometimes people read in the input sequence in reverse, starting at the end of the sentence and then going backwards. The reason why this is better is that the beginning of the English sentence probably has more to do with the beginning of the French sentence than with the end of the French sentence. By reversing the input sentence, the first part comes last, which puts it closest to the first part of the output sentence.</p><p><strong>Sequence to sequence models</strong></p><p>We have two different RNNs for the input and the output; encoder and decoder have different weights and the encoder produces the initial hidden state activation for the decoder. This is a more realistic example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*YZCXQQ3Y0zlmVh4t9BnYoQ.png" /></figure><p>1 We read in the input sentence backwards and <br>2 We added multiple layers; multiple LSTMs (between two and five) are stacked on top of each other <br>3 The net is trained end-to-end on pairs of sequences<br>4 The sequences can be of different lengths</p><p><strong>Performing the decoding</strong></p><p>So far, the obvious way of getting a sentence from one of these RNNs is to do it one step at a time and then on the first step we have to output something, we get a softmax distribution. This means we get some vector of length equal to the number of possible words, you apply a softmax to it and that turns it into a vector of probabilities. That’s a probability distribution over the first word in the decoded sentence. The obvious thing to do at this point might be to pick the word with the largest probability and and then you feed that chosen word as the input at the next time step. This way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*Quxf_zujRlVc4nBcqDqoXA.png" /></figure><p>But notice that the network made a small mistake. On the first time step, it had a couple of possible words to choose from (of course, in a simplified scenario) and the correct word would have been “a”, but the word “one” had a similar probability, that was a little bit larger, because the French word “un” could mean both words. This seems a reasonable choice, but it ends up throwing off the rest of the decoding. It picks the word “puppy” for the second one, but “one puppy cute” is not a correct English sentence. So, the network chooses “is”, which produces a valid English sentence… But is not the correct translation.</p><p>So, what went wrong? The problem is we committed to selecting “one” before seeing the rest of the decoding. That first mistake, which was not that unreasonable, led to a completely unreasonable result. If instead of selecting “one” on the first time step, we had selected “a”, then we would have got a pretty reasonable generation later on. By choosing “a”, the probability for “puppy” at the third time step would have been way higher.</p><p>Here, probabilities depend on the entire input sequence and on all of the previous words that we generated for the output sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*ZJUHqlcNgB7-Gy0hTElB2g.png" /></figure><p>The idea is <strong>we want to maximize the product of all the probabilities</strong>, which allows us to get the most likely output sequence out of our decoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*h0_RsL3I1oEOK6387wbKvw.png" /></figure><p>Since dealing with products of lots of probabilities is annoying, we prefer expressing them in log space, where products become sums:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*h1ei5u8umNXzz3Wit9zbrw.png" /></figure><p>In order to maximize the product of all the probabilities, we should not just greedily select the highest probability on the first step. That means that we might choose a word early on with a slightly lower probability for the sake of getting a word later that has a much higher probability: it’s not always optimal to greedily pick the most likely word.</p><p>How many possible decodings are there? For M words, there are M ^ T sequences of length T. If we have only four tokens at every step, in principle we could select any of these four tokens on the first time step and any of these four tokens on the second step and any of these four tokens on the third step and so on. Of course, most of those sequences would have very low probability, but in principle any one of them could be the optimal one. Fundamentally, decoding is a tree search where the cost of a transition is the negative of its log probability (because in tree search you sum up the cost as you go) and the number of search paths increases exponentially. We could use any tree search algorithm to solve this problem, but exact search in this case is very expensive, because this problem doesn’t really have a nice structure that makes things like breadth first search and depth first search work really well. Fortunately, the structure of this problem makes some simple approximate search methods work very well.</p><p>The basic intuition, based on what we know about sequence decoding, is that while choosing the highest probability word at the first step may not be optimal, choosing a very low probability word is very unlikely to lead to a good result — this is not always true in search in general. So, we can’t be greedy, but we can be <strong>somewhat </strong>greedy. This algorithm is called beam search and instead of greedily decoding the best word at every step, it stores the k best sequences so far and then updates each of them. The special case where you set k to 1 is just normal decoding, because you always take the most likely word.</p><p>Here’s an example of beam search with k = 2. There’s a sentence in French that we’re going to translate to English and it’s intentionally chosen to be a somewhat non-trivial translation, in the sense that there’s no perfectly equivalent English word for “entarté”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*KOR_CoFvJ44fVLJ0d7r1ew.png" /></figure><p>Every step of the way, we track the two most likely hypotheses. We begin with a “start” token and we produce the softmax distribution — we run our RNN forward one step, produce a softmax distribution over the first word and track two of the most likely hypotheses. We get “he” and “I”. Now, we’ll step the RNN forward conditioned on the word “he” and then we’ll separately step the RNN forward conditioned on the word “I”. For those two forward steps, we’ll have four different softmax distributions over the second word in total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*f18K4uIfufN_CvLVaUk8dg.png" /></figure><p>Then we’re going to calculate the sums of the log probability for the top two words when we stepped with “he” and for the top two words when we stepped with “I”. We now have four scores and we take the best two: “I was” and “He hit”. We’ll keep expanding those two further:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*5AeIU6qUv9OAWfMnvv-oyg.png" /></figure><p>And again, same as before. When do we stop decoding? Quite simply, if one of our scoring hypothes ends with the END token, we stop expanding it and save it there. We would continue until either some cutoff length or until you have some predefined number of completed sequences. At the end, which sequence do we pick?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*FRi47ldH7VNgsaWK9HPoOg.png" /></figure><p>Remember that each of these scores is a sum of the log probabilities of every step, but the number of steps is different in every sentence. The longer the sentence, the more of these negative numbers we’re adding up, which means that in general longer sentences are going to tend to have lower log probabilities: in order to avoid that short but bad translations get chosen more often than longer and good translations, we actually define a score as the total log probability divided by the number of steps.</p><p>In summary, that’s beam search and it will do a really good job of decoding the most likely sentence most of the time. In fact, oftentimes very small values of k can work well, so 5 to 10 is pretty typical but even numbers as low as 2 might sometimes work well.</p><p><strong>Attention</strong></p><p>Here, I want to briefly introduce the notion of attention for sequence to sequence models. This stems from the fact that in sequence to sequence models we have the bottleneck problem: all the information about the source sequence has to be contained in the activations at the beginning of decoding. The decoder doesn’t know anything about the source sequence, except what the encoder puts into the first hidden state. That can be a big problem when the input sequence is very long.</p><p>Maybe we can relax this a little bit if we allow the decoder to peek into the input sequence a little bit more while it’s decoding. If your input is an entire paragraph and the encoder encodes the general gist of it, we want the decoder to get to that point and reference back into the input sequence in order to pull out the specific token it is interested in. This would greatly reduce the importance of the bottleneck and it’ll be much easier to deal with very long sequences.</p><p>The basic idea is that:</p><ol><li>While encoding, we’re going to have each step of the encoder RNN produce a little piece of information that describes what is present at that time step. This piece of information will not be semantically meaningful to us, it will just be a little vector of activations that doesn’t mean anything in isolation. It will be called “key” and is going to be learned as part of the learning process.</li><li>While decoding, we’re going to have each step of the decoder RNN output a little vector of the same length that we call “query”. Intuitively, it represents the type of information that we need at this time step.</li><li>We compare the query vector to each of the keys to find the one that is the most similar and that will tell us which time step in the input is the most relevant for this time step in the decoding process. Then, we will send that information to the decoder.</li></ol><p>Some crude intuition for what this might do is that one key might encode some notion of what is going on there in the sentence, like “this word is the subject of the sentence”; if the query encodes some notion like “I need to know the subject of the sentence”, then the aforementioned key will get selected because it is the most similar to the query. We then take the corresponding time step, take its hidden state and feed it into the decoder.</p><p>Critically, we don’t have to specify any of these things manually. This whole network will still be trained end-to-end and the actual content of the keys and queries will be determined by the neural network — just like the filters in a convolutional net have some kind of intuitive meaning but are not specified by hand.</p><p>In practice, I’m going to use the letter h to denote the hidden states for the encoder. I’m going to use the letter s to denote the hidden states for the decoder. For the key, I’m going to use the letter k; there’s a separate key at each time step and the key is some function that we apply to the hidden state of the RNN. It could be for example just a linear layer followed by a non-linearity and very often in practice the function k is just a linear transformation. For the query, I’ll use the letter q to denote it, with the subscript l instead of t. For the query, I’ll use the letter q to denote it, with the subscript l instead of t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*NHtQ0ER8WwqfFgVh-yU6iw.png" /></figure><p>The attention dot product “e” is a score that denotes how similar a key is to a query. It will be given by the dot product between kt and ql and we want to pull out the hidden state ht for the time step t for which the dot product is largest.</p><p>To do so, we’re going to create a vector alpha(l) — obtained with a softmax of the attention dot products:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*QJdgC5GZ7o0YewFmhyMrYQ.png" /></figure><p>The larger the attention dot product, the closer this softmax becomes to a arg max. Then, if we want to send the key that roughly corresponds to the largest dot product, we’re going to use alpha in a weighted sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*Iad6xmvCy1g4oK0CmaFJ3A.png" /></figure><p>Intuitively, these alphas will be small numbers for all time steps t except for the one that has the largest dot product; this weighted sum will therefore be dominated by the activation corresponding to the arg max of the dot product.</p><p>The intuition is we’re trying to pull out the encoder RNN state for the time step t corresponding to the largest dot product between the key and the query. The reason we call this attention is that the network is trying to pay attention to the most relevant part of the input. To summarize, for a specific query qt:</p><ol><li>The keys are learned from the hidden states of the encoder, “h”, for example with a linear layer</li><li>The attention scores “e” are produced by dotting the keys with that query</li><li>We apply a softmax to all the dot products “e” and we call the results “alphas”</li><li>The largest alpha gets sent to the decoder</li></ol><p>What does it mean to send alpha to the decoder? Alphas can be used in different ways by the decoder.</p><ul><li>Give it to the function that produces the output, so that the output becomes a function of both decoder state and the encoder state corresponding to the highest attention score</li><li>Give it to the next RNN layer, if you’re using a multi-layer or stacked RNN</li><li>Give it to the next decoder step, so that the attention vector serves as an additional input along with, for example, a new word</li></ul><p><strong>Attention variants</strong></p><ul><li>One simple choice is to use k and q to be identity functions. In this case the key at timestep t is just ht and the query at timestep t is just sl. When you’re decoding, your attention score is the dot product between the input hidden state and the decoder hidden state. It’s very easy to implement, but it can have somewhat limited expressivity</li><li>Another really simple choice is to use a linear multiplicative attention where key and query are just linear functions of the hidden state. This is very reasonable, because the RNN hidden state is already formed by applying a non-linear function. Therefore, this doesn’t diminish our representational capacity very much</li><li>The last variant is a little more complex. It still has keys and queries, but at the end, when you construct your attention vector, you don’t construct a weighted combination of the encoder hidden states, but instead you construct a weighted combination of those hidden states transformed by some learned function v. V here stands for “value” and the interpretation is that during encoding you produce key-value pairs, whereas during decoding you find the time step of the largest product between k and q and you take its value. This can give a bit of added flexibility.</li></ul><p><strong>Summary</strong></p><ul><li>Every encoder step t produces a key kt</li><li>Every decoder step l produces a query ql</li><li>The decoder gets sent the encoder activations ht that correspond to the largest value of the product kt and ql</li><li>Attention is very powerful, because all decoder steps end up being connected to all encoder steps</li><li>Gradients are better behaved, because the number of jacobians that get multiplied together along the attention route is O(1). This becomes very important for very long sequences</li></ul><h4><a href="https://www.youtube.com/watch?v=VDnEnlYzHOU&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=36">Transformers</a></h4><p>Previously, I have talked about how we can build sequence to sequence models and improve their ability to handle long-range dependencies by using an attentional mechanism.</p><p>Here, we’re going to talk about another class of models for processing sequences that does not use recurrent connections, but instead relies entirely on attention. We’ll build towards a class of models called transformers.</p><p>The basic question is: can we get away with using attentional connections without any explicit recurrence? In principle, attention can grab any information you want from the input string and our RNN can be transformed into a purely attention-based model. But with a few caveats:</p><p><strong>If we do this naively using the basic attention mechanism, we can access the hidden states of the encoder, but not previous states of the decoder.</strong></p><p>To fix this issue, we use self-attention. We’re going to take all of the time steps of our sequence and we’ll encode each time step. This is like a feed-forward model. H1 is some function of x1; h2 is some function of x2; h3 is some function of x3. The weights are shared at all time steps because the function is the same in each case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*ZKrtMuWsJxWyuUtWydDq2g.png" /></figure><p>Then, we’re going to produce a value for each time step, where vt is some linear function of ht:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*1lEQLDKQsOW9cBDTU-gxnQ.png" /></figure><p>We are also going to output a key, where the key is some linear function of ht:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*9WNvXy1C8inAn_Gfd9cxwQ.png" /></figure><p>And then, every timestep is also going to output a query; it’s as if we had encoder and decoder together. So far, we’ve got a key, a value and a query and all of them are linear functions of ht.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*5ODt_hu7GiQmKyJ6gq7-vQ.png" /></figure><p>Then, we’ll do exactly what we did with attention before, except that now there’s no distinction between an encoder and decoder. Essentially, every step can index into every other step including itself.</p><ol><li>We’ll compute dot products between every qt and every kt and those will give us our attention scores</li><li>We’ll pass each of them through a softmax and we’ll get alpha values</li><li>Then, we take the values at every step, we weight them by the alphas and that gives us the attention</li></ol><p>This self-attention mechanism has produced an attention vector at every time step. You can think of this as a layer that integrates information across the time steps. We could repeat this process more and more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*ebPJU2-jRlTaSjyt7i1tSA.png" /></figure><p>The actual process of turning this into a viable model requires a number of additional steps. The basic concept of self-attention can be used to develop a powerful type of sequence model called a transformer, but to make this actually work we need to develop a few additional components and address some fundamental limitations of self-attention.</p><p>Here are the things we need to take care of:</p><ul><li><strong>Positional encoding </strong>addresses an issue with self-attention which is that self-attention does not have any notion of proximity and time. All those x’s were processed entirely in parallel, without any regard for their order. If we had switched their order, the self-attentional layer would produce exactly the same answer. That can be a big problem when dealing with data like natural language, where the order of the words actually matters</li><li><strong>Multi-headed attention </strong>allows querying multiple positions at each layer; at each layer we don’t just have one value in query and key, but we can have multiple — so that we can do more complex operations. Crudely, you can think of a (key, value, query) tuple as a filter in a CNN; in practice, you would never build a CNN with just one filter per layer and in the same way you don’t want to build a pure self-attention model with just one attention head per layer</li><li><strong>Adding nonlinearities</strong>, because the model that we have discussed so far is entirely linear.</li><li><strong>Masked decoding</strong> prevents attention lookups into the future. Right now, the attention mechanism doesn’t distinguish between past and future. That can be a very bad thing when you’re trying to use self-attention for a language model to decode</li></ul><h3>From self-attention to transformers</h3><p><strong>Positional encoding</strong></p><p>What we see when we see some sentence involves both the words in that sentence and the order in which those words occur. If for example we have the sentence “he hit me with a pie”, what naive self-attention sees is just a bag of words. If you were to permute the words, you would get exactly the same attention vectors — whereas a recurrent model looks at the words one at a time and it remembers which words it saw before. In general, the position of words in a sentence carries important information and we would very much like to preserve that information when using our self-attention model.</p><p>To solve this, we are going to add some information to the representation at the beginning that indicates where it is in the sequence. Positional encoding just means that this first ht is going to be some function of xt as well as t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*uoRUzkvYItXzMaystgzkXQ.png" /></figure><p>That is going to preserve the order of the tokens in the sequence and allow self-attention to make use of that. Simply appending t to the input x would not be ideal, because absolute position is less important than relative position. If I give you two sentences (“I walk my dog every day” and “every single day I walk my dog”), the important piece of information is the index of the word dog relative to the word walk, not the index of the word dog by itself.</p><p>We could come up with a positional encoding that pays more attention to relative positions than it does to absolute positions. We want to represent position in a way that tokens with similar relative position have similar positional encoding. For example, instead of appending the actual time step, we could append frequencies of the time step. The positional encoding could be a vector of the same length as the embedding of xt; every entry in that vector is a sine or a cosine applied to the time step t divided by some frequency:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*tST5pM4zzpJNzXEOiAgqjw.png" /></figure><p>The earlier entries have very high frequencies, because it’s t divided by some small number; at the end of the vector they have very low frequencies, because it’s t divided by a big number, like 10.000. If you were to draw a picture of these positional encodings, this is what they’d look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*HYezuON1FxpJ5lXagK_63A.png" /></figure><p>Every row here is a different dimension of this positional encoding vector and every point horizontally is the index in the sequence. This frequency domain encoding is very good for getting relative positions.</p><p>However, we could have more sophisticated positional encoding. For example, we could learn it. We could learn the entire matrix I showed above, making the entries in the matrix learnable parameters of our model</p><p>At every position we have an x and that’s different for every input sequence; at every position we also have a p and that’s the same for every sequence, but it’s learned — so it’s a different p at every time step, but p1 for one sequence is exactly the same as p1 for a different sequence, so it’s just a learned constant. This has the advantage of being more flexible and perhaps more optimal in some sense than the sine-cosine encoding, because we do end up learning the positional encodings that work best for our sequence model. The downside is that it’s a little bit more complex and you need to manually pick the maximum sequence length</p><p><strong>How do we incorporate these positional encodings into our self-attention model?</strong></p><p>At each time step, we’re going to have our input xt and our positional encoding pt. Transformers usually embed the input first and they add the positional encoding to that embedding. So the encoding is just the embedding of xt plus the positional encoding pt. That’s an arbitrary choice, you can combine them in any other way.</p><p><strong>Multi-head attention</strong></p><p>Since we’re relying entirely on attention now, it might be desirable to allow the self-attention mechanism to incorporate information from more than one time step. For example, if at position two you need verb and subject of the sentence in order to combine them, it would be cool to have an attention mechanisms that provides the subject and another one that provides the verb.</p><p>The way that you can do this is you can have multiple keys, queries and values at every step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*lF6kYzwB-d8-xQH9-bC2Nw.png" /></figure><p>The different color outlines represent different heads. Each of these heads produces an attention score and the weights are computed independently for each head. At the end, a full attention vector is formed by stacking the three heads. And maybe one of those heads pulls out a subject, one pull out an adjective, one pulls out a verb and so on.</p><p>It’s a really good idea to build self-attention with multiple heads per self-attention layer — oftentimes, something around eight heads seems to work pretty well for big models</p><p><strong>Adding nonlinearities</strong></p><p>So far, self-attention is entirely linear in the values, because our keys, our queries and our values are linear functions of ht. Each self-attention layer has a different set of weights. Then, our alphas are calculated by applying a softmax, which is a non-linear operation, but the actual attention is obtained with a linear combination of the values weighted by those softmax scores. So, the attention is linear in the v’s and the v’s are linear in the h’s. This means that every self-attention layer is a linear transformation of the previous layer with nonlinear weights and this is not very expressive.</p><p>One very simple way to add nonlinearities is to simply alternate self-attention with some kind of non-linear layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*-UaerpEykRcsINx2l_CM8w.png" /></figure><p>This position-wise nonlinear function processes the information, whereas the self-attention layer is the memory fetch.</p><p><strong>Masked decoding</strong></p><p>The trouble with self-attention is that it doesn’t distinguish between past and future; instead, you would like to have the first time step only use information from the first step to generate the output, then you want to use that output as an input to the second step, which can then process that information (including information from the first step) and then produce the output of the second step, and so on.</p><p>The problem is that we have a circular dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*xFDTCrEQg5pIMomD5JV7tw.png" /></figure><p>While encoding, self-attention at step 1 can look at the value at steps 2 and 3, which is based on the inputs at steps 2 and 3. At test time, the inputs at steps 2 and 3 will be based on the output at step 1, which requires knowing the input at steps 2 and 3.</p><p>There’s a very simple fix that we can use to remove this problem, which is called masked attention. You have to allow self-attention into the past, but not into the future:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*djjMplwLs3egFg7k67bioA.png" /></figure><p>Mathematically, to compute the attention scores, you do the same as before only if the key comes before the query, otherwise you set the attention score to negative infinity. This way, when you put it into the softmax, e to the negative infinity is zero and future time steps will always have a weight of zero and never be used. In code, dealing with infinities is annoying, so you directly set the exponential to 0.</p><p><strong>Summary</strong></p><p>We can implement a practical sequence model, based entirely on self-attention and if you incorporate the four modifications that we described, the sequence model will work.</p><ul><li>You have to alternate self-attention layers with non-linear position-wise feed-forward networks to get non-linear transformations</li><li>You have to use positional encoding on the input or input embedding to make the model aware of the relative position of the tokens relative to each other in the sequence</li><li>You have to use multi-headed attention so you can incorporate information from multiple different time steps at each self-attention layer</li><li>If you want to use the model to decode, you have to use masked attention to prevent peaks into the future.</li></ul><p><strong>Transformers</strong></p><p>We’re now going to combine the pieces that we’ve learned about so far to go through the classic transformer model.</p><p>The model designs that use successive self-attention and position-wise non-linearity to process sequences are generally referred to as transformers, because they transform one sequence and another at each layer using these self-potential mechanisms.</p><p>A sequence to sequence RNN model has an RNN encoder and an RNN decoder. These can in general have multiple layers. To make this into a transformer we will replace the encoder and the decoder with successive self-attention layers, alternating with position-wise non-linear transformations.</p><p><strong>The encoder </strong>is going to get a sequence of x’s, with corresponding positional encodings p1, p2 and p3. At every position we will encode these, then we’ll pass them into a self-attention layer. Then, we will take the output of this multi-headed potential and pass it into a position wise nonlinear network. This is repeated n times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*oDItKXKFbe8hXeq3LJFTPA.png" /></figure><p><strong>In the decoder </strong>we’re also going to have a position-wise embedding of the output steps and their corresponding positional encodings. We’ll use masked attention, which means that earlier time steps don’t get to look into later ones. Then, we’ll have a position-wise non-linear network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*rsJfa510WIJxC-e07amOzA.png" /></figure><p>Then, we’ll have cross attention, which uses all of those hidden vectors produced by the encoder. This is very much like the classic attention that we described in the previous lecture, so instead of self-attention which looks at other time steps in that same sequence, cross attention is going to look at the time steps in the encoder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*Nz4af-4SanJ5tHCj0Irl8A.png" /></figure><p>After cross attention, we have another position-wise nonlinear network. This means that every decoder layer has two attention steps: it has a masked self-attention, a non-linear function, cross attention, another non-linear function and then that goes into the next block. These blocks are also repeated n times, so the decoder blocks have twice as much stuff going on as the encoder blocks</p><p>At the very end, after n blocks like these, we apply a softmax at every position and read out the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*BvJgnNXEOipK3S98JlKPag.png" /></figure><p>Let’s look more closely at the cross-attention mechanism, which is a little subtle.</p><p>We’re going to use ht with superscript l to denote the hidden states of layer l in the encoder and sl superscript l to denote the hidden states l in the decoder . These states are produced by the position-wise nonlinear network. In cross-attention, we have:</p><ul><li>A query, which is obtained by applying matrix Wql to the output of position-wise nonlinear network at decoder layer l, step t</li><li>A key, which is obtained by applying matrix Wkl to the output of position-wise nonlinear network at encoder layer l, step t</li><li>A value, which is obtained by applying matrix Wvl to the output of position-wise nonlinear network at encoder layer l, step t</li></ul><p>Then, we compute an attention score between every t and l, we apply the softmax and then we compute our cross-attention.</p><p>In reality, cross attention is also multi-headed. Before presenting the real transformer model, there’s one more little detail: layer normalization.</p><p>Layer normalization does not have anything to do with attention models, but it turns out to be important for the transformer because it’s difficult to use regular batch normalization with it. The main idea is that batch normalization is very helpful, but it’s hard to use it with sequence models for a few reasons:</p><ul><li>Sequences are different in length, which makes normalizing across the batch kind of hard</li><li>Sequences can be very long, so we sometimes have very small batches</li></ul><p>A simple solution that we can use is to replace batch normalization with something called layer normalization, which is like batch normalization but across different activations in a layer rather than across different samples in a batch. In standard batch norm, at every layer, you have a bunch of activation vectors, one from every input; batch norm computes a mean and a standard deviation over all of the points in that batch. Then, when you transform them with batch normalization, everything is per element and for every element you subtract the corresponding element of the mean, divide by the corresponding element of the standard deviation, multiply by the corresponding element of gamma (which is the learned scale) and add the corresponding element of beta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*SQ2Et9EUY83dlYS3s9LOwQ.png" /></figure><p>Layer norm is going to be a more traditional layer, it just uses information within a single data point and instead of computing the mean over different vectors in the batch, it computes a single number by averaging together the activations for every dimension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*vb7Hy97gKqFEfC3BUsXRBA.png" /></figure><p><strong>Putting it all together</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*3mg3JmhG8TtX0OLdfjT1yg.png" /></figure><p>This image is taken from the paper that introduced the transformer, called “Attention is all you need”. What this paper proposed is to use successive self-attention and position-wise non-linear functions to implement a sequence to sequence model — which they apply to machine translation.</p><p><strong>Encoder</strong></p><ul><li>We start off by taking our input sequence, separately embedding every token in that input sequence and adding the corresponding positional encoding to that embedding</li><li>Then we have our first multi-headed self-attention layer</li><li>You concatenate the attention from all the heads to get alpha at every position</li><li>Then you have this thing called “Add &amp; Norm”, which is a residual connection followed by a layer norm. The reason is that they want every layer to be a modification, with the benefit of well-behaved gradients that you get from residual connections</li><li>Then you have a position-wise non-linear function. In particular, it consists of a linear layer, then a ReLU and then another linear layer.</li><li>Then there is another “Add &amp; Norm”</li></ul><p>They have n of these blocks; each block is multi-headed self-attention, add &amp; norm, position wise non-linearity, add &amp; norm, pass it to the next block, multi headed self-attention, add &amp; norm, position wise non-linearity, add &amp; norm, pass it to the next block and so on.</p><p>That’s the encoder. Once you’ve run the encoder all the way forward, you will have computed six of these blocks. The product of the encoder is these keys and values</p><p><strong>Decoder</strong></p><ul><li>The decoder has the same kind of positional encoding business and then for each encoder block there’s a corresponding decoder block — but the decoder blocks are a little more complex. Now, the multi-head attention is masked and only looks at past time steps, because it is going to be used to generate a sequence.</li><li>Add &amp; norm</li><li>There’s a cross attention that produces queries based on the output of the self-attention. Those queries are used to look up the keys and values from the encoder.</li><li>Again, there is an add &amp; norm. This add &amp; norm will add together the results of cross attention and self-attention.</li><li>Then you have a position-wise nonlinear function, which uses the same architecture but different weights as the encoder</li><li>Then you have another add &amp; norm</li><li>Then you pass them to the next block</li><li>At the end of the last block, there’s a linear layer at every position followed by a softmax, which outputs a probability distribution over the token at that position</li></ul><p>The decoder decodes one position at a time with masked attention</p><p><strong>Why transformers?</strong></p><p>A few pros and cons of transformers:</p><ul><li>The attention computation is technically O of n squared, although this is not as big of a problem as it seems because most of the computation time is not spent performing those dot products, but on all the other parts of the network. In practice, in terms of computational cost, oftentimes transformers are actually a lot cheaper than RNNs</li><li>They are somewhat more complex to implement and involve a variety of seemingly weird decisions, like positional encodings which can make them a little tricky to work with. It can take a fair bit of hyperparameter tuning to get transformers to train well</li><li>They have much better long range connections: every position in the output is connected to every other output position and every other input position with a jump of length one. Computationally, implementing a transformer on parallelized hardware like GPUs makes them run much faster for our ends</li><li>In practice, you can make transformers much deeper than stacked RNNs.</li></ul><p>In general, the benefits of transformers seem to vastly outweigh the downsides and transformers work much better than RNNs and LSTMs in many practical sequence to sequence processing cases.</p><h3>Generative modeling</h3><p>The central idea of generative modelling stems around training a generative model whose samples x ∼ pθ(x) come from the same distribution as the training data distribution, x ∼ pd(x).</p><p>Consider a medical diagnosis problem in which we have taken an X-ray image of a patient, and we wish to determine whether the patient has cancer or not. Generative modelling first solves the inference problem of determining the class-conditional densities p(x|Ck) for each class Ck individually. Also, it separately infers the prior class probabilities p(Ck). Then, it uses Bayes’ theorem in the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*oZyj46mAFLSfksPzyEIcvw.png" /></figure><p>Equivalently, we can model the joint distribution p(x, Ck) directly and then normalize to obtain the posterior probabilities. Having found the posterior probabilities, we use decision theory to determine class membership for each new input x. Approaches that explicitly or implicitly model the distribution of inputs as well as outputs are known as generative models, because by sampling from them it is possible to generate synthetic data points in the input space.</p><p>While the range of applications to which generative models have been used continue to grow, we can identify three fundamental inference queries for evaluating a generative model:</p><ol><li><em>Density estimation:</em> given a datapoint x, what is the probability assigned by the model, i.e., pθ(x)?</li><li><em>Sampling:</em> how can we <em>generate</em> novel data from the model distribution, i.e., xnew∼pθ(x)?</li><li><em>Unsupervised representation learning:</em> how can we learn meaningful feature representations for a datapoint x?</li></ol><p>This is a taxonomy of generative models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4g4DUDQkuZMdlwsFDLrQw.jpeg" /></figure><p>Specifically, we will discuss four generative models:</p><ol><li>Autoregressive Models</li><li>Variational Autoencoders</li><li>Normalizing Flow Models</li><li>Generative Adversarial Networks</li></ol><h4>Autoregressive generative models</h4><p><em>Autoregressive generative models implicitly define a distribution over sequences using the chain rule for conditional probability, whereby in each step the distribution of the next sequence element is predicted given the previous elements</em>. The main principles for training autoregressive generative models are:</p><ol><li>We divide up x into its dimensions x1, …, xn</li><li>We discretize each of these dimensions into k values (for example, when we’re generating images, the image pixels are naturally discretized into 256 values because pixels can only take take on 256 different colors)</li><li>We represent the full joint over all the pixels or over all the dimensions of x by the chain rule</li><li>Use your favorite sequence model to actually model this p(x)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*4oNajS9ImEsL1h6lStlZFQ.png" /></figure><p>Using autoregressive generative models:</p><ul><li>Sampling</li><li>Completion</li><li>Representations</li></ul><p>Let’s walk through one popular class of models in this category, that is specific to autoregressive generative modeling of images. This is called “PixelRNN”; the idea is that we’re going to generate the pixels one at a time, left to right, top to bottom in scanline order. So, the probability of the whole image is given by the product over all the pixels and each pixel depends on its predecessors, which are defined as all preceding scan lines and all preceding pixels to the left of the current pixel in the current scan line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*OZ4vM7k7KWbjdZGEVaeGHg.png" /></figure><p>Each pixel consists of three color channels, so we also have to generate one color channel at a time — there’s actually a small network for every pixel that generates the red color given all the previous pixels, then the green color given all previous pixels and this pixel’s own red color and then generates the blue color given all previous pixels and this pixel’s red and green color. And then every color channel is a 256-way softmax, so every color channel’s brightness can take on 256 possible values.</p><p>With this model, once you’ve trained it, you can give it for instance the top half of an image and it can complete different random realizations for the bottom half.</p><p>Some practical considerations:</p><ol><li>It is quite slow, because while the basic recipe is the same as a language model, if the image is 32 by 32 pixels, that means that there are about a thousand pixels in that image — so that would be like a sentence of a thousand words. Plus, each pixel itself has three color channels, so that raises it to 3000.</li><li>Generating the image row by row like this might fail to capture some of the spatial context that is present in images, because the pixels that are located right above in the scan line are considered to be far away in the RNN ordering.</li><li>There are many practical improvements and better architectures that are possible to improve PixelRNN (PixelCNN, PixelTransformer, …).</li></ol><p><strong>Conditional autoregressive models</strong></p><p><em>Conditional autoregressive models solve this problem: what if we want to generate something that is conditioned on another piece of information?</em></p><p>For example, we could generate images of specific types of objects or we could have a conditional autoregressive model for imitation learning that generates distributions over actions.</p><p>The recipe is very similar to a conditional language model; you have some something that you’re conditioning on, which we will call “context”. The context is processed using some kind of encoder network, which could be just a feedforward model, a CNN, or another RNN and that is used to start the first time step of the autoregressive generative model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*jz0kZ3BZuFH58f7IeS08qA.png" /></figure><p>The encoder could be extremely simple, if for example you’re generating images of a class, or it could be very complex, if for example you represent the policy in imitation learning.</p><p>To sum up:</p><ul><li>While autoregressive models are extremely powerful density estimators, sampling is inherently a sequential process and can be exceedingly slow on high dimensional data. Additionally, data must be decomposed into a fixed ordering; while the choice of ordering can be clear for some modalities (e.g. text and audio), it is not obvious for others such as images and can affect performance depending on the network architecture used.</li><li>Autoregressive generative models are basically like language models, but for other types of data — although it’s more accurate to say that language models are just a special type of autoregressive generative model. In other words, the notion of an autoregressive generative model is actually more general than a language model</li><li>You can represent autoregressive models in many different ways (RNNs, LSTMs, PixelCNNs, Transformers, …)</li><li>There are some interesting trade-offs for these models compared to other models we’ll talk about later. <em>One really good thing about these kinds of autoregressive generative models is that they provide full distributions with probabilities, so they will assign a probability to every possible x and those probabilities are easy to get</em>. The downside is that they are slow for large datapoints (like images) and generally limited in image resolution.</li></ul><p>To summarize, some pros of pixelRNNs and pixelCNNs:</p><ul><li>They allow you to explicitly compute likelihood P(X). It’s an explicit density that we can optimize.</li><li>Being able to do this also has another benefit of giving a good evaluation metric. You can measure how good your samples are by this likelihood of the data that you can compute.</li><li>It’s able to produce pretty good samples</li></ul><p>However, this is still an active area of research and the main disadvantage of these methods is that the generation is sequential and so it can be pretty slow.</p><h4>Autoencoders</h4><p>Autoencoders are a very widely used class of models for all sorts of unsupervised learning tasks. Not all autoencoders are generative models; in fact, the autoencoders that we’ll discuss here are difficult to use for generation, but we’ll talk about a special kind of autoencoder called the variational autoencoder that is actually a very good generative model.</p><p>More broadly, <em>an </em><strong><em>autoencoder</em></strong><em> is a type of artificial neural network used to learn efficient codings of unlabeled data (unsupervised learning). The encoding is validated and refined by attempting to regenerate the input from the encoding</em>. The autoencoder learns a representation (encoding) for a set of data, typically for dimensionality reduction, by training the network to ignore insignificant data (“noise”). Variants exist, aiming to force the learned representations to assume useful properties.</p><p>Let’s start with a very very high level view of probabilistic unsupervised learning models, for example things like language models. At a very high level you can think of them as having inputs where the input corresponds to the pixels in the image and the goal is to produce that same image — but in the middle you have some structure that makes this task of reconstructing the image somewhat non-trivial. So, a PixelRNN for instance doesn’t get to look at pixels that it hasn’t generated yet; it has to generate a pixel before it actually sees what that pixel is.</p><p>You can think of this as a general design for generative models: you have some input (which could be an image, a link, a natural language sentence) that goes into a model and that model has a loss, which is to produce the same thing as output. <em>An arbitrary model could just learn the identity function, but some kind of structure is imposed on the model that makes this task of reconstructing the input image not easy and forces the model to learn meaningful representations</em>. Examples of that structure in the middle:</p><ul><li>RNN/LSTM sequence models that have to predict a pixel’s value based only on previous pixels</li><li>PixelCNN models that must predict a pixel’s value based on a masked neighborhood</li><li>Pixel transformer, which makes predictions based on masked self-attention</li></ul><p>All of these models have spatial structure, which has to do with the arrangement of the pixels in the image or the arrangement of the words in the sentence. But can we use more abstract structure once we recognize that all these models basically read in x and then output that same x? More broadly, models that take in some input and then are tasked with producing that same thing as output are called autoencoders and <em>the basic idea behind an autoencoder is to train a network that encodes an image into some hidden state and then decodes that image as accurately as possible from that hidden state.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*vrtaFVjm0lEOasu_QJzO_A.png" /></figure><p>Something about the design of the model or something in the data processing or regularization has to force the autoencoder to learn a structured representation.</p><ul><li><strong>Dimensionality</strong>: make the hidden state smaller (in terms of the number of dimensions) than the input/output, so that the network has to compress it.</li><li><strong>Sparsity</strong>: force the hidden state to be sparse, meaning that most entries in the hidden state are zero, so the network has to compress the input.</li><li><strong>Denoising</strong>: corrupt the input with noise, forcing the autoencoder to learn to distinguish noise from signal</li><li><strong>Probabilistic modelling</strong>: force the hidden state to agree with a prior distribution. This is the approach that we can use to get autoencoders to also be very good generative models.</li></ul><ol><li><strong>A bottleneck autoencoder</strong> relies on the fact that whatever the dimensionality of your input is, you pick the dimensionality of the hidden state to be much smaller. If you have a 100 by 100 pixel image and the hidden state is only 128 dimensions, it can’t possibly learn the identity function, because it can’t store the values of every single pixel in those 128 dimensions. This is very straightforward and it does have some interesting properties. This is a non-linear generalization of principal component analysis, because if both the encoder and the decoder are linear, then training this kind of bottleneck autoencoder with mean squared error for reconstruction exactly recovers principal component analysis — and the dimensionality of the hidden state is the number of principal components that you’re going to get. To sum up, the upside is that it is very simple to implement; the downside is that simply reducing dimensionality often does not provide the structure we want.</li><li><strong>A sparse autoencoder</strong> relies on this basic principle: we can describe the input with a small set of attributes — instead of describing the image of a dog by specifying the color of each pixel, which is not structured and interpretable, you could give a 1 for each property that the dog possesses (ears, wings, wheels, etc.). An interesting property of these kinds of representations is that most attributes will be zero for most images, because there are a huge number of possible objects in the world that do not possess most attributes. That goes hand in hand with the structure; the sparsity principle says that what you want is this kind of attribute dictionary, that is very structured and that tends to be sparse. This is neat, because then the attributes that are present are very specific to that object and they’re very descriptive of it. As an aside, this idea originated in neuroscience, where researchers believe that the brain uses these kinds of sparse representations to represent things in the world (“sparse coding”). Practically speaking, the only thing we really have to do to get a sparse autoencoder is we have to choose a sparsity loss. We’re going to train the sparse autoencoder with backpropagation to minimize some loss function on reconstructing the input, but it will have an additional loss function applied to the hidden state that will encourage that hidden state to be sparse. To sum up, the upside is that it is a principled approach that can provide a disentangled representation; the downside is that it is harder in practice as it requires choosing the regularizer and adjusting hyperparameters.</li><li><strong>A denoising autoencoder</strong> relies on the idea that a good model that has learned meaningful structure should be able to fill in the blanks. If you take an image and you corrupt it in some way and then you ask your model to remove the corruption, then your model will have to learn something about what realistic images look like. To sum up, the upside is that it is very simple to implement; the downside is that it is not clear which layer to choose for the bottleneck and there are many ad-hoc choices to make.</li><li><strong>A variational autoencoder</strong> performs probabilistic modelling: it connects up autoencoders to probabilistic generative models. It also addresses a big problem that other autoencoders have: sampling or generation from them is very hard, which limits their uses. In general, variational autoencoders are meant to compress the input information into a constrained multivariate latent distribution (encoding) to reconstruct it as accurately as possible (decoding).</li></ol><p>Autoregressive models define a tractable density function and based on that we can directly optimize the likelihood of training data. On the other hand, variational autoencoders define an intractable density function with latent z. Our data likelihood p(x) is now an integral over taking the expectation over all possible values of z — however, we cannot optimize this directly.</p><p><strong>Latent variable models</strong></p><p>As an introduction to variational autoencoders, let’s discuss latent variable models first. In statistics, <em>latent variables are variables that are not directly observed but are rather inferred (through a mathematical model) from other variables that are observed (directly measured)</em>. Mathematical models that aim to explain observed variables in terms of latent variables are called latent variable models.</p><p>More in general, let’s say that our distribution p(x) is very complex and we can’t represent it easily. Let’s then introduce another distribution over another variable z; p(z) is just a zero mean unit variance normal distribution. Then, we’ll build our generative model as a probabilistic mapping from z to x. <em>In other words, we are trying to represent p(x) as a composition of two very simple distributions.</em> One of them is p(z), which is just a gaussian; the other one is p(x|z), which is a simple distribution as well, but its parameters are very complex and deterministic functions of z.</p><p>p(x) is now the integral over p(x|z) p(z) dz. All the complex models we will discuss are based on this principle: you have an easy distribution over a very abstract latent variable z and you have an easy conditional distribution over your complicated variable x, but the mapping from z to x are represented by a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*FByRmQIRq625zJzOwDLaDQ.png" /></figure><p><strong>How do we train latent variable models?</strong></p><p>We’re going to have some model pθ(x) and we have a dataset of x’s. We train with maximum likelihood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*Ha6lvx9YT7OetJOzgQHm_A.png" /></figure><p>Since each of your p(x) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*j1qbM32CNEgo3qSCSKS0lQ.png" /></figure><p>We substitute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*4y5izNN2ik8EcdtiK5iBHQ.png" /></figure><p>But this objective is completely intractable, because you can’t integrate over all possible z’s — this integral does not have a closed form solution. Instead, when we train latent variable models, we need to use something a little more manageable: the expected log likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*yYgMQJxnPjbTrpKDR1APvg.png" /></figure><p>Instead of integrating z, we essentially guess what the z is by estimating p(z|x) for every image and then we maximize the probability of that x with that z. But how do we calculate p(z|x)? This is called probabilistic inference.</p><p><strong>Latent variable models in deep learning</strong></p><p>Some variable z has some prior distribution p(z). This prior distribution is typically set to something very simple, because the meaning of z is not fixed; the meaning of z is entirely determined by your model, so you don’t need to learn or design p(z) and you can choose something simple like a zero mean identity covariance multivariate normal distribution. Then, you have a decoder, which maps vector z to distributions over x: this is a neural network.</p><p>Using the model for generation works like this:</p><ol><li>Sample z from p(z): random number generation.</li><li>Sample z from p(x|z): turn that vector of random numbers into an image</li></ol><p>A latent variable deep generative model is usually just a model that turns random numbers into valid samples.</p><p><strong>How do we represent latent variable models?</strong></p><p>The easy part is representing p(z): generating random Gaussian numbers. Representing pθ(x|z) is a bit more complex.</p><ol><li>Option one is to say that your pixels are continuous values; you would represent them as a multivariate normal distribution with a diagonal covariance, which just amounts to saying that every pixel is going to have a mean and every pixel is going to have a variance. Both the mean and the variance of every pixel could in general be functions of z, so they might be the output of a neural network. Very often, we will simplify this and make sigma be a constant — in which case you just get a mean squared error loss</li><li>Another option is to say that your pixels are discrete valued and in that case pixels all depend on z, but conditioned on z they can be seen as independent. This actually very well, but it’s a little bit slow.</li><li>There are other choices (discretized logistic, binary cross-entropy, …)</li></ol><p><strong>What architecture should we use for pθ(x|z)?</strong></p><p>An easy choice for tiny images or for non-image data is to just use a big fully connected network. A better choice for more complex data is to (a) run the z vectors through a fully connected layer to turn them into a lower resolution convolutional map (b) use transpose convolutions and unpooling to get the resolution up until it gets to the full resolution that you want for your final image</p><p><strong>Training latent variable models</strong></p><ol><li>Choice one is to perform inference to figure out p(z|x) for each training image x and then minimize the expected negative log likelihood (this is what variational autoencoders do)</li><li>Use an invertible mapping z to x</li><li>Do not bother getting the z’s for each individual x, but to match the distributions themselves. Basically sample a z at random, sample the x given that z and try to match those samples at the population level to the training data (this is what generative adversarial networks do)</li></ol><p>The way that we’re going to guess the z is by taking an expected value under p(z|xi) for every data point xi in our data set and then we’ll maximize the joint log probability of xi and the z that we guessed. In reality, p(z|xi) is a distribution, meaning that we don’t know exactly which individual z goes with which xi, but we can guess the probability of differences: what we have to do is average over all those possibilities and that’s what an expected value does. The big challenge with this scheme is the way we calculate p(z|xi): we’ve essentially transformed this problem of evaluating an intractable integral into the problem of somehow estimating and then sampling from p(z|xi). This is called probabilistic inference, because we are inferring which z goes with a particular x.</p><p><strong>The variational approximation</strong></p><p>The basic idea behind what we’re going to do is called variational approximation. Instead of actually calculating the real distribution p(z|xi), we’re going to approximate it with some much simpler distribution that’s much easier to deal with. For example, we might just say that p(z|xi) for a particular image xi is some gaussian qi(z) with some mean and variance — and it’s going to be a different mean and a different variance for every image.</p><p>Of course, the real p(z|xi) is not just a gaussian, it might be some really complicated thing — so this is an approximation and perhaps a fairly crude one. <em>The remarkable fact is that for any choice of qi(z) we can construct a lower bound on log p(xi), so the quantity that we’ll work out is not equal to log p(xi)but it but it is less than or equal to it</em>. This means that if we’re trying to maximize log p(xi), we can maximize this lower bound quantity instead.</p><p>Here’s how we can do it: let’s start with the expression for log p(xi) that uses that intractable integral from before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*buP6Yj4YEhG-75nkBhWuOg.png" /></figure><p>Then, we multiply by 1 and rewrite the logarithm as an expected value under qi(z):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*QgQeiG2a12EgsqV3Az-tdw.png" /></figure><p>Now we’re going to apply a mathematical identity that is at the core of variational approximation, which is Jensen’s inequality: it allows us to bound any concave function of an expectation below by the expectation of the concave function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*DUX5chPfwWk-WjC7O7K4xQ.png" /></figure><p>In other words, if you have the logarithm of an expected value, that quantity is always greater than or equal to the expected value of the logarithm. If it’s a convex function, then the inequality goes the other way.</p><p>This is what we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*Q7bobGwFmgle3jMB2gW2-g.png" /></figure><p>Now we’ll do a little bit of algebra to turn this last line into something that we can actually optimize with gradient descent. First, we’re going to apply the very useful identity that says that the logarithm of a product is equal to a sum of logarithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*79tF01UOOWmofh5d4ZJV4A.png" /></figure><p>The last term is the negative entropy of qi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*l0N4VuLycGW93PZKuqoTbg.png" /></figure><p>The conclusion of all this discussion is that <em>maximizing this quantity that we have at the end is going to push up on a lower bound to log p(xi), which means it will eventually maximize log p(xi) as well</em>. A brief parenthesis about entropy:</p><p><strong>Entropy allows us to ask:</strong></p><ol><li>How random is the random variable? Entropy represents how random a distribution is; if all outcomes are equally likely, then you have the highest entropy, whereas if one outcome is guaranteed, then you have the lowest entropy.</li><li>How large is the log probability in expectation under itself? For example, if you have two distributions like these:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*kKHkH3uETKqIUcfIZmIMaA.png" /></figure><p>These are continuous-valued distributions. We could ask: which one has the higher entropy? Since entropy quantifies how random a random variable is, the top one has higher entropy because there are more values that are possible, which means the probability of each of those values must be lower (because distributions always integrate to one).</p><p>Then, what do we expect from this expression?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*l0N4VuLycGW93PZKuqoTbg.png" /></figure><p>We’re maximizing entropy over qi and we’re also maximizing the expected value of those log probabilities.</p><ul><li>The first term is going to encourage putting a lot of probability mass on a value of z for which log p(xi|z) +log p(z) is large</li><li>The second term is going to encourage broadening this probability mass</li></ul><p><em>What that means is that we’ll capture the point with the largest probability under p, but we’ll also make the resulting distribution q as broad as we can, so that it covers as much probability mass as possible and has the highest entropy.</em></p><p><strong>KL-Divergence</strong></p><p>Another concept in information theory that we should discuss is KL-Divergence. It can be thought of as:</p><p>1 A measure of how different two distributions are, because if q and p are exactly the same, then the divergence is zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*xOBBAgwrtwgn9t9K-vUSlQ.png" /></figure><p>2 A measure of how small the expected log probability of one distribution under another is, minus entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*XGslWU_GpMCl4H3RsBFiWg.png" /></figure><p><strong>The variational approximation</strong></p><p>The expression that we derived before by using Jensen’s inequality is actually a KL-Divergence. We call this the evidence lower bound and it’s a function of two distributions: p, which is the distribution we’re learning and qi, which is our approximation to the posterior. So what makes qi(z) good? Being able to accurately approximate p(z|xi) with a low KL-Divergence between them.</p><p>One can prove that the log p(xi) is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*mwuo2JzAtOax-ul19TaP5A.png" /></figure><p>Where the second term is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*qmQLQ0GkgrgcDiE8-TLH_w.png" /></figure><p>Therefore, if we want qi(z) to approximate p(z|xi) well, the KL-Divergence has to be low.</p><p>If we want to know how to train our model, we can train our model by maximizing the evidence lower bound with respect to the model p and, if we want to get the best qi, we also maximize the same evidence lower bound with respect to qi. This is telling us that if we just maximize the lower evidence bound, we are in fact minimizing the KL-Divergence.</p><p>The goal is then to maximize the evidence lower bound: for every xi in our dataset, we’re going to calculate the gradient of the evidence lower bound with respect to the parameters of our model. The way we do that is we first sample a z from qi(z); then, we approximate our gradient as the gradient for our model for that one sample; then, we take one gradient descent step and we update our qi to also maximize the lower expected bound (there are different ways of doing so).</p><p>Let’s start with something simple: let’s just say that qi is a gaussian distribution over z, with a mean and a variance. For every image in our dataset, we have a different mean and a different variance that we’ll keep track of.</p><ol><li><strong>Regular variational inference<br></strong>One way that we could update mean and variance is we could compute the gradient of the evidence lower bound with respect to those quantities and then just do gradient descent on those. But there are two problems with this approach. The first is the number of parameters we need to optimize grows (at least) linearly with the number of observations. Not ideal for massive data-sets. The second is that if we get new observations, or have test observations we would like to perform inference for, it is not clear how this fits in to our framework. In general, for new observations we would need to re-run the optimization procedure.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*vHOu81k1oJ2hTDgShUuCdA.png" /></figure><p><strong>2. Amortized variational inference<br></strong>Amortized VI is the idea that instead of optimizing a set of free parameters, we can introduce a parameterized function that maps from observation space to the parameters of the approximate posterior distribution. In practice, we might (for example) introduce a neural network that accepts an observation as input, and outputs the mean and variance parameter for the latent variable associated with that observation <a href="https://gordonjo.github.io/post/amortized_vi/#fn:4">4</a><a href="https://gordonjo.github.io/post/amortized_vi/#fn:5">5</a>. We can then optimize the parameters of this neural network instead of the individual parameters of each observation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*M-XdCn0Qfo32jxJ5yS906A.jpeg" /></figure><p>Notice that this directly addresses the issues mentioned earlier. First, the number of variational parameters is now constant w.r.t. to the data size! In our example, we need only specify the parameters of the neural network, and that is not dependent in any way on the number of observations we have. Second, for a new observation, all we need to do is pass it through the network, and voila, we have an approximate posterior distribution over its associated latent variables! At the constant cost of a forward pass through a network! These gains are the source of the term amortized.</p><p>Taking a gradient ascent step on φ: by computing the gradient with respect to φ of L. φ appears in two places in the evidence lower bound: (1) it appears as the parameters of the distribution under which we compute the expectation (2) it appears inside the second entropy term</p><p>This is our evidence lower bound:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*urKt7yd_TKlnVXWWgewB9Q.png" /></figure><p>The gradient of the entropy term is easy to handle, but the first part is a little more complex. One way that we can think about calculating the gradient of the first part is to note that all the stuff inside the expectation does not depend on φ, so we can collect those terms into a single expression I’m going to call r(xi,z):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*MKBgUjwFBoInKvfiX6wssQ.png" /></figure><p>This is similar to the objective in reinforcement learning, which is to maximize the expected value of the reward where the expectations are taken with respect to a distribution determined by the policy. Here, we have the expected value of some function r, where the distribution is determined by qφ: we could just use policy gradient.</p><p>The simple version would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*SzWwxEUXYMhePQTKIy1utg.png" /></figure><p>The shortcoming of this expression is the same as the shortcoming of policy gradient in general: the variance is large, which means that we might in practice have to generate quite a few samples zj to get an accurate gradient estimate.</p><p>There is a much better way that we can train these models that’ll be much faster and more effective in practice; it’s going to leverage the fact that unlike in the case of reinforcement learning, in the case of latent variable models we can actually calculate the derivative of r. This is called the reparameterization trick.</p><p>Here’s the idea. We have our expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*2wws0luKBJEaFN-ykXI3dw.png" /></figure><p>For which we want to calculate the derivative with respect to φ, but φ is not just any distribution: it’s a normal distirbution. This means that we could also write z as a deterministic function of the mean and variance and epsilon, which is a standard gaussian sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*kimDk3hs1aYoT9RIbmUJkA.png" /></figure><p>This is because a gaussian with a non-zero mean and a variance that is not one can just be expressed as a affine transformation of a zero-one gaussian. Now everything here is deterministic except for epsilon, but epsilon does not depend on φ. It doesn’t depend on the neural network, so we can equivalently write our objective as the expected value with respect to epsilon, where we substitute this equation for z:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*JYPdQa1oq5gfOBThd0WTyQ.png" /></figure><p>φ only appears inside the expectation: the distribution with respect to which we’re taking the expectation is not dependent on φ anymore. We’ve re-parameterized the distribution and that’s why it’s called the reparameterization trick. So now we can estimate the gradient with respect to φ as follows: we can sample a bunch of epsilons from a zero mean unit variance gaussian and then the derivative with respect to φ is just applied by using the chain rule of differentiation. The reason that we cannot do this in reinforcement learning is that the derivatives of the rewards are not known to us.</p><p>Another way that we can look at our evidence lower bound objective works this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*MkQsNlSc8raXPLsVOLb3zg.png" /></figure><p>Theta only enters into the first term; the second and third terms are independent of theta and if we group them together we’ll notice that it’s just the negative KL-Divergence. It’s very convenient to express the evidence lower bound like this because all the hard stuff is basically in the first term</p><p>If we apply the reparameterization trick, then both theta and phi now appear inside the expectation and the distribution under which we’re taking the expectation does not depend on either of the parameters. We can estimate this using just a single sample of epsilon by just plugging in that epsilon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*MYPXNMBthLFVd6Ul3uzrKQ.png" /></figure><p>It might be instructive at this point to draw the resulting neural networks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*PbIm0Lz7tkacHk5PO7FopA.png" /></figure><p>This is how you implement a variational autoencoder. The reason this is called a variational autoencoder is because if you look at the structure of this neural network, it looks like an autoencoder. It has an encoder with parameters φ, which has this unusual noise, mean and variance thing at the end; then, it has a decoder with parameters θ. So, it’s just an autoencoder where, unlike for the denoising autoencoder, the noise is put into the hidden state z instead of being put in in the beginning. But the variational auto encoder has this very appealing interpretation as a latent variable model.</p><p><strong>Reparametrization trick vs policy gradient: </strong>what are the tradeoffs?</p><p>The policy gradient:</p><ul><li>Can handle both discrete and continuous latent variables</li><li>It has high variance and requires multiple samples and small learning rules</li></ul><p>The reparameterization trick:</p><ul><li>It only handles continuous latent variables</li><li>It’s very simple to implement and does work quite a bit better if you can use it</li></ul><p>Now, let’s put things together and go through the full variational autoencoder.</p><p>The variational autoencoder is a latent variable model that has latent variable z and it has observed variables x</p><ul><li>It has an encoder, which performs inference:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*ZKhgM7Yxlbe7OpmdUhB_4g.png" /></figure><p>This is a neural network that takes in x and it produces a mean and a variance over z.</p><ul><li>It has a decoder:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*vDMcff7X3mwUC84NdxVhXA.png" /></figure><p>This is a neural network that takes in z and it produces a mean and a variance over x.</p><p>This is the objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*unuTafDGwuBBF8ahuac3Lg.png" /></figure><p>The first part of the objective looks like an autoencoder objective: you encode xi into mean and variance, get z and then you decode to get the resulting distribution over x and you try to maximize the probability of the real image.</p><p>The second part can be thought of as a kind of penalty that penalizes how much qφ(z|xi) deviates from the prior p(z). From this, we can derive a little bit of intuition as to why the variational autocoder works: because that second KL-Divergence term encourages the encoded z’s to look similar to samples from p(z), at test time the decoder will know what to do with those z’s.</p><p>We can also train conditional models of variational autoencoders; if you have a conditional model, then you are mapping x to some output variable y and you would like p(y|x) to be some fairly complex distribution. We’ll use the same intuition as before: p(y|x) might be complex, but p(y|x, z) will be simple. Everything is just like before, only now we’re generating y and everything is conditioned on x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*fBELK8ha2OmlO1bu6M5lIg.png" /></figure><p><strong>VAEs with convolutions</strong></p><p>Let me walk you through a potential architecture we might use for a VAE with convolutions. You have your image and first it has to go into the encoder. This is the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1VyBxMmq5Y-b5MgMzfaWUw.png" /></figure><p>So far, everything is the same as any other convolutional autoencoder, but now we’re going to have one fully connected layer that outputs a mean and another fully connected layer that outputs a variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*uktTkuX4Y6qBE9xzWe2Gpw.png" /></figure><p>Then we’re going to sample our normally distributed epsilons, multiply one of them by sigma and this gives us z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*hBzJXqXlfirjVOGF7cJ2cw.png" /></figure><p>This is our bottleneck representation: if we want to use a variational autocoder for representation learning, for example for a downstream classification task, this is the vector that we would use as our compressed representation of the image.</p><p>But to train the VAE we also need a decoder. For that, we’re going to use transpose convolutions that up sample the vector all the way back up to a 64 by 64 image. Then, we train this whole thing end to end with backpropagation by using two loss terms:</p><ul><li>Negative log probability of the image</li><li>KL-Divergence between the distribution determined by μz and σz and our prior p(z), which is typically a zero mean unit variance gaussian.</li></ul><p>Our decoder outputs two numbers for each pixel: a mean and a variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*AiChrxOkOOxe4_x8Ybdnyg.png" /></figure><p><strong>VAEs in practice</strong></p><ul><li>One common issue is that it is very tempting for VAEs to ignore the latent codes or generate poor samples. The reason is that if you can approximate your x with just a regular gaussian distribution, it’s much easier especially for conditional VAEs to do this, because initially the z just looks like noise and figuring out how to use it can be pretty hard. You can tell that this is happening when you get back a blurry “average” image that does not look like the input.</li><li>A second problem you might get is that the latent code is not compressed. You can tell this is happening when your reconstructions are great, but when you sample a z from p(z) and then decode, you’ll get an unrealistic image.</li></ul><p>For problem 1, the KL-Divergence is too low: typically, qφ(z|x) ignores x and just outputs a zero mean a unit variance. This means the z’s carry no information about x, which means your decoder pθ doesn’t use the z’s. That is why it produces those blurry average images: there’s no information in z that would be useful for actually reconstructing x.</p><p>Problem 2 is characterized by the opposite, the KL-Divergence being too high: there is too much information being packed into z, which means that you can reconstruct x perfectly but because it’s so far from the prior when you sample z from it, your decoder doesn’t know what to do with it.</p><p>To control the KL-Divergence, a very common trick is to put a multiplier in front of that KL-Divergence. You adjust this hyper parameter depending on which problem you’re seeing: if you have problem one, then you need to decrease beta, whereas if you’re seeing problem two, then you need to increase beta.</p><p>Sometimes it is difficult to find the beta that both produces good samples and good reconstructions early on in training. Intuitively, early on in training the VAE needs to learn to pay attention to z and later on in training it needs to do a better job of compression. It can then be very useful to actually schedule beta to alter beta. For example, you could begin with very low values of beta, so that the VAE learns to use z and then later on raise beta to get the samples to be good. In other words, once your reconstructions look good you can increase beta and then your samples will become better too</p><p><strong>Invertible models and normalizing flows</strong></p><p>We’re going to talk about a different kind of model that is structurally a little bit similar to a variational autoencoder, but can be a lot simpler to train. Normalizing flow is a neural-network density estimation technique. <em>Starting from a simple prior distribution, like a Gaussian, one can use a tunable tranform to wrap that Gaussian around the fitted data in the training. Once training is complete, we can use that transform to map the points in the data space to the prior space.</em><strong> </strong>Thus, we can now obtain the probability density in the probability space.</p><p>We’ll first examine the basic mathematical framework of normalizing flows, and then we’ll take a look at an example paper that uses a normalizing flow to learn a generative model of images. Suppose we have a continuous random variable Z with some simple distribution, like a spherical Gaussian, allowing for easy sampling and density evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*4caWY9KNKCK6PeW81ZMOLw.png" /></figure><p>The key idea is to transform this simple distribution with some function f into a more complicated one. We’ll formulate <em>f as the composition of a sequence of invertible transformations, so the overall transformation is also invertible</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*erHJXC3ZoLDOGAa6fsRZ6A.png" /></figure><p>For any X, we have exactly one Z that could have been sampled to produce it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*06xEbumqZMyZi-MzUjJcHA.png" /></figure><p>So, say we ask what the density is of a given X. We might think that we can just say, “Okay, P of x equals P of F inverse of X.” Well, in general, no, this isn’t the case. It depends on the behavior of F. To understand how this works, we can take a look at what’s called the change of variables formula.</p><p>When we have an invertible and differentiable function f mapping from some domain Z to domain X, with the distribution P of Z defined over domain Z, the change of variables formula says that P of X is actually equal to P of F inverse of X multiplied by the magnitude of the determinant of the Jacobian of F inverse. That is, the matrix of all first-order partial derivatives of F inverse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*jDT2gNpv4dhP1z9E9hDXQw.png" /></figure><p>So, what does this mean? Well, first, let’s replace each F inverse of X with a unique Z associated with X. So we’re mapping X to its inverse, evaluating the density of this Z under P of Z, then multiplying by some scalar magnitude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*C00wZhp2JIw3n1M8-pUcZQ.png" /></figure><p>Now we know that a valid probability density function must always integrate to one over its domain. The magnitude of the Jacobian determinant, which basically indicates how much a transformation locally expands or contracts space, is necessary to ensure that the new density function P of X satisfies this requirement.</p><p>Let’s look at an example when Z and X are two-dimensional. The Jacobian of F at a given point in Z gives a linear approximation to how X is instantaneously changing with Z. So imagine we have a square region of space in Z near this point. The partial derivatives in the Jacobian locally define how this region will be transformed by F. For example, let’s say we have a 2 for each diagonal term and zeros elsewhere. Locally, this transformation is stretching both dimensions by a factor of 2. Likewise, according to the determinant, the area of the initial square region should increase by a factor of 4.</p><p>Now, the change of variables formula we had previously contains the determinant of DZ, the x, the determinant of the inverse Jacobian, which is actually just the reciprocal of the determinant of the original Jacobian. And we know that the total probability of the blue region in Z should be equal to the total probability of its image under F. What the change of variables formula is saying is that in order for this to be true, locally, each point in the X region has to have 1/4 as much density as its inverse.</p><p>Now we don’t actually care whether the Jacobian preserves orientation or not. For example, consider the case where we replace the bottom-right term in the Jacobian with negative 2. We no longer preserve orientation, as the region in X flips upside down, and the Jacobian determinant is now negative 4, not positive 4. But we only care about its magnitude. The relationship between the densities of points in X and points in Z will be the same. So we call our sequence of bijective transformations a normalizing flow.</p><p>After Z is initially sampled, it flows through the sequence with its density function being renormalized at each step to ensure it remains valid. Normalizing flows have been used particularly in work on generative models, as you’ve likely seen. Generative modeling is all about learning to approximate some observed data distribution, say, of natural images or speech audio. And these can be used to sample new data points with similar characteristics to the training data, conditionally complete a sample, such as an image in painting, evaluate probabilities or densities of samples, and see which samples are more likely, or infer latent variables that allow us to reduce the dimensionality of the data or expose internal structure that enables generating samples with specific characteristics.</p><p>One way to use normalizing flows in a latent variable generative model is to parameterize the likelihood as a flow. In our framework, Z will serve as a latent variable with prior P of Z, and X will be the observed variable produced by passing Z through a series of transformations F. So let’s derive our maximum likelihood objective. First, we take the log of both sides, distributing the log through the product on the right-hand side. Now we know that the overall transformation F was specifically constructed to be the composition of a sequence of functions. So this log-determinant term can be replaced with the sum of the log determinants of each intermediate Jacobian. This setup will allow us to directly train our model via maximum likelihood, as we can compute the log marginal likelihood exactly.</p><p>Now, this differs from some other prominent deep generative models, such as variational autoencoders known as VAEs, and generative adversarial networks known as GANs. In the VAE case, we can only approximate a lower bound on the log-likelihood, known as the evidence lower bound or ELBO, and this is what we optimize during training. In GANs, we actually avoid the evaluation of the likelihood altogether and instead optimize a minimax objective involving the discriminator and the generator. In addition, the flow-based framework allows for exact posterior inference. In fact, the invertibility of F guarantees that we can find the unique Z that generates a given X.</p><p>With a VAE, we have an encoder network parameterizing an approximate posterior, as computing the actual posterior is intractable. And in a standard GAN, there is no encoder for inferring the latents, and the generator is not guaranteed to have full support over the data. Now, we have the sequence of potentially high-dimensional bijective functions whose Jacobian determinant we need to be able to compute, but this can get expensive.</p><p>The basic trick often used is to ensure that the Jacobian is triangular. This is because the determinant of a triangular matrix is just the product of the diagonal elements, so we don’t have to take into account any of the off-diagonal elements. For example, in the paper “NICE: Nonlinear Independent Components Estimation,” the authors ensure that the Jacobian of each transformation is triangular via what are called coupling layers. Let Z be the input to a coupling layer. We first partition Z into two subsets, for instance, two contiguous subvectors.</p><p>For the first subset, we simply apply the identity, copying over the elements to the same positions in the layer’s output X. To get the remaining portion of X, we use two functions, N and G. N takes as input the first subset of Z, and then the output of N and the second subset of Z serve as inputs for G. We can look at the Jacobian of this transformation. Because elements in the first subset are not affected by elements in the second, we end up with all zeros in the upper right block and with the identity in the upper left. We’ll just need to make sure that the lower right block is lower triangular to ensure that the full Jacobian is triangular.</p><p>— — — — — — — — — —</p><p>Here’s the idea: instead of having the decoder represent a distribution over x given z, we’ll have a deterministic decoder that directly turns z into x.</p><p>Now if we want to compute p(x) for training, we can use the change of variables formula, which says that if x is a deterministic function of z, then p(x) is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*bI3BddNLK1fL81yo6YYbNA.png" /></figure><p>What it means is that if you have some distribution over z and z is transformed in a deterministic way to get x, then to get a density over x all you have to do is modify the density over z by how much of the volume changes according to f.</p><p>If we can calculate the determinant of the jacobian df/dz and we can calculate the inverse, then we can implement a model of this sort with a deterministic function that maps these stacks. So that determinant is just a correction for the change in local density due to f. The basic idea is therefore that if we can learn invertible mappings from z to x, that can make this determinant easy to compute and we can build these kinds of models without having to worry about all that variational inference stuff. We also don’t need lower bounds and can get exact probabilities.</p><p>This class of models is sometimes referred to as normalizing flow models. Our training objective is just maximum likelihood: maximize the log probability of all the xi’s in your dataset. We use the expression from the change of variables formula on the previous slide to write p(x) in terms of p(z); p(z) is still some very simple distribution. If we substitute this formula into the training objective, our objective is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*aOkxQsWku31ZTz7YqGE1cw.png" /></figure><p>We are going to choose a special structure that makes this easy to calculate. A normalizing flow model consists of multiple layers of invertible transformations, so all we need to do in order to implement these types of models is figure out how to make an invertible layer and then compose many of these invertible layers to make a deep network.</p><p>A few observations:</p><ul><li>If each layer is invertible, the whole thing is invertible</li><li>Oftentimes, invertible layers also have very convenient determinants</li><li>Log-determinant of whole model is just the sum of log-determinants of the layers</li><li>Our goal is to design an invertible layer and then compose many of them to create a fully invertible neural net</li></ul><p>There are many different ways to design invertible layers; I’ll start with one of the simplest types, called non-linear independent components estimation (NICE).</p><p>Ordinarily, a layer in neural net would be some mapping from z to x. For example, x is given by a ReLU applied to (Wz+b). But we can’t use this because this is non-invertible. Here’s an idea: what if we force part of the layer to keep all the information so that we can then recover anything that was changed by the non-linear part?</p><p>We can take our z and split it into two parts. The first part goes from number 1 to d, the second part goes from number d+1 to n. X will also have two parts: the first part is copied entirely to the first part of z, but it is also passed through some neural net and it is added to the second part of z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*sk_9wDXZ0fJJ2_qJkKe-Wg.png" /></figure><p>The question becomes: if we have x, can we recover z? If so, then this layer is invertible. We can then compose an entire net of such invertible layers.</p><ol><li>Recover z(1:d) = x(1:d)</li><li>Recover gθ(z(1:d))</li><li>Recover z(d+1:n) = x(d+1:n) — gθ(z(1:d))</li></ol><p>The trick that we needed to make this work is that the first part is preserved losslessly and the non-linear component depends only on that first part. This means that you can recover the nonlinear components and subtract them off.</p><p><strong>What about the Jacobian?</strong></p><p>We need the determinant to compute our normalizing flow objective; both x and z have these two parts, so this would be df/dz as a matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*oANB_7dJ2jOum89q8aCd5g.png" /></figure><p>The derivatives of this matrix are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*-9bzcLoss7jhfuAsX1vk-A.png" /></figure><p>However, you might know that the determinant is not affected by the lower left block, because the upper right block is zero. So the determinant for a matrix like this is a lower triangular matrix; it is just determined by the diagonal entries and the diagonal entries are all one, therefore the determinant is 1.</p><p>That’s very convenient: because of this particular form, for these invertible layers the determinants are always one, which means that that term in the objective has no effect on training the model whatsoever. Unfortunately, it’s representationally a bit limiting, because the determinant is always one and thus we can’t change the scale the determinants always. This kind of network only transforms z’s into x’s, but it never rescales them, so it can be very difficult to train very complex distributions in this way.</p><p>So in practice what we see is if we take this kind of invertible layer and we stack a few of these layers and use them to train a generative model, we can do a pretty good job of modeling simple datasets (MNIST), but when we start looking at more complex images, it tends to break down (CIFAR10).</p><p>There’s a small change we can make to this model that makes it substantially more expressive and this is something called Real-NVP: Non-Volume Preserving Transformation. We are going to split z and x into two parts like before, but now we’ll have two neural nets: a scaling network and a biasing network. We’ll take the second half and we’ll multiply it by the first neural net and then we’ll add the term from the second neural net, so that the second half of x is given by the second half of z times the exponential of the output of the first neural net plus the second neural net:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*zbpBGEFMS30cYJxOz8x3nw.png" /></figure><p>This is also an invertible operation and the way you derive the inverse is very similar to before. You recover the first half of z by just using the fact that it’s equal to the first half of x; once you’ve recovered that you can recover gθ and hθ and then you can solve for the second half of z by just taking the second half of x, subtracting g and then dividing by the exponential h.</p><p>Now the jacobian has a much more interesting form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*DJ0hYHD1iwXpFa45cu1wzg.png" /></figure><p>The bottom right block now is the diagonal of these exponential values, which means the determinant is not one anymore. It is significantly more expressive at the cost of adding a second non-linear component and this can generate much higher-quality images</p><p>Some concluding remarks about normalizing flows</p><ul><li>One big advantage of normalizing flows is you can get exact probabilities or likelihoods from them; you can actually evaluate p(x), whereas a variational autoencoder only gives you a bound on p(x)</li><li>You don’t need any lower bounds</li><li>It’s conceptually somewhat simpler</li></ul><p>It also has a few major disadvantages:</p><ul><li>It requires a special architecture, so you can’t just use regular layers</li><li>Since each layer is invertible, the dimensionality at every layer has to stay the same and this can be a really big deal with high resolution images. If you have a million pixels in your image, then you need a million dimensions in z, whereas a variational auto encoder can have a latent code that is much lower dimensional than the image and this can be a major limitation</li></ul><h4><a href="https://www.youtube.com/watch?v=39CmbTX1S8M&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=58">Generative adversarial networks</a></h4><p>The idea that we’re going to explore in today’s lecture is whether instead of training an encoder, like we did with VAEs, we could just train the whole model to generate images that look similar to real images at the population level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*dguM5wm3SDb2YTby9OzKow.png" /></figure><p>In other words, instead of trying to guess for every real image what its corresponding z is and then using that to supervise our network, what if we just generate a bunch of random images and then try to alter our network so that those random images at the population level resemble the population of realistic images given to us in our training set? <em>This means that we want to sample from complex, high-dimensional training distribution and there is no direct way to do this; the solution, therefore, is to sample from a simple distribution (like random noise) and then learn a transformation to the training distribution (using a neural net).</em></p><p>An example: let’s say that I have two sets of faces. No two faces are the same, but they look kind of similar at the population level, so if I were to take five samples from one distribution and five samples from the other distribution, probably you would not be able to tell which distribution those came from. In that case, we would say that these two distributions are similar at the population level. This is how we can basically try to match distributions without having to figure out what the latent variables for any particular image actually are. I might also ask you whether you can guess which set of faces is actually real: if I tell you that some of these faces were in fact generated by a latent variable model, would you be able to guess which set it is? These kinds of models that match distributions at the population level can get extremely good and much better than this.</p><p>Here’s how we’re going to set this up: we’re going to set up a game where the only winning move is to generate realistic images. In other words, <em>the idea is to train a network that is going to guess which images are real and which are fake; this classifier is going to output a probability that this image is a real image</em>. In order to train a network like this, all you need is a labeled training set; the fake images can come from our generative model, whereas the true images can come from our training set.</p><p>This model can then serve as a loss function for our generator: in other words, the loss function of our generator that turns z’s into x’s could be the realism score of the resulting image as produced by this classifier. The basic intuition behind this approach is that we’re going to learn a loss function by training a classifier to classify between fake images and real images and then we’re going to use this as a negative loss for our generator to get the images that it generates to be more real according to this classifier.</p><ul><li><strong>Generator network</strong>: try to fool the discriminator by generating real-looking images</li><li><strong>Discriminator network</strong>: try to distinguish between real and fake images</li></ul><p>The core idea of a GAN is based on the “indirect” training through a discriminator, which itself is also being updated dynamically. This basically means that the generator is not trained to minimize the distance to a specific image, but rather to fool the discriminator. This enables the model to learn in an unsupervised manner.</p><p>Here is a potential algorithm:</p><ol><li>Get a true dataset of real images</li><li>Get a generator Gθ(z), which can even be initialized randomly</li><li>Generate a dataset of false images</li><li>Train your discriminator, which is just a classifier that tries to predict whether the image came from the true dataset or the false one</li><li>Use this discriminator to construct some kind of loss function for training G(z)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*mFE0fhmQrwWyAkc0X7rdbg.png" /></figure><p>This recipe almost works, but it has a few major problems that we need to address before we can construct a viable method.</p><p>If we do step five only once, the big problem is that in step five it’s very easy for G(z) to fool D(x). If D(x) was trained for fake images coming from a really bad generator, then the new generator against step five just needs to be better than the old one, but it might still not be very realistic. In order to make it work, we choose an iterative approach. After getting a generator, we’re going to sample our false images and then update our discriminator with only one gradient step: we won’t actually train the discriminator convergence, we’ll just take one gradient step. That will give us a slightly better discriminator, then we will update our generator also for only one gradient step and then we’ll generate new false images; so instead of just generating all the false images up front and training your discriminator convergence, you’ll actually alternate between updating the discriminator to get better at classifying real from fake and then updating the generator to generate more realistic images. <em>It’s going to be a kind of game where the discriminator will keep trying to keep up with the generator and the generator will keep trying to fool it.</em> Because they have this kind of competitive process, the only way for the generator to win the game is to produce images that are truly indistinguishable from real images</p><p><strong>Summary</strong></p><p>A known dataset serves as the initial training data for the discriminator. Training it involves presenting it with samples from the training dataset, until it achieves acceptable accuracy. The generator trains based on whether it succeeds in fooling the discriminator. Typically the generator is seeded with randomized input that is sampled from a predefined latent space. Thereafter, candidates synthesized by the generator are evaluated by the discriminator. Independent backpropagation procedures are applied to both networks so that the generator produces better samples, while the discriminator becomes more skilled at flagging synthetic samples.</p><p><strong>A little bit more intuition for why this basic idea actually works</strong></p><p>What does G(z) want to do? Ideally, its goal is to somehow persuade the discriminator to output 0.5 for all generated images. In order to do this, it has to generate images that look realistic; but the the somewhat more subtle point is that in order to really get 0.5 on all of your generated images, you don’t just need to generate images that look realistic, <em>you actually need to generate all possible realistic images and this is why GANs match distributions.</em></p><p>Let’s say that we have a dataset that has photographs of cats and dogs; half the pictures are cats and half of them are dogs. Our generator has gotten really good at generating very realistic images, but it only generates dogs, so it has not covered the whole distribution. Imagine what the discriminator is going to do in this case:</p><ul><li>If we take a picture of a cat and we pass it to the discriminator, the discriminator will say that the probability that it is a true image is 1. This is because the training set has about half the true images containing cats, but none of the false images contain cats.</li><li>If we take the picture of a dog and we pass it to the discriminator, the discriminator will say that the probability that it is a true image is 0.25. This is because the training set has about half the true images containing dogs, but all the false images were dogs.</li></ul><p><em>This is why in order for the generator to win this game against the discriminator, it really has to not only generate realistic images, but all of the realistic images.</em> For full disclosure, a particular issue with GANs that I will not talk about too much in this lecture is that in reality in practical instantiations these models do often suffer from something called the mode collapse problem. The mode collapse problem is a type of overfitting and when that happens GANs do in fact fail to capture the entire distribution.</p><p><strong>Technical details of actually setting up GANs</strong></p><p>The classic GAN described by the previous procedure can also be expressed as a two-player game — a min-max problem where you have two players that are respectively trying to minimize (the generator) or maximize (the discriminator) the same objective. This expression is basically just cross-entropy loss: it takes the positive labeled images and maximizes the log probability of those; then, it takes the negative labeled images and maximizes the log probability of those.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*bhleogvBKRDbuZThiOIATA.png" /></figure><p>In a binary classification problem, the probability of a negative label is just 1 minus a positive label, so that’s why you see “1 — D”. Both these are expected values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*8GUNZA8KSmjVnhEMXpMsvg.png" /></figure><p>D is trying to maximize the log likelihood, such that D(x) is close to 1 (real) and D(G(z)) is close to 0 (fake); G is trying to do the opposite. It is no longer a conventional gradient descent optimization, it is in fact the problem of finding the Nash equilibrium in a two-player game. Here is the GAN game, rewritten in terms of θ (parameters of G) and φ (parameters of D):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Ur_nKLekqg9addRB4vqstA.png" /></figure><p>The algorithm is basically the same as alterning between a gradient ascent step on φ, because φ is maximizing, and a gradient descent step on θ, because θ is minimizing. These two steps just alternate.</p><p>There are two important details that we have to get right in order for this to work:</p><ol><li><strong>How to make this work with stochastic gradient descent or ascent, because we want to use a mini-batch</strong></li></ol><p>For using stochastic gradient ascent or descent, we approximate the gradient by using a mini batch of training points for the first expectation and then for the second expectation we sample the same number of z’s and run them through the generator. That basically gives us a mini batch gradient ascent or mini batch gradient descent version of this. The loss is cross-entropy loss. The generator loss is just estimated with the same mini batch of z’s; you just run them through the generator, ask the discriminator what probability lends to them and then use that as the loss for your generator.</p><p><strong>2. How to compute gradients</strong></p><p>Computing these gradients is pretty straightforward; the gradient for the discriminator is just cross-entropy loss; the gradient for the generator may be a little bit more elaborate, because computing the loss function for the generator requires generating images and then passing them into the discriminator. The way that we calculate gradients for the generator is we backpropagate through the discriminator into the generator</p><p><strong>What particular objective does the GAN actually optimize?</strong></p><p>Can we somehow take this two-player game, analyze it and be able to state formally that at convergence this should minimize some measure of discrepancy between the data distribution and the distribution of images produced by our GAN?</p><p>For the purpose of theoretical analysis, we express the optimal D(x) in closed form as a function of G(z); we have an outer minimization and inner maximization, so maybe the solution of that inner maximization can be expressed in closed form as a function of G. We obviously can’t implement that in code, we need to actually train a neural net to do that, but maybe at least theoretically we can characterize the solution for D as a function of G</p><p>A very useful property for this is an identity that can be used to describe the Bayes’ optimal classifier. Let’s say that we have a set of positively labeled images (coming from p(x)) and a set of negatively labeled images (coming from q(x)). P(x) is p(data) and q(x) is the distribution of our images obtained by sampling z from p(z) and then running that through G. The optimal discriminator which I’m going to call D* is just the arg max of the log likelihood, which we can write as the expectation under p of log(D) plus an expectation under q of log(1-D).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*hjCzemPD4YVJXr-btObc7g.png" /></figure><p>Now we’re going to take the derivative of this with respect to D; we’re not taking the derivatives of any parameters, we’re just taking the derivative with respect to the function D and we’re going to set that derivative to zero and solve for D. If we can solve for the D that sets us to zero, we will have recovered the optimal discriminator. Crucially, that doesn’t mean that your neural net can represent that optimal discriminator — this is more in a case where we have a very expressive function and we can just not worry about parameters and just characterize the function that would be the optimal solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*aqAtKWDRqZUZ4l7vSzcOaA.png" /></figure><p>What I’m going to claim is that if I plug this in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*fVJIPRQYmcrPOCkk8SizkA.png" /></figure><p>Then the derivative will be 0. An expected value is just a sum over all possible x’s of the probability times the quantity inside the expectation, so the expected value under p(1/D(x)) is just a sum over all x’s of p(x) divided by D(x):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*I0yoULaX9O6_tVloSpb14g.png" /></figure><p>The same goes for the second term. In both expectations, the denominator and the distribution with respect to which we’re taking the expectation cancel out, so we’re just left with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*8lOHJhtwhBhIkqDcEaVHkQ.png" /></figure><p>Which equals 0. This expression D*(x) is in fact the optimal classifier that we can get if our positively labeled points come from p of x and our negatively labeled points come from q of x. This is the Bayes optimal classifier.</p><p>Taking p data(x) to be p and pG(x) to be q, we can derive the optimal classifier D*(G) as a function of G. If G is fixed and we optimize the discriminator’s convergence, if our neural net is very very expressive, in the limit this is what we should get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*J9ggkZQ0SC6-FpgoUCTQpQ.png" /></figure><p>Now, what’s the objective for G? We can simply plug in D*G(x) into the min-max optimization of above and turn it into just a minimization over G. I emphasize that this is purely a theoretical exercise, the only reason we’re going through this is in order to understand what the GAN objective really is. So if we substitute this in. we basically just have to write out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*tr2quGz4gesYJvJVVRL7Gg.png" /></figure><h4>What does the GAN optimize?</h4><p>Here’s the expression that we arrived at: it has these two funny expected value expressions. Do they actually mean something?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*aaS3k2U2MGbxz4jmiaAbWg.png" /></figure><p>Well, let’s define another distribution that we’re going to call q, which is the average of p data and pG. So, we’ll define q(x) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*mcB2_qBEmdmk_89TwgRUNg.png" /></figure><p>Then, we can write our expression for the generator objective as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*CGYi_yguyYpK0aqGudWxGA.png" /></figure><p>Each of these terms is a KL divergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*y9qfDm3KU1YHBlTlsPtOcQ.png" /></figure><p>It turns out that this expression is actually another divergence measure called Jensen-Shannon divergence. It has some interesting properties:</p><ul><li>It goes to zero if the distributions match</li><li>Unlike the KL divergence, it’s symmetric</li></ul><p>This means that the GAN really is trying to match the data distribution</p><p><strong>A small practical aside about GANs</strong></p><p>Following all the derivations that we had so far, the conclusion should be that the generator loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*TvyW4ZipUsL38EfG8nV11A.png" /></figure><p>Which amounts to saying: let’s minimize the probability that the image is fake. In practice, we actually often use a slightly different loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*mxdhM_gZRamMA1UAwCcyrA.png" /></figure><p>Which amounts to saying: let’s maximize the probability that the image is real. These two things are very similar and they represent the same concept, but their gradients look a little bit different when you’re very far from the optimum. The reason why it is better to maximize the probability that the image is real has to do with the shape of the function log x and the function log 1 minus x:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*mAcUVdqivInpEDIDlI7ySg.png" /></figure><ul><li>If you have a very bad generator, you’re going to have a large loss value, so you’re going to be on the left side of these two curves.</li><li>If you have a very good generator, you’re going to have a low loss value, so you’re going to be be on the right of these two curves</li></ul><p>The problem with minimizing the probability that the image is fake is that the gradient tends to be pretty small when the generator is bad and then it becomes really steep on the right once the generator is good; we don’t really want that because it’s most important for the generator to learn very well when the generator is bad. If it can’t make progress when it’s bad, it’s never going to get good</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*jC25CcNQS0nFBGA5JmENtA.png" /></figure><p><strong>A few practical notes on GAN architectures: how do you actually set up the GAN?</strong></p><ul><li>You could have a fully connected architecture. You could take your your z’s and mount them through two fully connected layers with 512 units each and produce an MNIST digit. Then you could have your discriminator also have two fully connected layers of 512 units each and produce a true/false output, with a sigmoid non-linearity at the end.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*53hehQvGvihBbT8RpiXfeA.png" /></figure><ul><li>You could have a more complex convolutional GAN, maybe similar in spirit to some of those VAE architectures where you might have some transpose convolutions actually produce a higher resolution image and then a convolutional discriminator that produces your true/false label</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*QRwDeM-HLxZZIsp-R4ogLg.png" /></figure><ul><li>A BigGAN is a very modern GAN that produces high resolution images. This architecture is much more complex but it is conceptually quite similar to the previous one. The basic principle is the same: it’s going to be some kind of transpose convolutional style structure</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1q4eCEpi8SzobeveHaQzTA.png" /></figure><ul><li>Conditional GANs generate images of a particular class. All you have to do is you have to concatenate your class label shown here as y to both the input to your generator and the input to your discriminator. You take your class label represented as a one-hot vector and just concatenate it to z and then for the discriminator concatenate it to x</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*PwpfGqoH_vy-tJitD3BHxg.png" /></figure><ul><li>CycleGAN is concerned with a very particular problem: not just generating any image, but specifically translating from one domain into another. For example, if you get a large collection of photographs of zebras and a large collection of photographs of horses, can you turn a zebra photograph into a horse? The problem is that you would be given these images but you won’t be given pairs: it’s not like english to french translation, where you get a sentence in english and a corresponding sentence in french. You just get one collection of horses and a different collection of zebras</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*5IKX2wBm9XKwy2tBZWQ4sw.png" /></figure><p>We have two conditional generators and two discriminators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*FwFT7CItDnf6rq00rs348A.png" /></figure><p>G turns X into Y, so it’s conditioned on x, which might be a photograph of a horse, and its job is to generate y, photographs of zebras.</p><p>Dx is trained where positives are real pictures of horses and negatives are generations from G and Dy is trained where positives are real pictures of zebras and negatives are generations from F. But of course in order for F to generate a sample it needs to be given some x, so F will generate a zebra given a horse. We can now imagine training these two generators and two discriminators and now we’ll have a generator that turns horses into zebras and another generator that turns zebras into horses. But we’re not done yet, because nothing about this says which horse or which zebra you should generate. So the problem is why should the translated zebra look anything like the original horse?</p><p>That’s where the cycle consistency loss comes in: if I turn this horse into a zebra and then turn that zebra back into a horse, I should get the same horse and that’s measured in terms of distance. Literally, the pixels in the image should be close together in terms of their absolute value difference. So, that is the idea behind CycleGAN: two GANs, one for each domain, and a loss that says: if you map from one domain to another and then back, you should end up in the same place where you started.</p><p><strong>Brief summary</strong></p><ul><li>The GAN is a 2-player game. This is the equation for it:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*bHT0TXw56bLbSQjW32Jguw.png" /></figure><ul><li>We can derive the optimal discriminator and from this determine what objective is actually minimized at the Nash equilibrium</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*R35MNRo72WQeyEdCwdRGew.png" /></figure><p>This does not guarantee that we’ll actually find the Nash equilibrium; so, this derivation just shows that if we find the Nash equilibrium, the fixed point for this GAN, it will minimize the divergence.</p><ul><li>We can train either fully connected or convolutional GANs and there’s a lot of liberty that we have in terms of determining their architecture</li></ul><h4><a href="https://www.youtube.com/watch?v=RdC4XeExDeY&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=60">Modern techniques for training GANs</a></h4><p>If you just implement GAN training the way I described until now, you’ll probably find that in all about the simplest problems, it requires an enormous amount of hyperparameter tuning for it to work well. One particularly difficult scenario for GANs that perhaps illustrates this problem is the following: let’s say that x’s are one-dimensional, so that I can draw them on the slide. Now, let’s say that these blue circles represent real data; let’s say that these orange circles represent samples generated by your current generator. You could imagine the distributions like these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*1haK2OD9JW26rrcO80Jv3w.png" /></figure><p>If I train my discriminator with pdata and pG, my discriminator might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*3wMMXkAk5O5-TdK_vfHEKA.png" /></figure><p>It’ll be perfectly 1.0 close to the real data and it’ll be perfectly 0.0 close to the generated data and we’ll have some decision boundaries somewhere in the middle, very far from either distribution.</p><p>Remember that the generator learns entirely by using the gradient through the discriminator, so what will the generator gradient actually be near the generated data? Well, the discriminator is outputting zero pretty uniformly over all those points.</p><p>How can we make sure that even when the generator is very bad compared to the discriminator and when the generated data is very far from p data, the discriminator still gives us a meaningful gradient signal?</p><ul><li>One thing we can do is we can somehow alter our discriminator; maybe we can somehow change how the discriminator is trained, so that even if it can perfectly classify p data from pG, it is still encouraged to produce a smoother slope between these two distributions to give the generator some gradient signal to guide it towards p data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*pGO6pRwoQ8lEtRAyNiZV5Q.png" /></figure><ul><li>Another thing we could do is we could basically alter the distributions a little bit, maybe we can somehow modify p data and pG so they overlap more and then the discriminator will not be quite so sharp — then we’ll see a stronger gradient signal</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*PIfPsQnINyEAdQAaUFtNjw.png" /></figure><p>Both of these are viable ideas and we can actually instantiate this intuition in some practical methods. Here are some improved GAN techniques that are good to be aware of in no particular order:</p><ul><li>Least-squares GAN is a way to modify the GAN discriminator to output a real valued number instead of a probability between zero and one and train the discriminator so that it produces a smoother slope</li><li>The Wasserstein GAN is a way to modify the discriminator to be Lipschitz-continuous, which also encourages it to have more of a cleaner slope between p data and pG</li><li>Gradient penalty is a way to improve the Wasserstein GAN, so the discriminator is constrained to be continuous even harder</li><li>Spectral norm is a way to really constrain the discriminator to be continuous</li><li>Instance noise is trying to change the distributions by adding a lot of noise both to p data and to generated samples in the hopes of getting their distributions to overlap more</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*g9SnFEEW7w0A3Z1lt7GvfQ.png" /></figure><p>In this article, I’m going to focus primarily on Wasserstein GAN and then briefly remark gradient penalty and spectral norm, but do keep in mind that things like least-squares GAN and instance noise are also viable choices</p><h4>Wasserstein GAN</h4><p>The high level intuition is that the Jensen-Shannon divergence used by the classic GAN doesn’t have any way to account for distance. Essentially if you have this scenario:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*iHCqplBeyZtqxLwBpFLbDg.png" /></figure><p>You can say these two distributions are really far apart. Or you can have this scenario and notice that these two distributions are really close together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*vxScjaKQ4PbLTsDkBbxBUQ.png" /></figure><p>In terms of JS divergence, these two cases are about the same because in both cases the overlap between the distributions is negligible. So, the JS divergence, KL divergence and most other divergences that purely use the probabilities are almost identical in these two cases, even though clearly the bottom one is much much better. This is the high-level reason why it is so difficult to get a meaningful gradient in a GAN when the generator is very bad: because a good gradient should tell you that the way to improve the situation up above is to move towards a situation down below, but if your divergence measure thinks these two distributions are almost the same, then of course it’s not going to have much gradient.</p><p>The reason that this is true mathematically is if you look at the form of the JS divergence in the form of the of the GAN objective, you’ll see that basically it’s expressed in terms of log probabilities under one distribution in expectation under another distribution. So if p data is approximately zero for all the x’s where pG is not zero and pG is approximately zero for all the x’s where p data is not zero, then these expressions will just not give you any meaningful gradient. That basically explains why the top situation is considered to be very similar to the bottom situation, as far as JS divergence is concerned, despite the fact that in the bottom case these distributions are really close together.</p><p>What we can do to rectify this problem is to try to come up with a way to train a GAN with a different divergence measure that better captures how far apart two distributions are. Here’s how you can think about a better metric: consider how far apart all the bits of probability are in Euclidean space; imagine those distributions are basically piles of material piles. How far do you have to travel to move the dirt from one pile into another? This is sometimes referred to as an optimal transport problem. How far do you have to go to transport one distribution to another? The total distance you have to travel is how far apart these two distributions are.</p><p>Wasserstein distance is formally defined as the expected value of the distance between y and x, where y and x are distributed according to the optimal choice of joint distribution gamma. So, you find the best gamma for minimizing this expected value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*Pql8lu_vUGwkGIQR545XSQ.png" /></figure><p>Gamma is a joint distribution over x and y, where the marginal with respect to x is p data and the marginal with respect to y is pG. The intuition is that correlations between x and y in gamma(x,y) indicate which x should be transported to which y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*X1yF4uaMgjh82d7_TgX01g.png" /></figure><p>In order to evaluate the Wasserstein distance, you find the gamma that minimizes the expected value of these distances, that minimizes the discrepancy between the x and the y for every y that goes to that particular x. Intuitively, finding gamma is like finding the optimal plan for moving all the points in p data into pG.</p><p>Unfortunately, actually learning gamma directly like this is very very hard, because p data is unknown and gamma(x,y) might itself be some really really complex distribution</p><p>There’s a really cool theorem that we can use based on Kantorovich-Rubinstein duality, which provides us with a much more tractable way to solve for the Wasserstein distance. The statement is that the Wasserstein distance is also equal to the supremum over all possible functions f of the expected value under p data of f minus the expected value under pG of f:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*MEJdFqmazEGUmVSQxVupHQ.png" /></figure><p>The crude intuition is that f is gonna come from the same place where you get a Lagrange multiplier. So, you have a constraint on gamma, which is the marginals of gamma need to match p data and pG and you’re gonna basically take the dual of that. The really appealing thing about this expression for the Wasserstein distance is that it expresses the difference of expectations under pG and p data, just like a regular GAN</p><p>The supremum was taken over this funny expression that says:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*S70jPQR-FAg1VDbGO9sgHQ.png" /></figure><p>That’s shorthand for saying that you should do this over functions that are 1-Lipschitz. This means that the difference between f of x and f of y should be less than or equal to the difference between x and y. This is kind of equivalent to saying that the function is bounded slope — so it should never be too steep, because if f is too steep, then it can arbitrarily maximize f of x under p data and arbitrarily minimize it under pG. This limit on slope is a kind of speed limit on how fast you can travel when you’re carrying bits of one distribution to another.</p><p>How do we enforce that the slope of f should be bounded by some constant? That is basically the hard part of instantiating WGAN. Here’s an idea, which is not necessarily the best one, but it’s one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*1RyoAwTS-GIypCqSXpVl4A.png" /></figure><p>If you have just a 1-layer network, so one linear layer followed by a ReLU non-linearity and all of your entries in W are between -0.01 and +0.01, then the slope can’t be bigger than 0.01 x D.</p><p>If you have a 2-layer network, then you can constrain all the entries in both weight matrices to be between -0.01 and +0.01. Then your slope is also going to be bounded; of course it’s a lot bigger than before, because you’re actually multiplying these w’s together, but it’s still bounded by a constant so this doesn’t guarantee that it’s 1-Lipschitz, but it does guarantee that it’s something-Lipschitz for some constant, which means the slope will be bounded, which means that you will get some multiple of the Wasserstein distance.</p><p>The caveat is that weight clipping is clearly terrible as a way to enforce a Lipschitz constraint. If the clipping parameter is large, then it can take a long time for any weights to reach their limit, thereby making it harder to train the critic until optimality. If the clipping is small, this can easily lead to vanishing gradients when the number of layers is big, or batch normalization is not used.</p><p>But if we want to work through this Wasserstein GAN procedure, here’s how it works. We would have our generator just like before and we would have a discriminator that now instead of outputting the probability that the image is real, it actually just outputs a real number. That real number is unconstrained, so you just have a bunch of linear layers with ReLUs and no sigmoid at the end. The discriminator is going to use weight clipping, so here’s how that’s going to work.</p><p>Every iteration of your stochastic gradient algorithm you would update the discriminator using the WGAN objective. Then, you would clip all the weight matrices inside theta to be between some constants and that would ensure that the discriminator is k-Lipschitz for some fixed finite k. Finally, you would update your generator to maximize the expected value of f of G(z)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*QXzqy5Zroq8Sk1cFHuLo2A.png" /></figure><p>How do we do better discriminator regularization, as weight clipping is a terrible way to enforce a Lipschitz constant?</p><ul><li>One very simple and very effective method is called gradient penalty. If what we started with is the idea that we want to bound the slope, why don’t we just directly write down an expression for the slope and just add that to our objective?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*OPay1_-29lmv42wtOE23jw.png" /></figure><ul><li>Spectral norm is a somewhat more complex approach. The trouble with gradient penalty is that it’s not actually a constraint, it’s just a penalty. So you really need a Lipschitz constraint, but this is just giving you a penalty. If you actually want a constraint, you can bound the Lipschitz constant in terms of singular values of each weight matrix in your network.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*2SVE4-XedQeBxFlmyLDXXQ.png" /></figure><p>If your function f of x is a composition of multiple functions, the Lipschitz constant can be written as a composition of three functions. All we have to do is to bound the Lipschitz constant of every layer of our network. The maximal slope of ReLUs is one, so you don’t have to worry about them; the maximal slope of linear layers is the spectral norm of w, which is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*wHg_17N6vE5BzOjgtCTzzw.png" /></figure><p>All you have to do is to ensure after every step that the spectral norm of every weight matrix in your network is less than or equal to one; to ensure this, you just divide every weight matrix by its spectral mass</p><h4>Summary</h4><p>GAN training is really hard, because the discriminator can provide poor gradients. Various tricks can make this much more practical. For example, you can have:</p><ul><li>Smooth real-valued discriminators (LSGAN, WGAN, WGAN-GP, spectral norm)</li><li>Instance noise</li></ul><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d22beb83edc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Deep reinforcement learning with Q-functions]]></title>
            <link>https://samuelebolotta.medium.com/5-deep-reinforcement-learning-with-q-functions-c79ee8ab4b2?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c79ee8ab4b2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligen]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Sun, 29 May 2022 15:36:26 GMT</pubDate>
            <atom:updated>2022-05-29T18:29:30.903Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fifth of a series of articles in which I summarize the lectures from CS285 held by Professor Sergey Levine, to whom all credit goes. All images are taken from his lectures. <a href="https://samuelebolotta.medium.com/1-an-introduction-to-deep-reinforcement-learning-c5ab792af013">This article</a> I wrote is an introduction to deep reinforcement learning. <a href="https://samuelebolotta.medium.com/3-actor-critic-algorithms-779f14465b74">Actor-critic algorithms</a> build on the policy gradient framework that we discussed in <a href="https://samuelebolotta.medium.com/2-deep-reinforcement-learning-policy-gradients-5a416a99700a">this article</a>. On top, they’re also augmented with learned value functions and Q-functions, which we discussed <a href="https://samuelebolotta.medium.com/4-value-function-methods-17f2c898a00d">in this article.</a></p><p>Although we learned that value-based methods in general are not guaranteed to converge, in practice we can actually get some very powerful and very useful reinforcement learning algorithms out of them and that’s what we’ll talk about today.</p><h4>Problems with online Q iteration algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*Scm4YwC05gf2c5AgycT25g.png" /></figure><p>First, we learned that the update in step 3, even though it looks like a gradient update, is not actually the gradient of any well-defined objective — so Q-learning is not gradient descent.</p><p>Second, when you sample one transition at a time, sequential transitions are highly correlated. So the state I see at timestep t is likely to be quite similar to the state that I see at time step t+1, which means that when I take gradient steps on those samples in step three, I’m taking gradient steps on highly correlated transitions. This violates commonly held assumptions for stochastic gradient methods and it has a pretty intuitive reason to not work very well. To understand why, let’s rewrite the algorithm by plugging in the equation for the target value right into the gradient update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*p2teIU-gc3fXwVDTFI6Vxg.png" /></figure><p>States that you see one right after the other are going to be strongly correlated and your target values are always changing, so even though your optimization procedure looks like supervised regression, in a sense it’s kind of chasing its own tail — it’s trying to catch up to itself and then changing out from under itself and the gradient doesn’t account for this change. The reason this might be a problem is if you imagine that this is your trajectory and you get a few transitions, you’ll locally overfit to these transitions, because you’re seeing very similar transitions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*GETwTOGE9wUf027Af1FRKQ.png" /></figure><p>Then you get some other transitions and then you overfit a little bit to those:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*ZkaUmqLRLjTjotBAmRg5_Q.png" /></figure><p>And so on. Then, when you start a new trajectory, your function approximator will have been left off at the point where it overfitted to the end of the previous one and will again be bad. So if it had seen all the transitions all at once it might have actually fitted all of them accurately, but because it’s seeing this very local highly correlated window at a time, it has just enough time to overfit to each window and not enough broader context to accurately fit the whole function.</p><p>We could borrow the same idea that we had in actor-critic: the particular solution we discussed was tto have multiple workers that each collect a different transition, collect a batch consisting of samples from all of these workers, update on that batch and repeat. This procedure can in principle address the problem with sequential states being highly correlated; the sequential states are still correlated, but now you get a batch of different transitions from different workers and across workers they are hopefully not correlated. So it doesn’t solve the problem fully, but it can mitigate it. Of course, just like we learned about in actor-critic, you could have an asynchronous version of this recipe where the individual workers don’t wait for a synchronization point, but instead query a parameter server for the latest parameters and then proceed at their own pace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*OQ-OFvSguyKTvU1_XrdEGg.png" /></figure><p>In fact, with Q-learning this recipe should in theory work even better, because you don’t even need the workers to use the latest policy, so the fact that you might have a slightly older policy that is being executed on some of the workers is in theory not a major problem. However there is another solution to the correlated samples problem that tends to be quite easy to use and works very well in practice: replay buffers.</p><h4>Replay buffers</h4><p>Let’s think back to the full fitted Q-iteration algorithm: we would collect the dataset of transitions using whatever policy we wanted and then we would make multiple updates on that on that dataset of transitions. So we would label all the transitions with target values, then we might make a large number of gradient steps regressing onto those target values and then we might even go back and compute new target values before we even collect more data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*CQHQeenc1VCZCODQ8idz5w.png" /></figure><p>The online Q-learning algorithm is simply the special case of this, when k is set to one and we take one gradient step in step three and of course any policy for collection will work so long as it has broad support. In fact, we could even omit step one altogether; we could just load data from the buffer. This view presents Q-learning as a kind of data driven method where we just have a big bucket of transitions, we don’t really care so much where these transitions came from so long as they cover the space of all possibilities pretty well and we’re just going to crank away taking more and more updates on those transitions, alternating between computing target values and regressing onto those target values. So we could still take one gradient step in step three if we want, and then we’d get something that looks a lot like online Q-learning, only without the data collection. This gives us a modified version of the Q-learning algorithm with a replay buffer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*1iX4axHPk_sWiuB-sN5tOg.png" /></figure><p>In step one, instead of actually taking steps in the real world, we simply sample a batch of multiple transitions from our buffer and then in step two we sum up our gradient over all of the entries in that batch. So each time around this for loop, we might sample a different batch, IID (independently and identically distributed), from our buffer.</p><p>We have multiple samples in the batch, so we have a low variance gradient and our samples are no longer correlated, which satisfies the assumptions of stochastic gradient methods. We still unfortunately don’t have a real gradient, because we’re not computing the derivative through the second term, but at least the samples are not correlated. Where will the data come from? What we need to do is we need to periodically feed the replay buffer, because initially our policy will be very bad and maybe our initial very bad policy just won’t visit all the interesting regions of the space — so we still want to occasionally feed the replay buffer by using our latest policy, maybe with some epsilon greedy exploration to collect some data that achieves better coverage.</p><p>So, we have a buffer of transitions, on which we do off-policy Q-learning, and then periodically we deploy some policy back into the world, for example the greedy policy with epsilon greedy exploration, to collect a little bit more data and bring back some more transitions to add back to our buffer. That will refresh our buffer with behavior that hopefully gets better coverage.</p><p>Putting it all together, we can devise a full Q-learning recipe with replay buffers. Step one, collect a dataset of transitions, using some policy, and add this data to your buffer. Step two, sample a batch from B and then do some learning on that batch by summing over the batch this Q-learning pseudo-gradient. So, we’re going to calculate target values for every entry in the batch and then we’re going to do the current Q-value minus the target value times the derivative and then we’ll sum it over the whole batch. Since we sum over the whole batch, we get a lower variance gradient and since we sample the batch IID from our buffer, our samples are going to be decorrelated so long as our buffer is big enough. We can repeat this process k times.</p><h4>Target networks</h4><p>At this point we’ve almost developed a practical deep Q-learning algorithm that we could actually use, but there’s another component that we need to discuss to really get a stable and reliable procedure. We dealt with the problem of our samples being correlated by introducing a replay buffer — where we store all the data that we’ve collected so far and each time we have to take a step on the parameters of our Q function, we actually take that step using a batch of transitions that are sampled IID from our buffer.</p><p>But we still have this other problem to contend with, which is that Q learning is not gradient descent and it has a moving target. You could think of it as square error regression, except that the regression target itself changes all the time and it changes out from under us, which makes it very hard for the learning process to ever converge.</p><h4>What does Q-learning really have to do with regression?</h4><p>In the full fitted Q-iteration algorithm that I described before, step 3 performs what looks a lot like supervised learning, essentially regression onto target values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*N9tm6DcgLMW2uSrujmqWFA.png" /></figure><p>And in fact, step three in the full fitted Q-iteration algorithm will converge, but then your targets will change, so maybe you don’t want it to converge. Essentially trading to convergence on the wrong targets isn’t necessarily a good thing to do, which is why in practice we often use a much smaller number of gradient steps as few as one gradient step — and then we have this moving target problem, where every gradient step our targets change and our gradient is not accounting for the change in the targets.</p><p>So, intuitively what we would like to resolve this issue is something that’s a little bit in between: where we could have some of the stability of the full fitted Q-iteration algorithm, but at the same time don’t actually train the convergence. Here’s how we can do Q-learning with a replay buffer and a target network — and this is going to look like a kind of mix between the online Q-learning algorithm and the full batch fitted Q-learning algorithm.</p><p>We’re going to collect our data set using some policy and we add that policy to our buffer (this is now step two, as step one will be revealed later). We’re going to then sample a batch from this buffer and then we will make an update on the parameters of our Q-function. This update looks a lot like the update from before with replay buffers, but now the parameters and the max are different parameter vectors. Then of course after I make k of these back and forth updates, I go out and collect more data. Then I have a big outer loop, where after n steps of data collection, I’m going to actually update φ’ and set it to be φ. This looks a lot like the fitted Q-iteration procedure I had before, because essentially I’m making multiple updates with the same target values (if φ’ stays the same, then the entire target value stays the same), except that I might still be collecting more data in that inner loop. In step two, the data collection is now inside the updates to φ’ and the reason for doing this is because in practice you often want to collect data as much as possible, whereas for stability you typically don’t want to update your target network parameters quite as often. So, k could be between 1 and 4, so we might take between 1 and 4 steps between each time we collect more data, but n might be around ten thousand, so it might take as many as ten thousand steps before we change our target values. And that’s to make sure that we’re not trying to hit a moving target, because it’s very hard to hit a moving target with supervised regression. Initially we initialize both φ and φ’ to be essentially a random initialization and then after the first n steps, we’re going to update φ’, set it to be equal to φ, but then φ’ will remain static for the next n steps. And that means that step four starts looking a lot more like supervised regression and for that reason step four is easier to do, it’s much more stable and you’re much more likely to get an algorithm that learns a meaningful Q-function. So, your targets don’t change in the inner loop and that means that essentially step two, three and four look a lot like supervised regression, with the only real difference being that you might collect more data and that data could be collected using your latest, for instance, epsilon greedy policy.</p><p>Based on this general recipe, one of the things we can derive is the kind of classic deep Q-learning algorithm, which is sometimes called DQN. This particular special case looks like this: in step one, take an action and observe the resulting transition and then add it to the buffer. So, this looks a lot like online Q-learning. In step two, sample a mini batch from your buffer uniformly at random, so this mini batch might not even contain the transition that you just took in the real world. In step three, compute a target value for every element in your mini batch and compute these target values using your target network Qφ’. In step four, update the current network parameters φ by essentially taking the gradient for the regression onto those target values. Now, notice that so far φ has not been used anywhere else, except maybe in step one if you’re using an epsilon gradient policy and then in step five, which is only done every n steps, to update φ’ by replacing φ’ or φ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*TsJzbMCM6IViPMbg6Jt42w.png" /></figure><p>Something to note is that this procedure is basically a special case of the more general procedure at the top: you get this algorithm if you choose k=1. The numbering of the steps has been rearranged a little bit, but they are basically the same method.</p><p>There are some other ways to handle target networks that have been used in the literature and that could be worth experimenting with. There’s something a little strange about this way of updating target networks and here’s some intuition to illustrate some of the strangeness. Let’s say that I sampled my transition and then I updated my φ and then I sampled another transition and I updated my φ again. Blue boxes are step one, while green boxes are steps two, three and four:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*vN5Gg_NLUvBp9pxaRNIikQ.png" /></figure><p>Over here, on this step maybe my target network is obtained from the first step. So perhaps at the first step, when I started out, φ’ is equal to φ, so at the third step I get my target values back from the first step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*ZUIv_CKTkNHZyexi1CfgTQ.png" /></figure><p>And at the second step I get them from the first step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*Kd9of-0-LvHG_FFWoG12lw.png" /></figure><p>And at the fourth step I get them from the first step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*7o47knjptLOz3LakDW3mNA.png" /></figure><p>And then if the fourth step is where I update φ’ to be equal to φ (so basically if my n is equal to 4), then at the fifth step I get my φ’ from the preceding step. So it seems like at different steps the target values are lagged by very different amounts. If you’re at the step right after n, your target network is only one step old and if you’re right before a flip then it’s n — 1 step old. So it seems like at different points in time, your target values look more like moving target than others; if you’re right after that point where you set φ’ to φ, then your target really looks like a moving target and if it’s been a long time, then it really doesn’t look like a moving target. This is not actually that big of a problem, but it feels a little bit off. Then one common choice that you could do is you could use a different kind of update, which is kind of similar to Poliak averaging: a popular alternative is the set φ’ at every single step to be tau times the old φ’ plus 1 minus tau times the new φ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*PoVlhhFmkvMKxw0dw3x6aQ.png" /></figure><p>So, you can think of this as if φ’ is gradually interpolating between its old value and the new value defined by φ. You would choose tau to be a pretty big number, so for instance you might choose it to be 0.999, which means that one part out of a thousand is essentially coming from φ and the rest is coming from φ’. Of course the caveat is that this only makes sense if φ’ is similar to φ; because you’re gradually making φ’ more and more similar to φ, this procedure is actually all right.</p><h4>A general view of Q-learning</h4><p>Here, I want to discuss another view that we can take of these Q learning algorithms that maybe provides a little bit more of a unified perspective.</p><p>Here is the general Q-learning with replay buffers and target networks that I discussed before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*dRxGZwAtIdD7gJMb1MmDtQ.png" /></figure><p>And here is the fitted Q-iteration algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*MoZl8XQ2rYxkClxNwwrJ2Q.png" /></figure><p>They’re really kind of the same thing and if you view them as having the same basic processes running in parallel at different rates, then all of these methods can be unified into one kind of parallel framework.</p><p>In the fitted Q-algorithm, the inner inner loop is just SGD and the DQN method we had before is a special case where n equals one and k equals one, but all of them are really just special cases of this more general view. We have our our data set of transitions, our replay buffer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*_hodj7d2u5o9_tCsxHzOuw.png" /></figure><p>We periodically interact with the world and when we interact with the world, what we typically do is we take our latest vector φ, we construct some policy out of φ, for instance using epsilon-greedy or Boltzmann exploration, we send it out into the world and it brings back one or more transitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*qYvADMjr88UbmyLggt6saA.png" /></figure><p>And you can think of this not as a discrete decision that we make periodically, but it’s a continuous process that is always running. All of this process is step 1: the data collection process, which takes steps in the environment and each step it takes it sends back to our replay buffer. Our replay buffer is a finite size, we can’t just keep adding stuff to it forever, so we also have another process, an eviction process, which periodically throws things out of the buffer when it gets too big:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*CQxT3sHuywcb435w-SnUZA.png" /></figure><p>A very simple and reasonable choice is to simply structure the replay buffer as a ring buffer, where the oldest thing in the buffer gets thrown out when a new thing gets added in. Then you have your target parameters φ’, which are used to compute those target values, and you have your current parameters φ, which are the ones that you’re going to give to process one in order to construct that epsilon greedy policy to collect more data. Between these two parameters, there is process two, which updates the target parameters and is typically very slow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Dm6gn2-Wmg1cOzIi7KftIw.png" /></figure><p>And then you have process 3, which is kind of the main learning process. It loads a batch of transitions from the replay buffer, it loads in the target parameters φ’, it uses the target parameters to calculate target values for every transition in the batch that was sampled, it uses that to update the current parameters φ and then saves them back out into the the current parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*D5h8QJP5bL3NOU766DyKmw.png" /></figure><p>This is a graphical depiction of a general Q-learning recipe that encompasses all of the algorithms we’ve discussed. All of them can essentially be instantiated as special cases of this general processes.</p><ul><li>Online Q-learning is a special case where you evict immediately, meaning the size of your buffer is one. And then process one, two and three all run at the same speed and they all take one step sequentially. So process one takes one step, which means you collect one transition; process two takes one step, which means that your target values are always computed using the latest parameters; process three takes one step, which means that you make one gradient update.</li><li>The DQN algorithm that we mentioned before is also pretty similar: process one and process three run at the same speed, and then process two is very slow and the replay buffer is quite large (so you might store up to a million transitions). Part of why this starts looking so weird is that when your replay buffer is large, process one and process three are pretty heavily decoupled, because once it’s large enough the probability you’ll sample the transition that you just collected becomes pretty low. It does turn out that it’s actually quite important to collect data pretty quickly, so the performance of your Q-learning algorithm can degrade rapidly if you don’t collect data fast enough, but nonetheless process one and process three have quite a bit of buffer space between them.</li><li>The fitted Q-iteration algorithm can also be viewed as a special case of this. Process three is in the inner loop of process two, which itself is in the inner loop of process one. In this algorithm, you do your regression all the way to convergence, then you update your target network parameters and you might alternate these a few times; and then in the outer outer loop you pop all the way back out and collect more data</li></ul><p>But these are really not all that different, they’re just particular choices about the rates at which we run all these different processes and there’s something of course a little bit deeper about this, because if process two and process one are completely halted, then process three is just faced with a standard convergent supervised learning problem. By varying the rates of these different processes, by making them all run at different rates, we’re essentially mitigating the effects of non-stationarity. Because if the rate of process two, for example, is very different from process three, then to process three (which is running a lot faster) it will kind of look like everything is almost stationary. And this is the deeper reason why having these three different processes running at different rates can help Q-learning algorithms converge more effectively.</p><h4>Improving Q-learning</h4><p>Let’s discuss some practical considerations hat we need to take into account when actually implementing Q-learning algorithms and then some improvements that can make them work a bit better.</p><h4>Are our Q-values actually accurate?</h4><p>We can think of Q-values as this kind of abstract object that we use inside reinforcement learning to help us improve our policy and get that argmax, but a Q-function is also a prediction: it’s a prediction about the total reward that you will get in the future if you start in a particular state-action and then follow your policy. So, it makes sense to ask whether these predictions are actually accurate predictions. Do they match up with the reality?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEKgogj8dH4cxZ1n5_n9qw.png" /></figure><p>If we look at the basic learning curve where the x-axis is the number of iterations of Q-learning and the y-axis is the average reward per episode, and we look at it on a bunch of Atari games, we’ll see that for all of these Atari games our average per episode is going up. So, things are getting better. If we look at the average Q-values that are being predicted and that’s the two plots on the right, we’ll see that the Q-function is predicting larger and larger Q-values as training progresses. And that intuitively makes sense: as training progresses, our policy gets better, it’s getting higher rewards, so our Q-function should also predict that it’s getting higher Q-values.</p><p>Interestingly, the relative Q-values of different states and actions seem to make sense on a successful training run, but their actual absolute values will in practice not be very predictive of real values. In particular, the Q-function seems to systematically think it’s going to get larger rewards than it actually gets. This problem is sometimes referred to as overestimation in Q-learning and it has actually a fairly straightforward and intuitive reason.</p><h4>Overestimation</h4><p>Let’s look at how we’re computing our target values. When you compute your target value, you take your current target Q-function and you take the max of that Q-function with respect to the action. This max is the problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*6rII62U3aoQu3G2pEqfS_g.png" /></figure><p>Now, let’s forget about Q-values for a minute and let’s just imagine that you have two random variables, x1 and x2. You could think that maybe x1 and x2 are normally distributed random variables, so they have some true value plus some norms. You can prove that the expected value of the max of x1 and x2 is always greater than or equal to the max of the expected value of x1 and the expected value of x2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*bbNnlusYgSW2zpsIqXSKPA.png" /></figure><p>The intuition for why this is true is that when you take the max of x1 and x2 you’re essentially picking the value that has the larger noise and even though the noise for x1 and x2 might be zero mean, the max of two zero mean noises is not in general zero mean. You can imagine that one noise is positive or negative by fifty percent, the other is positive and negative by fifty percent, but when you take the max of the two, if either of them is positive, you’ll get a positive answer. So of course the probability that one of the two noises is positive is going to be pretty high. Now, if you imaeg that your Q-function has some noise, then when you take this max in the target value, you’re doing exactly this. Imagine that your Qφ’ for different actions represents the true Q-value of that action plus some noise, when you take the max in the target value then you’re actually selecting the positive errors and for the same reason that the expected value of the max of x1 and x2 is greater than or equal to the max of their expected values, the max over the actions will systematically select the errors in the positive direction, which means that it will systematically overestimate the true Q-values even if your Q-function initially does not systematically have errors that are positive or negative. For this reason, the max preferentially selects errors in the positive direction.</p><p>How can we fix this? If we think back to the Q-iteration, the way that we got this max was by basically modifying the policy iteration procedure. We had our greedy policy and we then sent that argmax back into our Q-function to get its value. This is just another way of saying that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*0PdFfyjLfIg0GjOQZEv2wQ.png" /></figure><p>This is actually the observation that we’re going to use to try to mitigate this problem. See, the trouble is that we select our action according to Qφ’, so if Qφ’ erroneously thinks that some action is a little bit better because of some noise, then that’s the action we’ll select and then the value that we’ll use for our target value is the value for that same action which has that same noise. But if we can somehow decorrelate the noise in the action selection mechanism from the noise in the value evaluation mechanism, then maybe this problem can go away. So, the problem is that the value also comes from the same Qφ’, which has the same noise as the rule that we used to select our action.</p><h4>Double Q-learning</h4><p>If the function that gives us the value is decorrelated from the function that selects the action, then in principle this problem should go away. So the idea is to just not use the same network to choose the action as the network that we use to evaluate the value. Double Q-learning uses two networks. One network which we’re going to call φa and another network which we’re going to call φb. φa uses the values from φb to evaluate the target values, but selects the action according to φa. So if you assume that φb and φa are decorrelated, then the action that φa selects for the argmax will be corrupted by some noise, but that noise will be different from the noise that φb has, which means that when φb evaluates that action, if the action was selected because it had a positive noise, then φb will actually give it a lower value. So the system will be kind of self-correcting and then analogously φb is updated by using φa as its target network by using φb as the actual selection rule. This is the essence of double Q-learning .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*cHGEByMu0ZGZzyGPZiL2Uw.png" /></figure><p>In practice, the way that we can implement double Q-learning is without actually adding another Q-function, but actually using the two Q-functions we already have. We can use the current and target networks.</p><p>If this is standard Q-learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*ZedHDgLbTPzdPtYH5DeSIw.png" /></figure><p>This is double Q-learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*YTTg_-VaA6K68L0H1UAeKQ.png" /></figure><p>We select the action using Qφ, but evaluate it using Qφ’. As long as φ’ and φ are not too similar, then these will be decorrelated. You could say that we do still have a little bit of the moving targets problem, because as our φ changes so does our action, but presumably the change in the argmax is a very sudden discrete change and it doesn’t happen all the time, so if you have three different actions, the argmax isn’t going to change as often. Of course, φ’ and φ are not totally separate from each other, because periodically you do set φ’ to be equal to φ, but in practice it actually tends to work pretty well and it mitigates a large fraction of the problems with overestimation.</p><h4>Multi-step returns</h4><p>There’s another trick that we can use to improve Q-learning algorithms and it’s similar to something that we saw in the actor-critic article. It’s the use of multi-step returns. This is our Q-learning target:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*7w_fUcWr8zHsoRZn2HA1WQ.png" /></figure><p>Where does the signal come from? If your initial Q-function is very bad, then almost all of your learning has to come from the reward and the second term is just contributing noise. On the other hand, if the Q-function is good, the target values do mostly heavy lifting. Early on in training your Q-function is pretty bad, so almost all of your learning signal really comes from the reward. Later on in training, your Q-function becomes better and the Q-values are much larger in magnitude than the rewards, so later on in training the Q-values dominate. But your initial learning period can be very slow if your Q-function is bad, because this target value is mostly dominated by the Q-value. This is quite similar to what we saw in actor-critic when we talked about how the actor critic style update that uses the reward plus the next value has lower variance but it’s not unbiased, because if the value function is wrong then your advantage values are completely messed up. And Q-learning is the same way: if the Q-function is wrong, then your target values are really messed up and you’re not going to be making much learning progress. The alternative that we had in the actor-critic lecture is to use a Monte Carlo sum of rewards, because the rewards are always the truth; they’re just higher variance, because they represent a single sample estimate. We can use the same basic idea in Q-learning. So, Q-learning by default does this kind of one step back up, which has maximum bias and minimum variance, but you could construct a multi-step target just like an actor critic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*TPdsP7myJTv3GJlSksnp4A.png" /></figure><p>The way that you can construct a multi-step target is by not just using one reward, but making a little sum from t’ = t to t + n — 1. You can verify that if n = 1, then you recover exactly the standard rule that we had for Q-learning, but for n larger than one you sum together multiple reward values and then you use your target network for the t + n step multiplied by gamma to the n. So this is sometimes called an n step return estimator, because instead of summing the reward for one step, you sum it for n steps. Just like with actor-critic, the trade-off is that it gives you a higher variance, because of that single sample estimate for r, but lower bias, because even if your Q-function is incorrect, now it’s being multiplied by gamma to the n and for large values of n, gamma to the n might be a very small number. So let’s talk about Q-learning with these n n-step returns: it’s less biased because the Q-values are multiplied by a small number and it’s typically faster early on, because when the target values are bad, those sums of rewards really give you a lot of useful learning signal. Unfortunately, once you use n step returns, this is actually only a correct estimate of the Q-value when you have an on-policy sample. The reason for this is that if you have a sample collected with a different policy, then that second step t+1 might actually be different for your new policy, because if on the second step you take a different action, that will match what you’re getting from your instant return. So, n step returns technically are not correct without policy data, whereas with off policy data technically you’re only allowed to use n equals one. Therefore, it is only correct when learning on-policy, because off-policy you end up using the action from the sample for those intermediate steps, which is not the action that your new policy would have taken. How can we fix this?</p><ul><li>We can ignore the problem</li><li>We can dynamically cut the trace, so we can choose n to only get on policy data. Essentially, we can look at what our deterministic greedy policy would do, we could look at what we actually did in the sample and we can choose n to be the largest value such that all of the actions exactly match what our policy would have done and that will also remove the bias. But this works well when data is mostly on policy and the action space is pretty small.</li><li>Another thing we can do is importance sampling: we can construct a stochastic policy and importance weight these n-step return estimators.</li><li>You condition the Q-function with some other additional information that allows you to make it off policy.</li></ul><h4>Q-learning with continous actions</h4><p>It is actually possible but somewhat more complicated to extend Q-learning procedures to the case when we have continuous actions.</p><p>What’s the problem with continuous actions? Well, the problem is that when you select your actions, you need to perform the argmax over actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*rz0XPXjLXlf-V5mQp6PVcg.png" /></figure><p>And doing it over discrete ones is straightforward: you simply evaluate the Q-value for every possible action and take the best one. But when you have continuous actions, it’s much harder. It is harder in two places: a) when evaluating the argmax policy and when computing the target value, which requires the max (or in the case of double Q-learning also an argmax).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*fCCcgSqyhaW7gH0EPZ279Q.png" /></figure><p>Moreoveor, the target value max is particularly problematic because that happens in the inner loop of training, so you really want to be very fast and very efficient. So how can you perform this max when you have continuous actions? There are three choices:</p><p><strong>Option 1: optimization</strong></p><p>Option one is to use a continuous optimization procedure, like for instance gradient descent. Gradient descent by itself can be pretty slow, because it requires multiple steps creating calculations and it happens in the inner loop of an outer loop learning procedure; so, there are better choices that we could use. Plus, our action space is typically low-dimensional, so in some sense it presents a slightly easier optimization problem than the kind of problems we typically take on with SGD.</p><p>So, it turns out that for evaluating the max with optimization, a particularly good choice is to use a derivative free stochastic optimization procedure. A very simple solution is to simply approximate the max over a continuous action as the max over a discrete set of actions that are sampled randomly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*c99S1Fje5YOrrSQ9B7o7jg.png" /></figure><p>For instance, you could sample a set of n actions, maybe uniformly at random, from the set of valid actions and then take the Q-value with the largest of those actions. That’s not going to give you an exact max, it’ll give you a very approximate max, but if your action space is pretty low-dimensional and you can bombard it with enough samples, this max might actually be pretty good. And of course if overestimation is your problem, this might actually suffer from overestimation less, because the max is less effective. This also has the advantage of being dead simple, it’s very efficient to parallelize, because you can essentially use your favorite deep learning framework and just treat these different actionsas different points in a mini batch and evaluate all of them in parallel. The problem is that it’s not very accurate, especially as the action space dimensionality gets larger. This random sampling method just doesn’t actually give you a very accurate max.</p><p>If you do want a more accurate solution, there are better algorithms are based on basically the same principle.</p><ul><li>Cross-entropy method (CEM) is a simple iterative stochastic optimization scheme and it consists of sampling sets of actions just like in the simple solution above, but then instead of simply taking the best one, cross-entropy method refines the distribution from which you sample to then sample more samples in the good regions and then repeat. And this can also be a very very fast algorithm if you’re willing to parallelize and you have a low dimensional action space.</li><li>CMA-ES: you can kind of think of it as a much fancier version of CEM, which is substantially less simple, but structurally very similar. And these methods work okay for up to about 40 dimensional action spaces, so if you use one of these solutions you simply plug this in place of your argmax to find the best action and the rest of your Q-learning procedure stays basically the same.</li></ul><p><strong>Option 2: function class that is easy to optimize</strong></p><p>Alternatively, you can use a function class that is inherently easy to optimize. So, arbitrary neural networks are not easy to optimize with respect to one of their inputs, but other functional classes have closed form solutions for their optima. One example of such a function class is the quadratic function; you could for example express your Q-function as a function that is quadratic in the action and the optimum for quadratic is a closed form solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*IZ88ozKWh9WzOlbZHw7Zyg.png" /></figure><p>Pne of the ways you could do this is with something called the Normalized Advantage Function (NAF). You have a neural network that outputs three quantities: a scalar valued bias, a vector value and a matrix value. The vector and matrix together find a quadratic function in the action, so this function is completely non-linear in the state, it can represent any function of the state, but for a given state the shape of the Q-value in terms of the action is always quadratic and when it’s always quadratic, then you can always find the maximum. In this case the maximum is just μφ of f. The reason that it’s called “Normalized” is that if you exponentiate it, then you get a normalized probability distribution. Now we’ve just made this maximization operation very easy at the cost of reducing the representational capacity of our Q-function, because if the true Q-function is not quadratic in the action, then of course the problem we have is that we can’t represent it exactly. So there’s no change to the algorithm, it’s just as efficient as Q-learning, but it loses some representational power</p><p><strong>Option 3: learn an approximate maximizer</strong></p><p>This is going to be a little bit similar to option one, only instead of running the optimization separately for every single argmax that we have to take, we’ll actually train a second neural network to perform the maximization. Remember that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*j9UAeQDb2gCFQ0_9Q5s8ng.png" /></figure><p>So as long as we can do that argmax, we can perform Q-learning. So the idea is to train another network μφ(s) such that μφ(s) is approximately the argmax of Q-φ. And you can also think of μφ(s) as a kind of policy. because it looks at a state and outputs the action, specifically the argmax action. To do this, we just solve for theta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*u3-3B9oq9lilL2V6dqab_w.png" /></figure><p>Now these are our targets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*27eTTmkvwTOwD-a9sybYqg.png" /></figure><p>The algorithm would thus look like this:</p><p>First, we take some action and we get and observation that we add to the buffer. Then, we sample a mini-batch from the buffer uniformly at random. Step three, we compute the target value by using μφ and target nets Qφ’. Step four, just like in Q-learning, we perform a gradient update on φ. Step five, we perform a gradient update on theta. The gradient on theta takes the derivative of the Q-value with respect to the action and then multiplies that by the derivative of the action with respect to theta, which is just back propagation through μ. Then, we’re going to update our target parameters φ’ and theta prime, for example using Polyak averaging. Then, we’ll repeat this process.</p><h4>Implementation tips and examples</h4><p>Q-learning methods are generally quite a bit more finicky to use than policy gradient methods, so they tend to require a little bit more care to use correctly. It takes some care to stabilize Q-learning algorithms and what i would recommend is to start off by testing your algorithms on some easy, reliable problems, where you know that your algorithm should work. This is just to make sure your implementation is correct, because essentially you have to go through several different phases of troubleshooting. You first have to make sure that you have no bugs, then you have to make sure that you tune your hyperparameters and then get it to work on your real problems, so you want to do the debugging before the hyperparameter tuning, which means that you want to do it on really easy problems, where basically any correct implementation should really work. Q-learning performs very differently on different problems.</p><p>Large replay buffers do tend to help to improve stability quite a lot, so using a replay buffer of a size about 1 million can be a pretty good choice. And at that point the algorithm really starts looking a lot more like fitted-Q iteration,which is perhaps part of the explanation for its improved stability. Lastly, Q-learning takes a lot of time, so be patient: it might be no better than random for a long time while that random exploration finds the good transitions and then it might take off once those good transitions are found. Start with high exploration, start with large values of epsilon and then gradually reduce exploration as you go, because initially your Q-function is garbage anyway, so it’s the random exploration that will be doing most of the heavy lifting, and then later on once your Q-function gets better, then you can decrease epsilon — so it often helps to put on a schedule.</p><h4>More advanced tips for Q-learning</h4><ul><li>The gradients of the Bellman error can be very big; something that’s a little troublesome is that if you have a really bad action, you don’t really care about the value of that action, but your squared error objective really cares about figuring out exactly how bad it is. So if you have some good actions that are like +10, +9, +8 and you have some bad actions that are -1.000.000, the bad actions will create a huge gradient although you really care that’s -1.000.000. In other words, it could also be 1.000 and it would result in the same policy, but your Q-function objective really cares about that and that will result in big gradients. What you can do is you can either clip your gradients or you can use what’s called a Huber loss:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*5DH5ji8kPbJTqxdGGwjLEA.png" /></figure><p>It is an interpolation between a squared error loss and an absolute value loss, so far away from the from the minimum the Huber loss looks like absolute value and close to the minimumit flattens out with a quadratic.</p><ul><li>Double-Q learning helpts a lot in practice, it is simple and it has no downsides.</li><li>N-step returns also help a lot, but have some downsides: they will systematically bias your objective, especially for larger values of n.</li><li>Schedule exploration and schedule learning rates, as well as Adam optimization can help too.</li><li>When debugging your algorithm make sure to run multiple random seeds, because you’ll see a lot of variation between random seeds, so you should run a few different random seeds to make sure that things are really working the way you expect.</li></ul><h4>Summary</h4><p>We talked about Q-learning in practice, how we can use replay buffers and target networks to stabilize it; we talked about a generalized view of fitted-Q iteration in terms of three processes, we talked about how double Q-learning can make Q-learning algorithms work a lot better; we talked about multi-step Q-learning and finally about how to make Q-learning work with continuous actions.</p><p><em>Feel free to drop me a message or:</em></p><ol><li>Connect and reach me on<strong> </strong><a href="https://www.linkedin.com/in/samuele-bolotta-841b16160/">LinkedIn </a>and <a href="https://twitter.com/SamBolotta">Twitter</a></li><li>Follow me on <a href="https://medium.com/@samuelebolotta">Medium</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c79ee8ab4b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Value function methods]]></title>
            <link>https://samuelebolotta.medium.com/4-value-function-methods-17f2c898a00d?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f2c898a00d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Thu, 26 May 2022 19:39:51 GMT</pubDate>
            <atom:updated>2022-05-26T21:19:02.340Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fourth of a series of articles in which I summarize the lectures from CS285 held by Professor Sergey Levine, to whom all credit goes. All images are taken from his lectures. <a href="https://samuelebolotta.medium.com/1-an-introduction-to-deep-reinforcement-learning-c5ab792af013">This article</a> I wrote is an introduction to deep reinforcement learning. <a href="https://samuelebolotta.medium.com/3-actor-critic-algorithms-779f14465b74">Actor-critic algorithms</a> build on the policy gradient framework that we discussed in <a href="https://samuelebolotta.medium.com/2-deep-reinforcement-learning-policy-gradients-5a416a99700a">this article</a>. On top, they’re also augmented with learned value functions and Q-functions.</p><h4><strong>Can we omit the policy gradient entirely?</strong></h4><p>What if we just learn a value function and then try to use that value function to figure out how to act? The intuition for why this should be possible is that the value function tells us which states are better than others, so if we simply select actions that go into the better states maybe we don’t need an explicit policy neural network anymore.</p><p>Here’s the the way to make this intuition a bit more formal. The advantage is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*Pn8TY4wKj04ftvBwTn6efg.png" /></figure><p>It is the difference between our Q value and our value and intuitively the advantage says how much better this action is than the average action according to the policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*6sTz7Reda0j6PSalg7UI_g.png" /></figure><p>Then arg max is the best action that we could take if we followed the policy thereafter. This means that the argmax is going to be at least as good as an action that we would have sampled from our current policy. We know it’s at least as good because it’s actually the best. The interesting thing is that this is true regardless of what the policy actually is. This arg max should immediately suggest to us that regardless of which policy we had before, even if it was a very bad random policy, we ought to be able to improve it by selecting the action according to the argmax of the advantage.</p><p>Maybe we could forget about representing policies explicitly and we could just use this argmax. This is the basis for value-based methods. We will construct new policies implicitly, so at every iteration we can construct a new policy that assigns a probability of one to the action a if it is the argmax of the advantage, and 0 otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*KWTc577bJWkrRruk2iWAWQ.png" /></figure><p>So now instead of taking a gradient ascent step on an explicit policy, we will construct this implicit policy as the arg max, so there’s no actual learning that happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*2HXd3xKD1EH_42A6dvj52Q.png" /></figure><p>This is called policy iteration. It’s called policy iteration because we iterate between evaluating the policy in step one and updating the policy in step two. Step two is pretty straightforward, but the big puzzle is really how to do step one. How do you evaluate the advantage for a particular state-action tuple for a given previous policy?</p><p>Like before we can express the advantage as the reward plus gamma times the expected value of the value at the next timestep minus the value at the current timestep. Let’s evaluate the value.</p><h4><strong>Dynamic programming</strong></h4><p>One way to evaluate the value in order to then estimate these advantages for policy iteration is to use dynamic programming. For now let’s assume that we know the transition probabilities and let’s assume that state and action are both discrete and small. This is not the setting we usually operate in in model-free RL, but we’ll assume that that’s our setting for now just so that we can derive the simple dynamic programming algorithm and then turn it into a model free algorithm later.</p><p>We could imagine that we can essentially enumerate our entire state and action space — we can represent it with a table. For instance, in this gridworld you have 16 states and 4 actions per state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*m0XRVhDqi_YZgN7w-sIjIQ.png" /></figure><p>Your transition probabilities T are represented by a 16 by 16 by 4 tensor. So, when we say we’re doing tabular reinforcement learning or tabular dynamic programming, what we’re really referring to is a setting like this.</p><p>Now we can write down the bootstraped update for the value function that we saw in the previous article, in terms of these explicit known probabilities. If we want to update the value of the state, we can set it to be the expected value with respect to the action sampled from the policy of the reward plus gamma times the expected value over the next state sampled from the transition probabilities of the value of the next state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*MHRbKbz1wpLcSZabagifag.png" /></figure><p>If you have a tabular MDP, meaning you have a small discrete state space and you know the transition probabilities, each of the expected values can be computed by summing over all values of that random variable and multiplying the value inside the parentheses by its probability. Then of course we need to know the value of the next state, so we’re just going to use our current estimate of the value function for that value. Once we calculate a value function this way, then we can construct a better policy pi prime by assigning probability 1 to the action that is the argmax of the advantage. This also means that our policy will be deterministic, so expected values with respect to this policy will be pretty easy to compute. We can simplify our bootstrapped update by removing the expectation with respect to the policy and just directly plugging in the only action that has non-zero probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*apV8-LLF5awUZ6VhbnlQbg.png" /></figure><p>Now we can plug this procedure into our policy iteration algorithm, specifically in step 1, when we evaluate the value of the state. You can prove that repeating this recursion eventually converges to a fixed point and this fixed point is the true value function.</p><h4><strong>Even simpler dynamic programming</strong></h4><p>You probably notice the way policy evaluation works: values propagate consistently on each iteration, but slowly. But even if we truncated policy evaluation after a single iteration, we could still improve upon the initial policy by taking the greedy policy of the Q-function estimation after<br>a single state-space sweep of policy evaluation. This algorithm is another fundamental algorithm in RL: it’s called value iteration (VI). VI can be thought of “greedily greedifying policies,” because we calculate the greedy policy as soon as we can, greedily. VI doesn’t wait until we have an accurate estimate of the policy before it improves it, but instead, VI truncates the policy-evaluation phase after a single state sweep.</p><p>Mathematically, the idea is that the argmax of the advantage is equal to taking the argmax of the Q function. Because if you remove the value of the state, which you can do since the argmax is with respect to the action, then you just get the Q-function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*UHeYivRkGP8QcWJHqe3i2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*x2lCFvN9yn9glILNTRmiCg.png" /></figure><p>Instead of getting the index from the argmax of the advantage and then plug it in the Q function to get the highest value, we can directly skip the step where we recover the indices and take the values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*ISHY-bmchh-XMfBBmTQtwg.png" /></figure><p>In step one, we set the Q values to be the reward plus the expected value of the value function of the next timestep and then in step two we set the value function to be the max over the action in the Q function table. Here, explicit policy computation is skipped, we don’t ever actually represent the policy explicitly, but you can think of it as showing up implicitly in step two because setting the value to be the max over the actions in the Q value table is analogous to taking the argmax and then plugging the index of the argmax into the table to recover the value. But since taking the argmax and then plugging it into the table is the same as just taking the max, we can basically short circuit that step and get this procedure</p><h4><strong>Fitted value iteration and Q-iteration</strong></h4><p>So far, we talked about how we can learn value functions represented in a tabular form, so there’s no neural net. Now let’s talk about how we can introduce neural networks and function approximation</p><p>First, how do we represent the value? So far, we talked about how we can represent it as a big table. However, let’s say that you’re playing a videogame from images: in this video game the number of possible states, if you have a 200 by 200 pixel image, is 255, which is the number of values that each pixel can take on, raised to the third power because there are three color channels, raised to the power 200 times 200. Maintaining a table over these many entries is impossible: this is more than the number of atoms in the universe. This is known as the curse of dimensionality: the simple fact that if you have a state space with many dimensions, the number of entries that you need in a table for tabular reinforcement learning is exponential in the number of dimensions.</p><p>So we’ll use a function approximator. We’re going to have a neural net value function that maps from states to scalar valued values. We can fit our neural net value function by doing least squares regression onto target values — and if we use the value iteration procedure from the previous section, then our target values are just the max over the action of the Q function.</p><p>Then our fitted value iteration algorithm would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*FxyygkZ2y3sVYlghTmllFA.png" /></figure><p>Step one, compute your target values by constructing the Q function for every possible action at each sampled state (we still assume that we have a discrete action space so we can perform this enumeration exactly); for every action we value its reward plus gamma times the expected value of the value at the next state. Do the max over that, that gives us our target value and then in step two regress onto those target values.</p><p>This is a reasonable algorithm that we could use, but it still requires us to know the transition dynamics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*HOPyVVe4CcAZxuAv_fA63w.png" /></figure><p>There are two ways in which this requires knowledge of the transition dynamics. First, it requires being able to compute that expected value and perhaps more importantly it requires us to be able to try multiple different actions from the same state, which we can’t do in general if we can only run policies in the environment instead of teleporting to a state multiple times and trying multiple actions from the same exact state</p><p>Let’s go back to policy iteration. In policy iteration, we alternated between evaluating the Q function and then setting the policy to be the greedy argmax policy. Step one in policy iteration involved policy evaluation, which required repeatedly applying this value function recurrence so we saw before. So what if instead of applying the value function recurrence to learn the value function, we instead directly constructed a Q function recurrence in an analogous way?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*ONVXObo6diraYhO64hWT7A.png" /></figure><p>If I wanted to construct the Q function at a particular state-action tuple, I could write exactly the same recurrence, except that now since the Q function is a function of a state and an action, I don’t need to evaluate the next state given the state and the policy, I just evaluate the next state given the state-action tuple that I’m training my Q function on. This might at first seem like a very subtle difference, but it’s a very important one, because now as my policy changes, the action for which I need to sample the next state doesn’t actually change, which means that if I have a bunch of samples (state, action, next state), I can use those samples to fit my Q function regardless of what policy I have. The only place where the policy shows up is as an argument to the Q function at the next state, inside of the expectation. And it turns out that this very seemingly very simple change allows us to perform policy iteration style algorithms without actually knowing the transition dynamics, just by sampling some tuples which we can get by running any policy we want. If we do this for step one in policy iteration, we would no longer require knowing the transition probabilities.</p><p>Can we do the “max” trick again?</p><p>Now we we seemingly took a step back, because before we derived policy iteration and then we simplified it to get value iteration, and the way that we got value iteration is by using this max trick. In value iteration, we saw that when we construct the policy we take the argmax, but then we simply take the value of that argmax action, so evaluating the value of the arg max is just like taking the max — so we can forego that step two and directly perform value iteration.</p><p>Can we do the same max trick with Q functions? This is what we did before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*1qolb-lzkmLUqFnzsQ_-Sw.png" /></figure><p>The way that we construct the fitted Q iteration algorithm is very much analogous to fitted value iteration. We construct our target value as the reward plus gamma times the expected value of the value function at the next state. Then, in step two we simply regress our Q function onto those target values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*uCl_FQaCveHG2axWP1Ty_A.png" /></figure><p>The trick of course is that we have to evaluate step one without knowing the transition probabilities. We’re going to do two things: first, we’re going to replace the value of the next state with the max over the action at the Q function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*Lqno6oiWS5j2umG4uGKlkg.png" /></figure><p>This is because we’re only approximating the Q function and not the value function.</p><p>Second, instead of taking a full expectation over all possible next states, we’re going to use the sampled state that we got when we generated that sample. And now all we need to run this algorithm is samples (state, action, next state), which can be constructed by rolling out our policy. This doesn’t require simulation of different actions, it only requires the actions that you actually sampled last time when you ran your policy.</p><p>This works even for off policy samples, so this algorithm does not make any assumptions that the actions were actually sampled from the latest policy, the actions could have been sampled from anything. You can store all the data you’ve collected so far, it doesn’t need to come from your latest policy.</p><p>Unfortunately, it turns out this procedure does not have any convergence guarantees for non-linear function approximation; however, if you use a tabular representation it is actually guaranteed to converge.</p><p>To put the pieces together, this is the fitted Q-iteration algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*abOKrLEfZ7oyFgg4qAvChg.png" /></figure><p>The algorithm works for a wide range of different policies. One of the parameters you have to choose is the number of such transitions you are to collect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*WoxSjKoT98kvPn80-K0tSQ.png" /></figure><p>Step two, for every transition that you sampled, calculate a target value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*nefhS_9NqpjK7uviRn4YUg.png" /></figure><p>Step three, train a new Q function, which means find a new parameter vector by minimizing the difference between the values of Q and the corresponding target value. One parameter you have to choose is the number of gradient steps that you will make in performing this optimization. Doing step three once doesn’t actually get you the best possible Q function; you could alternate step two and step three some number of times before going out and collecting more data.</p><h4><strong>From Q-iteration to Q-learning</strong></h4><p>Let’s talk a little bit more about what it means for fitted Q-iteration to be an off-policy algorithm. Just as a reminder: off-policy means that you do not need samples from the latest policy in order to keep running your RL algorithm. Typically, what that means is that you can take many gradient steps on the same set of samples or reuse samples from previous iterations, so you don’t have to throw out your your old samples and you can keep using them — which in practice gives you more data to train on.</p><p>Intuitively, the main reason that fitted-Q iteration allows us to get away with using off-policy data is that the one place where the policy is used is utilizing the Q function rather than stepping through the simulator. So as our policy changes what really changes is this max:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*6_eUDTG76_fXplAFpBDUNw.png" /></figure><p>Remember that the way that we got this max was by taking the argmax and then plugging it back into the Q value to get the actual value for the policy. So inside of that max you can kind of unpack it and pretend that it’s the Q function of the next state and of the argmax of Q. And that argmax is basically our policy, so this is the only place where the policy shows up and conveniently enough it shows up as an argument to the Q function, which means that as our policy changes, we do not need to generate new rollouts — you can almost think of this as a kind of model. The Q function allows you to sort of simulate what kind of values you would get if you were to take different actions and then of course you take the best action if you want to most improve your behavior. This max approximates the value of our greedy policy at the next state.</p><p>One way that you can think of fitted Q iteration structurally is that you have this big bucket of different transitions and what you’ll do is you’ll back up the values along each of those transitions and each of those backups will improve your Q value, but you don’t really care so much about which specific transitions they are so long as they kind of cover the space of all possible transitions quite well. So you could imagine you have this dataset of transitions and you’re just plugging away on this dataset, running fitted Q iteration, improving your Q function each time you go around the loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*T-0c_dJRU6OE3S84Sl6a_w.png" /></figure><h4><strong>What is fitted Q-iteration optimizing?</strong></h4><p>The step where you take the max improves your policy, so in the tabular case this would literally be your policy improvement. Your step three is minimizing the error of fit, so if you have a tabular update you would just directly write those targets into your table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*OmooJ-ZElK-q4KUC_3ycGg.png" /></figure><p>But since you have a neural network, you have to perform some optimization to minimize an error against those y’s. You could think of fitted Q-iteration as optimizing an error, the error being the Bellman error — the difference between the Q function and the targets. Tat is kind of the closest to an actual optimization objective, but of course that error itself doesn’t really reflect the goodness of your policy, it’s just the accuracy with which you’re able to copy your target values. If the error is zero, then you know that this is an optimal Q-function, but if the error is not zero, then you can’t really say much about the performance of this policy.</p><p>Now let’s discuss a few special cases.</p><h4><strong>Online Q-learning algorithms</strong></h4><p>You can instantiate a special case of the previous algorithm with particular choices for those hyperparameters which correspond to an online algorithm. In the online algorithm, you take exactly one action and observe one transition; then in step two , you compute one target value for the transition that you just took, very much analogous to how you calculate the advantage value in online actor-critic for the one transition that you just took; then in step three you take one gradient descent step on the error between your Q values and the target value that you just computed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*k49aGbnGWZ4vEb7tYvxCrQ.png" /></figure><p>The equation that I have here looks a little complicated but I basically just applied the chain rule of probability to that objective inside the argmin in step three. The error in those parentheses is sometimes referred to as the temporal difference error.</p><h4><strong>Exploration with Q-learning</strong></h4><p>While learning is progressing, using the greedy policy may not be such a good idea. The reason is our argmax policy is deterministic and if our initial Q function is quite bad, it’s not going to be random, but it’s going to be arbitrary. Then it will essentially commit our argmax policy to take the same action every time it enters a particular state and if that action is not a very good action we might be stuck taking that bad action essentially in perpetuity and we might never discover that better actions exist. So in practice, when we run fitted Q iteration it’s highly desirable to modify the policy that we use in step one to not just be the argmax policy, but to inject some additional randomness to produce better exploration. There are a number of choices that we make in practice to facilitate this.</p><p>One common choice is called epsilon greedy; this is one of the simplest exploration rules that we can use with discrete actions and it simply says that with probability 1 minus epsilon you will take the greedy action and then with probability epsilon you will take one of the other actions uniformly at random.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*_FgAIncJZ1ySH-nvaA7QLg.png" /></figure><p>If we choose epsilon to be some small number, it means that most of the time we take the action that we think is best and that’s usually a good idea — but we always have a small but non-zero probability of taking some other action which will ensure that if our Q-function is bad, eventually we’ll just randomly do something better. A very common practical choice is to vary the value of epsilon over the course of training and that makes a lot of sense because you expect your Q-function to be pretty bad initially and at that point you might want to use a larger epsilon. And then as learning progresses your Q-function gets better and then you can reduce epsilon</p><p>Another exploration rule that you could use is Boltzmann exploration, to select your actions in proportion to some positive transformation of your Q values. A particularly popular positive transformation is exponentiation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*OU1KT9AurA1Hi3ovjkp_Iw.png" /></figure><p>So if you take actions in proportion to the exponential of your Q values what will happen is that the best actions will be the most frequent and actions that are almost as good as the best action will also be taken quite frequently, because they’ll have similarly high probabilities. But if some action has an extremely low Q-value then it will almost never be taken. In some cases this kind of exploration rule can be preferred over epsilon greedy, because 1) With epsilon greedy the action that happens to be the max gets much higher probability and if there are two actions that are about equally good, the second best one has a much lower probability, whereas with this exponentiation rule if you really have two equally good actions, you’ll take them about an equal number of times 2) If you have a really bad action and you’ve already learned that it’s just a really bad action, you probably don’t want to waste your time exploring it, whereas epsilon greedy won’t make use of that.</p><h4><strong>Summary</strong></h4><p>We’ve discussed value-based methods, which don’t learn a policy explicitly, but just learn a value function or Q-function. We’ve discussed how if you have a value function, you can recover a policy by using the argmax and how we can devise this fitted Q-iteration method, which does not require knowing the transition dynamics — so it’s a true model-free method and we can instantiate it in various ways as a batch mode, off-policy method or as an online Q-learning method.</p><h4><strong>Value functions in theory</strong></h4><p>Let’s now delve into a bit of theory to explain what I meant before when I said that value-based methods with neural networks don’t in general converge to the optimal solution. To get started, let’s start with the the value iteration algorithm that we covered before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*1FyxRPms4XURZNKxnOYfEA.png" /></figure><p>It’s a pretty simple algorithm and it’s a little easier for us to think about, but we’ll get back to the Q-iteration methods a little bit later. To remind everybody, in value iteration we can think of it as having two steps. Step one, construct your table of Q values as the reward plus gamma times the expected value at the next state; step two, set your value function to be the max over the rows of that table. So you can think of it as constructing a table of values and then iterating this procedure. The question we could ask is: does this algorithm converge? And if it does converge, what does it converge to? One of the ways that we can get started with this analysis is, we can define a Bellman operator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*ibvxl_a26xZdNj0nvfPH6A.png" /></figure><p>When applied to a value function, this operator performs the following operations:</p><ul><li>First, it takes V and applies the operator T subscript a, which is a matrix with dimensionality SxS, where every entry in that matrix is the probability of the next state given the current state and action and where the action is chosen according to that max. So this is basically computing that expectation, which is a linear operator.</li><li>We multiply it by gamma</li><li>We add the vector r subscript a, which is a vector of rewards where for every state you pick the reward for the corresponding action and then outside of this you perform a max over the action. Crucially, this max is per element, so for every state we take a max</li></ul><p>This funny way of writing the the Bellman backup basically just captures the value iteration algorithm, which consists of repeatedly applying the operator B to the vector V</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*pWnCezusiVGX0DDU1vXNxw.png" /></figure><p>One interesting property that we can show is that v star (the value function for the optimal policy) is a fixed point of B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*OjrTtbb0n-U2wFgvdILykg.png" /></figure><p>If we find a value function that satisfies this equation, we have the optimal value function and if we use the arg max policy with respect to that, we’ll get the optimal polic, the policy that maximizes total rewards. That means that V star is equal to B times V star. That’s very nice: if we find a fixed point of B, then we’ll have the optimal value function. And furthermore it’s possible to show that v star always exists. This fixed point always exists, it’s always unique and it always corresponds to the optimal policy; so the only question that we’re left with is: does repeatedly applying B to V actually find this fixed point? In other words, does the fixed point iteration algorithm converge? If it does converge, it will converge to the optimal policy and it has a unique solution. I won’t go through the proof in detail, but the high-level sketch behind how we argue that value iteration converges is by arguing that it’s a contraction. We can prove that value iteration reaches v star because B is a contraction. What does it mean to be a contraction? It means that if you have any two vectors v and v bar, then applying B to both v and v bar will bring those vectors closer together, meaning that the norm of BV minus B * V bar is less than or equal to the norm of V minus V bar. In fact, it’s a contraction by some coefficient; that coefficient happens to be gamma, so not only is the norm of B*V minus B * V bar less than or equal to the norm of V minus V bar norm, but it’s also less than or equal to the norm V minus V bar times gamma. So, you will contract and you’ll contract by some non-trivial amount, which means that V and V bar will always get closer together as you apply B to them</p><h4><strong>Non-tabular value function learning</strong></h4><p>Regular value iteration can be written extremely concisely as just repeatedly applying this one step: V goes to BV.</p><p>Now, let’s go to the fitted value iteration algorithm. The fitted value iteration algorithm has another operation; it has a step two where you perform the arg min with respect to the parameters. One of the ways you can think of supervised learning is that you have some set of value functions that you can represent. That set is a continuous set that consists of all possible neural nets with your particular architecture, but with different weight values. So we’ll denote that set as a set omega. In supervised learning, we sometimes refer to this as the hypothesis set or the hypothesis space. Supervised learning consists of finding an element in your hypothesis space that optimizes your objective and our objective is the square difference between the value of the state and our target value. Now, what is our target value? Our target value is basically BV. You can think of the entire fitted value iteration algorithm as repeatedly finding a new value function v prime, which is the argument inside the set omega of the squared difference between v prime and BV, where BV is your previous value function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*DDZw-k47jeiuA0VLUrSDXA.png" /></figure><p>This procedure is itself also a contraction. When you perform this supervised learning, you can think of it as a projection in the L2 norm. You have your old v, you have your set of possible neural nets represented by this line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*-ZJipr0MKd26fQS2QN2eIg.png" /></figure><p>Omega is basically all the points on that line. When we construct BV, we might step off this line, so the point BV doesn’t lie in the set omega. When we perform supervised learning, when we perform step two of fitted value iteration, what we’re really doing is we’re finding a point in the set omega that is as close as possible to BV. And “as close as possible” means that it’s going to be at a right angle, so we’ll project down onto the set omega and it’ll be a right angle projection. That’ll get us v prime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*cN99yScjTFNWf_fJAl_4Jg.png" /></figure><p>We can define this as a new operator. We can call this operator Π for “projection” and we’re going to say that ΠV is just the argmin within the set omega of this objective, which is the L2 norm.</p><p>B is a contraction with respect to the infinity norm. Π is a contraction with respect to the L2 norm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*1GWzt0R1Iw_P6KOKyywmkg.png" /></figure><p>The reason why Π is a contraction is if you have any two points in euclidean space and project them on a line, they can only get closer to each other and they can never get further. Unfortunately, ΠB is not a contraction of any kind.</p><p>If you imagine that the blue dot is your starting point and the yellow star is the optimal value function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*f0D_Bt-t41lco7OuYaxnZQ.png" /></figure><p>You take a step, so your regular value iteration will gradually get closer and closer to the star:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*aO7x95xI_MM4efbMhEIshA.png" /></figure><p>If you have a projected value iteration algorithm, a fitted value iteration algorithm, then you’re going to restrict your value function to this line each step of the way, while your Bellman backup will get you closer to the star in terms of infinity norm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*OFZ8y18lrMBchtYDofC2iQ.png" /></figure><p>Then your projection will move you back onto the line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*dm9lAjPQ9No9RPrgNZHtow.png" /></figure><p>And while both of those operations are contractions, notice that V prime is now actually further from the star than V is. And you can get these situations where each step of the way actually gets you further and further from V star.</p><p>The sad conclusions from all this are that:</p><ul><li>Value iteration does converge in the tabular case</li><li>Fitted value iteration does not converge in general and it often doesn’t converge in practice</li><li>Fitted Q-iteration is the same: ΠB is not a contraction of any kind.</li></ul><p>Importantly, some might think that step 3 in this algorithm might be just gradient descent, which converges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*QsAM7ofAS-dDjmuUGeJzDg.png" /></figure><p>However, Q-learning is not gradient descent. It is not taking gradient steps on a well-defined objective and it’s because the target values in Q-learning themselves depend on the Q values — but you’re not considering the gradient through those target values. So the gradient that you’re actually using is not the true gradient of a well-defined function, and that’s why it might not converge. Now it’s probably worth mentioning that you could turn this algorithm into a gradient descent algorithm, by actually computing the gradient through those target values. The bigger problem is that the resulting algorithm is called the residual algorithm and it has very poor numerical properties and doesn’t work very well.</p><h4><strong>A sad corollary</strong></h4><p>Our actor-critic algorithm that we discussed before also is not guaranteed to converge on the function approximation for the same reason. There, we also do a Bellman backup, when we use a bootstrapped update and we do a projection when we update our value function. The concatenation of those is not a convergent operator, so fitted bootstrapped policy evaluation also doesn’t converge.</p><h4><strong>Summary</strong></h4><p>We talked about some value iteration theory, we discussed the operator for the backup, the operator for the projection; we talked about how the backup is a contraction and our tabular value iteration converges. We talked about some convergence properties of function approximation, where the projection is also a contraction, but because it’s a contraction in a different norm, backup followed by projection is not actually a contraction — and therefore fitted value iteration does not in general converge. And its implications for Q learning. We will find out in the next article that in practice, we can actually make all these algorithms work very well, but their theoretical properties leave us with a lot to be desired.</p><p><em>Feel free to drop me a message or:</em></p><ol><li>Connect and reach me on<strong> </strong><a href="https://www.linkedin.com/in/samuele-bolotta-841b16160/">LinkedIn </a>and <a href="https://twitter.com/SamBolotta">Twitter</a></li><li>Follow me on <a href="https://medium.com/@samuelebolotta">Medium</a></li></ol><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f2c898a00d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Actor-critic algorithms]]></title>
            <link>https://samuelebolotta.medium.com/3-actor-critic-algorithms-779f14465b74?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/779f14465b74</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Wed, 25 May 2022 20:06:25 GMT</pubDate>
            <atom:updated>2022-05-25T21:02:15.528Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the third of a series of articles in which I summarize the lectures from CS285 held by Professor Sergey Levine, to whom all credit goes. All images are taken from his lectures. <a href="https://samuelebolotta.medium.com/1-an-introduction-to-deep-reinforcement-learning-c5ab792af013">This article</a> I wrote is an introduction to deep reinforcement learning. Actor-critic algorithms build on the policy gradient framework that we discussed in <a href="https://samuelebolotta.medium.com/2-deep-reinforcement-learning-policy-gradients-5a416a99700a">this article</a>. On top, they’re also augmented with learned value functions and Q-functions.</p><h4><strong>Improving the policy gradient</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*7uxaqdxQgcz4UUevG9Y8eQ.png" /></figure><p>The reward to go is an estimate of the expected reward if we take action a in state s. Can we get a better estimate of this quantity?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*yJX2yt8uexNjyRqOtTvmbg.png" /></figure><p>Let’s imagine that this curvy line represents one of the trajectories that you sampled and your reward to go is calculated at a particular time step. So, this green circle represents the state coming from sample i and at time step t. At that point in time, we’re going to calculate an estimate of our reward to go and then we’re going to multiply that by the probability of our actions.</p><p>The way that we calculate this estimate is by summing up the rewards that we actually got along that trajectory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*4hVdf8fiZoMb1fkgQvbH5g.png" /></figure><p>But that trajectory represents just one of the many possibilities, so if we were to somehow accidentally land in the same exact state again and then run our policy just like we did on this rollout, we might get a different outcome simply because the policy and the MDP have some randomness in them. Right now, we’re using a single step estimate for the reward to go, but in reality there are many possibilities for what might happen next, so we would have a better estimate of the reward to go if we could actually compute a full expectation over all these different possibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*5U-JRPlx-hJHuru7B1PnBA.png" /></figure><p>And the reason that there are many possibilities is simply because there’s randomness in the system: our policy has randomness and our MDP has randomness, but this randomness can be quite significant, which means that our single sample estimate that we got by summing up the rewards that we actually obtained in that trajectory might be quite far off from the actual expected value.</p><p>This problem directly relates to the high variance of the policy gradient. The connection is that the policy gradient way of calculating the reward to go is a single sample estimate of a very complex expectation. The fewer samples you use to estimate an expectation, the higher the variance of your estimator will be. If we could somehow generate a million samples, then we would have much lower variance; if we could somehow calculate this expectation exactly, we would have much lower variance. So if we had access to the true expected reward to go, defined as the true expected value of the sum of rewards that we get starting from state i at timestep t and action i at timestep t, then the variance of our policy gradient will be much lower. Then, if we had this Q-function, we could simply plug it in in place of the reward to go and get a lower variance policy gradient.</p><p>In the previous article, we also saw how baselinescan lower the variance of a policy gradient even further. Can we apply a baseline even when we have the true Q-function? The answer is yes. We can subtract some quantity b:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*pdSpzK-71dizI6eMp56bvQ.png" /></figure><p>Where the average reward is a good choice for b, although not the optimal choice. So, what do we average? We could average Q values and then we will have this appealing property that the policy gradient will increase the probability of actions that are better than average and decrease the probability of actions that are worse than average. But it turns out that we can lower the variance even further, because the baseline can actually depend on the state. It can’t depend on the action, because that leads to bias, but you can make it depend on the state. So, if you make the baseline depend on the state, a better thing to do would be to compute the average reward over all the possibilities that start in that state. Not just the average reward over all possibilities of that time step, but specifically in that specific state. And if you average your Q values over all the actions in a particular state, that’s simply the definition of the value function. A very good choice for the baseline is the value function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*L8gR2mZ_X5V6W88ri23M_w.png" /></figure><p>The difference between the Q value and the value function represents your estimate of how much better that action a is on average than the average action you would take in the state s from sample i at timestep t. This Q-V term is so important that we have a special name for it: we call it the advantage function, because it represents how advantageous the action a from sample i at timestep t is as compared to the average performance that you would expect the policy to get in the state s from sample i at timestep t.</p><h4><strong>State and state-action value functions</strong></h4><p>A Q function, or state-action value function, represents the total expected reward that you expect to get if you start in state s, take action a and then follow your policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*vW5fPCOLX0AgLkVEe6DRfw.png" /></figure><p>The value function is the expected value over all the actions in state s under your current policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*Q-u7qqFQXBVBAR5_DmUeIQ.png" /></figure><p>The advantage function is the difference between these two quantities and the advantage function represents how much better the action a is as compared to the average performance of your policy in state s. So we can get a very good estimate of the policy gradient if we simply multiply the gradient of the logarithm of the policy by the advantage value.</p><p>Of course, in reality we won’t have the correct value of the advantage, we’ll have to estimate it for example using some function approximator. So, the better our estimate of the advantage, the lower our variance will be. It’s also worth mentioning that the kind of actor-critic methods that we’ll discuss in today’s article don’t necessarily produce unbiased estimates of the advantage function. So while the policy gradient we’ve discussed so far has been unbiased, if your advantage function is incorrect, then your entire policy gradient can also be biased. Usually, we’re okay with that because the enormous reduction in variance is often worth the slight increase in bias that we obtain from using approximate Q-values and value functions.</p><p>To summarize the conventional policy gradient uses a kind of a Monte Carlo estimate of the advantage calculated by using the one sample that you have in the remainder of the current trajectory by summing up the rewards in your trajectory and subtracting a baseline. This is an unbiased but high variance single sample estimate and we can replace it with an approximate advantage function which itself is usually calculated from an approximate Q function or an approximate value function — and get a much lower variance estimate.</p><h4><strong>Value function fitting</strong></h4><p>Fitting value functions: we have three possible quantities, namely Q, V and A. Ultimately, we want A, but the question we might ask is: which of these three should we fit and what should we fit it to?</p><p>The Q function is the expected value of the reward that we’ll get when we start from state s, take action a and then follow our policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*KV0YBQ8k_Y5VQEWowp6aTg.png" /></figure><p>One very convenient property of this is that because s and a are not actually random variables, we can rewrite the Q function as simply the current reward plus the expected value of the reward in the future — because the current reward depends on the state and on the action, and they are not random.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*KI3I_iIcbGQOMLKkGRCwJg.png" /></figure><p>This quantity that we’re adding is simply the expected value of the value function at the state s (t+1) that we will get when we take action a in state s t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*iIVDHx0l5wULAF4pn-x75A.png" /></figure><p>We can similarly write the Q function in terms of the value function as the current reward plus the expected value of the reward of the value function of the next time step. The expectation here is of course taken with respect to the transition dynamics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*aOCH0QwHU8lmXHD85tjJJg.png" /></figure><p>We can make a small approximation where we could say that the actual state s (t+1) that we saw in the current trajectory is kind of representative of the average s (t+1) that we’ll get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*NQT-f7gGEQ5WGmM1pkUQnQ.png" /></figure><p>At this point, we’ve made an approximation. This is not an exact equality, we’re essentially approximating the distribution over states of the next time step with again a single sample estimator. But now it’s a single sample estimator for just that one time step and everything after that is still integrated out as represented by the value function.</p><p>The reason that we would want to do that is because if we then substitute this approximate equation for the Q value into the equation for the advantage, we get this very appealing expression where the advantage is now approximately equal to the current reward plus the next value minus the current value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*7pNP2Hv-GcjyMvNMBUBVAw.png" /></figure><p>This is still an approximation because, to be exact, the next value needs to be in expectation over all possible values of s (t+1), whereas we’ve just substituted the actual s(t+1) that we saw. But what’s very appealing about this equation is that now it depends entirely on V, and V is more convenient to learn than Q or A — because Q and A both depend on the state and the action, whereas V depends only on the state. When your function approximator depends on fewer things, it’s easier to learn because you won’t need as many samples. So maybe what we should do is just fit the current value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*WSIA6ZStsUhs6UAEMytsBA.png" /></figure><p>When we fit the current value, we would have some kind of model such as a neural network that maps states s to approximate values. Let’s talk about the process of fitting the current value; this process is sometimes referred to as policy evaluation, because the current value represents the value of the policy at every state, so calculating the value is evaluation.</p><h4><strong>Policy evaluation</strong></h4><p>One thing that we could do is we could use Monte Carlo policy evaluation; in a sense, this is what policy gradients do. We run our policy many many times and then sum together the rewards obtained along the trajectories generated by the policy and use that as an unbiased, but high variance estimate of the policy’s total reward. So we could say that the value at state s(t) is approximately the sum over all the rewards that we saw after visiting state t along the trajectory that visited state s(t). Ideally, what we would like to be able to do is sum over all possible trajectories that could occur when you start from that state, because there’s more than one possibility. Unfortunately, in the model free setting, this is generally impossible because this requires us to be able to reset back to the state s(t) and run multiple trials starting from that state. Generally, we don’t assume that we’re able to do this; we only assume that we’re able to run multiple trials from the initial state.</p><h4><strong>Monte Carlo evaluation with function approximation</strong></h4><p>What happens if we use a neural network function approximator for the value function with this kind of Monte Carlo evaluation scheme? At every state that we visit, we sum together the remaining rewards and that will produce our target values, but then instead of plugging the “reward to go”’s directly into our policy gradient, we’ll actually fit a neural network to those values and that will actually reduce our variance. This is because even though we can’t visit the same state twice, our function approximator or our neural network will actually realize that different states that we visited in different trajectories are similar to one another. This is essentially generalization — it means that your function approximator understands that nearby states should take on similar values. It’s not as good as making multiple roads from the same state, but it’s still pretty good.</p><p>The way that we would do this is we would generate training data by taking all of our rollouts and for each state along every rollout we create a tuple consisting of the state s from sample i at timestep t and a label corresponding to the sum of rewards that we saw starting from s(i,t). We are going to call these labels y(i,t), which are the targets. Then we’ll solve a supervised regression problem; we’ll train our neural network value function, so that its parameters minimize the sum over all of our samples of the squared error between the value function’s prediction and the single sample Monte Carlo estimate of the value at that state. Of course if our function approximator massively overfits and produces exactly the training label at every single state, then we wouldn’t have gained much as compared to just directly using the y(i,t) values in our policy gradient, but if we get generalization we’ll actually get lower variance, because this function will now average out the dissimilar labels at similar states.</p><h4><strong>Can we do better?</strong></h4><p>The ideal target that we would like to have when training our value function is the true expected value of rewards starting from the state s(i,t).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*Xw7b_5a7NMWgAYIZy-J-iQ.png" /></figure><p>The Monte Carlo target that we used before uses a single sample estimate of this quantity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*hMH8VrMpFpXaT_MNMbiKqA.png" /></figure><p>But we can also use the relationship that we wrote out before, where we saw that a Q function is simply equal to the reward of the current time step plus the expected reward starting from the next time step. And if we write out this quantity then we can perform the same substitution as before and actually replace the second term in the summation with our estimate of the value function. This is a better lower variance estimate of the reward to go than our single sample estimator. This says: let’s use the actual reward that we saw the current time step plus the value at the actual state that we saw the next time step. Of course we don’t know the value, so we’re going to approximate that simply by using our previous function approximator. We’ll assume that our previous value was okay and we’ll plug it in in place of the current value. This is what is called a bootstrap estimator. Here we’re directly going to use the previous fitted value function to estimate this quantity.</p><p>So now our training data will consist of tuples of the states that we saw and labels that correspond to the reward that we actually got at that time step plus the estimate of the value function at the actual next state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*neXjZGNQdiGPJj8NJsDjAg.png" /></figure><p>This estimate might be incorrect, but as we repeat this process hopefully these values will get closer and closer to the correct values and because the values are averaging together all possible future returns, we expect their variance to be lower. Now our target value is y(i,t):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*uAPVCe5dYwieVyID-pwuTw.png" /></figure><p>Our training process just like before is going to be supervised regression onto these targets. This is sometimes referred to as a bootstrapped estimate and the bootstrapped estimate has lower variance because it’s not using a single sample estimator, but it also has higher bias because it might be incorrect.</p><h4><strong>From evaluation to actor critic</strong></h4><p>A basic batch actor-critic algorithm can look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*exuo4Tb2eJNDzevDpBeGzg.png" /></figure><p>Step one is going to be to generate samples by running rollouts through our policy. Step two is to fit our approximate value function to those sampled rewards, instead of just naively summing up all the rewards. Step three, for every state-action tuple that we sampled, we evaluate the approximate advantage as the reward plus the approximate value of the next state minus the value of the current state. Step four, we use these advantage values to construct a policy gradient estimator by taking the gradient of the logarithm of the policy at every time step and multiplying it by the approximate advantage. Finally, step five like is to take a gradient descent step.</p><p>The part that we talked about when we discussed policy evaluation is mostly the step two: how do we actually fit the value function? We talked about how we can make a number of different choices. We could fit it to single sample Monte Carlo estimates, meaning that we actually sum up the rewards that we got along that trajectory, and that gives us our target values. We also talked about how we could use bootstrap estimates where we use the actual observed reward plus the estimated value at the next state by using our previous value function estimator and this gives us a few different options for how to fit the critic.</p><p>A little aside: let’s discuss what happens when we fit value functions with this bootstrap rule in infinite horizon settings. The trouble that we might get into is that if the episode length is infinite, then each time we apply this bootstrap rule our value function will increase. How can we modify this rule to ensure that we can always have finite values and that we can handle infinite horizon settings? One very simple trick is to assume that we want a larger reward sooner rather than later. The way that we’re going to do this is we will introduce a little multiplier, gamma, in front of the value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*J5zoCiM4pmScVK5NYIfJmQ.png" /></figure><p>0.99 works really well. This number changes your MDP. Imagine having four states. You can transition between those four states and those transitions are governed by some probability distribution. When we add gamma, one way we can think about this is that we’re adding a fifth state, a death state, and we have a probability of one minus gamma of transitioning to that death state at every time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*5vwLuaARyagjZVPA8aP2PA.png" /></figure><p>Once we enter the death state, we never leave, so there’s no resurrection in this MDP, and our reward is always zero — so that means that the expected value for the next time step will always be expressed as gamma times its expected value in the original MDP plus one minus gamma times zero.</p><h4><strong>Discount factors</strong></h4><p>First, could we introduce discount factors into regular Monte Carlo policy gradients? Yes, we can just take that single sample reward to go calculation and we can put gamma into it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*iYk0BX3QMTtGZ5j-UZFg5g.png" /></figure><p>The equation I have here is exactly the reward to go calculation we had before, except that now I’ve added this gamma raised to the power t prime minus t in front of the reward. That means that the first reward has a multiplier of one, the next one gets a multiplier of gamma, the next one gets a multiplier of gamma squared and so on. So, we’re much more affected by rewards that happen closer to us in time. This type of estimator is essentially the single sample version of what you would get if you were to use the value function with a discounted bootstrap</p><p>There is another way that we can introduce a discount into the Monte Carlo policy gradient, which is very similar but has a subtle and important difference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*X-CqWTHf6ieldbBubBHvOg.png" /></figure><p>This option is saying that because you have this discount, not only do you care less about rewards further in the future, you also care less about decisions further in the future. So if you’re starting at time step one, rewards in the future matter less but also your decisions matter less — because your decisions further in the future will only influence future rewards. So, as a result you actually discount your gradient at every time step by gamma to the t minus one and essentially it means that making the right decision at the first time step is more important than making the right decision at the second time step, because the second time step will not influence the first time step’s reward.</p><p>This is in fact the right thing to do if you truly want to solve a discounted problem. But in reality the version that we actually usually use is option one. Think about a cyclic continuous RL task in which the goal is to make the agent run as far as possible. While we can model this as a task with discounted reward, in reality we really do want this guy to run as far as possible, ideally infinitely far — so we don’t really want the discounted problem. What we want to do is we want to use the discount to help get us finite values so that we can actually do RL, but then what we’d really like to do is get a solution that works for running for arbitrarily long periods of time.</p><p>What happens when we introduce the discount into our actor-critic algorithm? Well, the only thing that changes is step three:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*kwjjbde6fh4uJQ08nA9y6Q.png" /></figure><p>In step three, you can see that we’ve added a gamma in front of the value of the next step. One of the things we can do with actor-critic algorithms once we take them into the infinite horizon setting is we can actually derive a fully online actor-critic method. So far when we talked about policy gradients, we always used policy gradients in a kind of episodic batch mode setting, where we collect a batch of trajectories, each trajectory runs all the way to the end and then we use that batch to evaluate our gradient and finally update our policy. But we could also have an online version when we use actor-critic, where at every single time step we also update our policy. Here’s what an online actor-critic algorithm would look like: we would take an action, sampled from a probability distribution, and get a transition. In step two, we update our value function by using the reward plus the value of the next state as our target. Because we’re using a bootstrapped update, we don’t need to know what state we’ll get at the following time step; we just need the one next time step s prime. In step three, we evaluate the advantage as the reward plus the value function of the next state minus the value function of the current state. And then using this we can construct an estimate for the policy gradient by simply taking the gradient of the logarithm of the policy multiplied by the advantage that we just calculated and then we can update the policy parameters with policy gradient. And then repeat this process and we do this at every single time step.</p><h4><strong>Actor-critic design decisions</strong></h4><p>There are a few problems with this recipe when we try to do DRL. In order to actually instantiate these algorithms as DRL algorithms, we have to pick how we’re going to represent the value function and the policy. There are a couple of choices we could make.</p><p>One very reasonable starting choice is to have two completely separate networks — one network that maps a state to the value and one separate network that maps that same state to the distribution over actions. These networks have nothing in common.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*a-_fmFrjyfWN7rJSl242Fw.png" /></figure><p>This is a convenient choice because it’s relatively simple to implement and it tends to be fairly stable to train. The downside is it may be regarded as somewhat inefficient because there’s no sharing of features between the actor and critic; this could be a more important issue if for example you are learning directly from images and both these networks are convolutional neural nets maybe you would really want them to share their internal representations so that for example if the value function figures out good representations first, the policy could benefit from them. In that case you might opt for a shared network design where you have one trunk that maybe represents the convolutional layers and then you have separate heads — one for the value and one for the policy action distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*d3YWElARRYmFVEOuQNLSQQ.png" /></figure><p>This shared network design is a little bit harder to train, it can be a little bit more unstable because those shared layers are getting hit with very different gradients. The gradients from the value regression and the gradients from the policy gradient will be on different scales, they’ll have different statistics and therefore it might require more hyperparameter tuning in order to stabilize this approach. But it can in principle be more efficient because you have these shared representations.</p><p>There is another important point that we have to discuss before we get an actual practical deep reinforcement learning actor critic method and that’s the question of batch sizes. As described here, this algorithm is fully online meaning that it learns one sample at a time; so it takes an action, gets a transition, updates the value function on that transition and then updates the policy on that transition. Both updates use just one sample. Now, we know from the basics of deep learning that updating deep neural nets with stochastic gradient descent using just one sample is not going to work very well, so those updates are going to have a little too much variance. These updates will all work best if we have a batch and one of the ways that we could get a batch is by using parallel workers</p><p>Here’s the idea. This is the most basic kind of parallelized actor-critic. Instead of having just one data collection thread, you might run multiple simulators and each of them will choose an action in step one and generate a transition, but they’re going to use different random seeds so they’ll do things that are a little bit different. And then you will update, in step two and step four, using data from all of the threads together, so the update is synchronous, meaning that you take one step in step one for each of the threads, then collect all the data into your batch and use it to update the value function — and then use it to update the policy synchronously. Then you repeat this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*rcHPWT0AprrV9miTE0cWyA.png" /></figure><p>So this will give you a batch size equal to the number of worker threads. It can be a little bit expensive, because if you want a batch size 32, then you need 32 worker threads; but it does work decently well. It can be made even faster if we make it into asynchronous parallel actor-critic, meaning that we basically drop the synchronization point. Now we have these different threads that are all running at their own speed and when it comes time to update we’re going to pull in the latest parameters and we’re going to make an update for that thread but we will not actually synchronize all the threads together. So as soon as we accumulate some number of transitions from all the workers, we’ll make an update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*WYTioGf4hgwg1mFh0PrICw.png" /></figure><p>The problem with this approach of course is that the actual transitions might not have been collected by exactly the same parameters, so if one of the threads is lagging behind maybe its transition was generated by an older actor and then you will basically not actually update until you get transitions from faster threads and those will be using a newer actor. So in general all of the transitions that you’re pulling together into your batch here may have been generated with slightly different actors. They’re not going to be too different because these threads aren’t going to be running at such egregiously different rates, but they will be a little bit lagging behind. In fact, the asynchronous update is not mathematically equivalent to the standard synchronous update, because you have the small amount of lag which is similar to what you get with asynchronous SGD; but in practice it usually turns out that making the method asynchronous leads to gains and performance that outweigh the bias incurred from using slightly older actors. The crucial thing here is “slightly” older, because the actors are not going to be too old — if they are, then of course this won’t work.</p><p>This might get us thinking about another question: in the asynchronous actor critic algorithm, the whole point was that we could use transitions that were generated by slightly older actors. If we can somehow get away with using transitions that were generated by much older actors, then maybe we don’t even need multiple threads, maybe we could use older transitions from the same actor. Basically, we could use a history and load in transitions from that history and not even bother with multiple threads. That’s the principle behind off-policy actor-critic. The design of off-policy actor-critic is that now you’re going to have one thread and you’ll update with that one thread, but when you update you’re going to use a replay buffer of all transitions that you’ve seen and you will actually load your batch from that replay buffer. So you’re not going to necessarily use the latest transition, rather you’ll collect the transition store in the replay buffer and then sample an entire batch from that replay buffer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*wuO75paMZtHNXf_6Pz0mLA.png" /></figure><p>At this point we have to modify the algorithm because doing this naively won’t work. This batch that we loaded in from the replay buffer definitely came from much older policies, so it’s not like the asynchronous actor critic where the transitions came from just slightly older actors and we could just ignore that; now it’s coming from much older actors and we can’t ignore that we have to actually change our algorithm. Then of course we’re going to form a batch for each of these updates by using previously seen transitions.</p><p>In an off-policy actor-critic algorithm, we’re going to take an action as usual from our latest policy, get the corresponding transition and then instead of using that transition for learning we’ll actually store it in our replay buffer; then, we will sample a batch from that replay buffer. Then we’re going to update our value function using targets for each of these transitions in our batch. Then we’ll evaluate our advantage for each of the samples in our batch and then we’ll update our policy gradient by using that batch. So now the policy gradient is also averaged over n samples and then we’ll apply the policy gradient like before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*3VQzbVixXVi9Q9RRrz7AwA.png" /></figure><p>However, this algorithm is not going to work. The first problem is that when you load these transitions from the replay buffer, remember that the actions in those transitions were taken by older actors, so when you use those older actors to get the action and compute the target values, that’s not going to give you the right target value; it’ll give you the value of some other actor, not your latest actor. The second issue is that for that same reason you can’t compute the policy gradient this way; it is very very important, when computing the policy gradient, that we actually get actions that were sampled from our policy, because this needs to be an expected value under the policy. If that is not the case we need to employ some kind of correction such as importance sampling.</p><p>First, let’s talk about fixing the value function. If the value function tells you the expected reward you will get if you start in state s and then follow the policy, the Q function tells you the reward you’ll get if you start in state s, then take action a and then follow the policy. Notice here that there’s no assumption that the action actually came from your policy, so the Q function is a valid function for any action; it’s just that in all subsequent steps you follow the policy. So we will not learn V, but we will instead learn Q; this neural network will take in a state and an action and output a Q value. Otherwise, the principle behind the update is the same: we’re going to compute target values and then we will regress onto those target values. It’s just that now we’ll give the action as an input to the Q function. Another way to think about it is that we can no longer assume that our action came from our latest policy, so we’ll instead learn a state-action value function that is valid for any action so that we can train it even using actions that didn’t come from the policy, but then query it using actions from the policy.</p><p>The issue here is that before I was learning v and I was using v in my targets, but now I’m learning Q and yet I still need v for my target values. So where do I get that? Well, remember that the value function can also be expressed as the expected value of the Q function where the expectation is taken under your policy, so what we can do is we can replace the v in our target value with Q evaluated at the next action a, except that this action is not coming from our replay buffer, it is actually the action that your current policy would have taken if it had found itself in that state. We are exploiting the fact that we have functional access to our policy so we can ask our policy what it would have done if it had found itself in the in this old state, even though it never actually happened.</p><p>Now we’ve resolved our issue with the value function, but we have to deal with the policy gradient. All we’re going to do is we’re going to use the same trick, but this time we’re going to use it for the next action, we are going to use it for the current action. In order to evaluate the policy gradient, we just need to figure out an action sampled from the latest policy at the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*t8rAW90-W25v0nhc5BRbjg.png" /></figure><h4><strong>What else is left?</strong></h4><p>There is still a little bit of an issue, because the state that we’re actually using didn’t come from the state marginal of the latest policy, it came from the state marginal of an old policy. Unfortunately there’s basically nothing we can do here, so this is going to be a source of bias in this procedure and we’ll just have to accept it. The intuition for why it’s not so bad is because ultimately we want the optimal policy on pθ(s), but we get the optimal policy on a broader distribution, so our replay buffer will contain samples from the latest policy as well as many samples from other older policies so that the distribution is sort of broader than the one we want. For this reason, we’re not going to miss out on the states from our latest policy, we just also have to be good on a bunch of other states which we might never visit, so we’re doing kind of extra work, but we’re not missing out on important stuff and that’s the intuition for why this basically tends to work.</p><h4><strong>Some implementation details</strong></h4><p>Oftentimes there’s much fancier things we can do for step four, for example one thing we could use is something called the reparameterization trick which I’ll discuss in another article. There are also many fancier ways to fit the Q function and we’ll discuss this in the next two articles when we’ll talk about Q learning.</p><h4><strong>Critics as baselines</strong></h4><p>Now I’m going to talk about another way that we can use the critic by incorporating the critic as a baseline to the policy gradient and this is going to have some interesting trade-offs as compared to the standard actor critic algorithm that we’ve discussed so far.</p><p>This is the equation for the actor critic that we discussed so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*1EDIu9IpMcVFhex1o5zwxQ.png" /></figure><p>The actor critic consists of the grad log term multiplied by the reward plus gamma times the next value minus the current value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*214H1qj3HVRs6ZAdVp5DcA.png" /></figure><p>The policy gradient consists of the grad log term times the sum of the rewards to go minus a baseline.</p><p>The actor critic policy gradient estimator has the advantage that it drastically lowers the variance, because the functional approximator in the critic integrates in all those different possibilities for what might happen instead of relying on a single sample; unfortunately, the actor critic gradient estimator also has the disadvantage that it’s not no longer unbiased. The reason for that is that if your value function is slightly incorrect, which it might be because it’s a function approximator trained on a finite number of samples, then you can’t show anymore that in expectation this gradient will actually converge. On the other hand, the original policy gradient is unbiased, so even though it might have high variance, it’ll come out to the right value.</p><p>So, could we get a policy gradient estimator that is still unbiased but uses the critic in some other way to lower the variance? The answer is that we can we can actually construct a policy gradient estimator that has slightly higher variance than the actor critic version, but no bias like the policy gradient version. The way that we can do this is by using what’s called a state-dependent baseline. It turns out that we can prove that not only does the policy gradient remain unbiased when you subtract any constant b, it actually still remains unbiased if you subtract any function that depends on only the state and not on the action. A very good choice for the baseline is the value function, because you would expect this single sample estimator in expectation to come out to be equal to the value function, so if you use the value function as the baseline then the numbers that are multiplying the grad log should in expectation be smaller, which means that their variance is smaller, which means that the variance of your entire policy gradient is smaller. This doesn’t lower the variance as much as the full actor-critic algorithm, because you still have the sum over future rewards, but it’s much lower than a constant baseline and it’s still unbiased.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*JFc4tu7-1sp-MFmhpQ6Y3w.png" /></figure><p>What if we make the baseline depend on even more things, for example on the state and the action? Will we get an even lower variance that way? The answer is yes, but at that point things get much more complicated, so that’s what we’ll talk about now. Methods that use state and action dependent baselines are sometimes referred to as control variates in the literature.</p><h4><strong>Control variates: action-dependent baselines</strong></h4><p>The true advantages are approximate advantage that we use in policy gradients when we have a state dependent baseline. They are the sum of all future rewards minus the current value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*QZGfkSo8YnncGZxzMt7DnA.png" /></figure><p>This is nice because it has lower variance, but we can make the variance even lower if we subtract the Q value. If we do so, this has the nice property that it actually goes to zero if your critic is correct. So if your critic is correct and your future behavior is not too random, then you’d expect these quantities to eventually just converge to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*YgON82iD18lNOqSfxlxNYw.png" /></figure><p>Unfortunately if you plug in this advantage estimator into your policy gradient, the policy gradient is no longer correct because there’s an error term that you have to compensate for. Unlike the standard baseline which integrates to zero in expectation, an action dependent baseline no longer integrates to zero, it integrates to an error term and you have to account for that error term. So if you incorporate a baseline that depends on both the state and action and account for the error term, then you get this equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*wvxncbmzTaO1HfUC6fpl0g.png" /></figure><p>This equation is a valid estimator for the policy gradient even if your your baseline doesn’t depend on on the action, but in that case the second term basically vanishes; but if your baseline depends on the action, the second term is no longer zero. So the first term is just your policy gradient with your baseline, the second term is the gradient of the expected value under the policy of your baseline now. This second term looks a lot like the original policy gradient, so is this really any better? It turns out that this is actually a lot better in some cases. For example, in many cases the second term can actually be evaluated very very accurately. If you have discrete actions you can sum over all possible actions; if you have continuous actions then you can sample a very large number of actions, because evaluating the expectation of our actions doesn’t require sampling new states, so it doesn’t require actually interacting with the world, which means that you can generate many more samples from the same state, something that we could not do before when we had to actually make entire rollouts. Furthermore, in many continuous action cases, if you make a careful choice of the class of distributions on the class of Q functions, this integral also has an analytic solution. For example, the expected value of a quadratic function under a gaussian distribution has an analytic solution. So in many cases the second term can be evaluated in such a way that its variance is zero or very close to zero and the first term is low variance. This kind of trick can be used tocprovide a very low variance policy gradient, especially if you can get a good Q function estimator.</p><p>So far, we talked about ways that we can use critics and get policy gradient estimators that are unbiased, but can we also use critics and get policy gradients that are still biased, but only a little bit biased?</p><h4><strong>Eligibility traces &amp; n-step returns</strong></h4><p>First, let’s take a look at the advantage estimator in an actor-critic algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*jBrDj8oL9XXXjtT0WBN53A.png" /></figure><p>This has much lower variance than the policy gradient but higher bias if the value is wrong and it’s always at least a little bit wrong. We can also take a look at the Monte Carlo advantage estimator that we used in policy gradient algorithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*cspwJe0rqvIYGySCQdQPtg.png" /></figure><p>This has no bias, but it has a much higher variance because of the single sample estimate. So at this point you might wonder, can we get something in between? Could we for example sum over the rewards over the next five time steps instead of infinite time steps and then put the value at the end of that? It turns out that we can and we can use this to get a very nice way to control the bias variance trade-off. There are a couple of factors that make this interesting. First, when you’re using a discount typically your reward will decrease over time because you’re discounting it, so that means that the bias you get from the value function is much less of a problem if you put the value function not at the next time step, but further into the future where the rewards are smaller. On the other hand, the variance that you get from the single sample estimator is also much more of a problem further into the future. In general, we can be way more sure about what will happen tomorrow than about what will happen in ten years. Usually if you have these many possible trajectories emanating from the current state, they’ll branch out a lot more further into the future and they’ll be clustered much closer together in the present, which means that you have much higher variance far in the future and much lower variance closer to the present. That means that if you’re going to use your single sample estimator for a chunk of this trajectory, you’d rather use it close to the present and then cut it off before the variance gets too big and then replace it with your value function, which has much lower variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*qxP4TCtA-vVoUuUTNIC34Q.png" /></figure><p>The value function will then account for all these different possibilities, but potentially with some bias. The way that you can do this is by constructing what’s called an n-step return estimator. In an n-step return estimate you sum up rewards until some timestep n and then you cut it off and replace it with the value function. Here’s the equation for the n-step return estimator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*tANWIcVJiVTg0FrxKP8wUQ.png" /></figure><p>You sum up your rewards, but now you don’t sum them up until infinity, you sum them from t until t + n. You still subtract off your baseline, but then you have that remaining chunk, everything from n + 1 until infinity, and that you replace with your value function. So you evaluate your reward function at state in timestep t + n and you multiply by gamma to the n. This is an n-step return estimator and often times choosing n greater than one works better than n = 1. Generally, the larger n is, the lower the bias and the higher the variance. Very often the sweet spot is not at n = 1, nor at n = infinity and you may want to use an intermediate value. The last trick that I’m going to discuss is a way to actually generalize the n step return estimator and actually construct a hybrid estimator that uses many different n-step returns.</p><h4><strong>Generalized advantage estimation</strong></h4><p>Do we have to choose just one n? Do we have to make this hard slice at a particular point in time? What if we want to actually construct all possible n-step return estimators and average them together? Here is the equation for the n-step return estimator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*2n1aYQKeq67GxHUxTCvTKA.png" /></figure><p>We can construct a kind of fused estimator which we’re going to call GAE for generalized advantage estimation, which consists of a weighted average of all possible n-step return estimators with a weight for different n. The way that you can choose your weight is by utilizing that insight that you’ll have more bias if you use small n, more variance if you use larger n. So you mostly prefer cutting earlier, because then you have less variance, but you want to keep around some of those traces that go further in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*5VkW2TrQXOCBQroMc3x_LA.png" /></figure><p>A pretty decent choice that leads to an especially simple algorithm is to use an exponential falloff. If you use a exponential falloff, at every timestep you have one minus lambda times the value function at that timestep plus lambda of the GAE estimator from there onwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*nVxGoiLGfoSUGHA4nk853w.png" /></figure><p>That gives you this weighted sum of all possible step return estimators, but it turns out that we can collect the terms and get an even simpler form by expressing the GAE estimator this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*pltBo7K5p5R_yt3GbIyWjg.png" /></figure><p>If you just construct a weighted sum of these one step advantage estimators at every time step weighted by gamma times lambda to the t prime minus t, you recover exactly the sum of all possible n-step returns. So this is going to allow you to trade off bias and variance just by choosing this lambda, which acts very similarly to a discount. The larger lambdas look further in the future, whereas the smaller lambdas use value functions closer to the present. This has a very similar effect as a discount. This suggests that even if we didn’t have lambda, the role of gamma would be a kind of bias variance trade-off and that’s in fact the case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*1yEW_npi7egkbk9O0FVHjA.png" /></figure><p>So the discount can also be interpreted itself as a kind of variance reduction, because smaller discounts will result in your Monte Carlo single sample estimator putting lower weight on rewards far in the future, which are exactly the rewards that you’d expect to have high variance</p><h4><strong>Summary</strong></h4><p>We discussed how an actor-critic algorithm consists of several parts: an actor, which is the policy, and a critic, which is the value function. The actor-critic algorithm can be viewed as a version of policy gradient with substantially reduced variance and like the policy gradient and all other RL algorithms it consists of three parts: one component where we generate samples, one component where we estimate our return, which now corresponds to fitting the value function, and one component where we use gradient ascent to update our policy. Just like in policy gradients, policy evaluation refers to the process of fitting the value function and discount factors are something that we can use to make it feasible to do policy evaluation with infinite horizons. This has several different interpretations; you can interpret it as the fear of death, meaning that you would like to receive rewards sooner rather than later before you die, but you can also interpret as a kind of variance reduction trick. We talked about the design of actor-critic algorithms; you could have one network with two heads or two separate networks and you could have batch remote or online actor-critic algorithms. Also, you could use parallelism to get mini batch sizes that are larger than one. We also talked about state dependent baselines and even action dependent control variants as another way to use the critic, while remaining unbiased. We talked about how we can combine these with n-step returns or even the generalized advantage estimator, which averages together many different n-step return estimators.</p><p><em>Feel free to drop me a message or:</em></p><ol><li>Connect and reach me on<strong> </strong><a href="https://www.linkedin.com/in/samuele-bolotta-841b16160/">LinkedIn </a>and <a href="https://twitter.com/SamBolotta">Twitter</a></li><li>Follow me on <a href="https://medium.com/@samuelebolotta">Medium</a></li></ol><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=779f14465b74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2 Deep reinforcement learning: policy gradients]]></title>
            <link>https://samuelebolotta.medium.com/2-deep-reinforcement-learning-policy-gradients-5a416a99700a?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a416a99700a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Sun, 22 May 2022 04:21:31 GMT</pubDate>
            <atom:updated>2022-05-23T05:53:32.477Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second of a series of articles in which I summarize the lectures from CS285 held by Professor Sergey Levine, to whom all credit goes. All images are taken from his lectures. <a href="https://samuelebolotta.medium.com/1-an-introduction-to-deep-reinforcement-learning-c5ab792af013">This article</a> I wrote is an introduction to deep reinforcement learning.</p><p>Policy gradients are in some ways the simplest reinforcement learning algorithm in that they directly attempt to differentiate the reinforcement learning objective and then perform gradient descent on the policy parameters to make the policy better.</p><p>The objective of RL can be written out as an expectation. We would like to take the expected value of the sum of the reward under the trajectory, where the trajectories are distributed according to pθ(τ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*WEf_5Mowq2UShH31rmszHg.png" /></figure><h4>Evaluating the objective</h4><p>Since we assume that we can run our policy in the real world, which amounts to sampling from the initial state distribution and the transition probabilities, we can evaluate the objective approximately by simply making rollouts from our policy. We run it in the real world n times to collect n sampled trajectories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*Gx8tgmcOxNzQT9bT8xjm1Q.png" /><figcaption>t stands for timestep; i stands for sample</figcaption></figure><p>We can get an unbiased estimate for the expected value of the total reward simply by summing up the rewards along each sample trajectory and then averaging the rewards over the sample trajectory</p><h4>Direct policy differentiation</h4><p>Of course, in reality we don’t just want to estimate the objective; we actually want to improve it. To do so, we need to come up with a way to estimate its derivative and crucially the estimate of the derivative itself needs to be feasible without knowing the initial state probability nor the transition probability.</p><p>If I have an expected value, I can expand it as a sum for discrete variables or an integral for continuous variables of the product between the probability and the value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*anm-PTC_1Qhr2wqxNlO8sg.png" /></figure><p>Now we can start working on our derivative. Since the differentiation operator is linear, we can push it inside the integral, so this derivative is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*yko71FO-gfb-IFPW_t-j6A.png" /></figure><p>This doesn’t actually give us a practical way to evaluate the policy gradient, because <strong>∇</strong>θpθ(τ) requires differentiating through the unknown initial state distribution and the unknown transition probabilities. But there’s a very useful identity that will allow us to rewrite this equation in a way that we can evaluate using only samples. The convenient identity is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*RNxuZBk20OJOFJxHpX-qCw.png" /></figure><p>This is because the derivative of the logarithm is equal to dx / x. We’re going to apply this identity in reverse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*VDB1rP5JWqZFY8sAcylObg.png" /></figure><p>You’ll notice that we have an integral overall trajectories of pθ(τ) times some quantity, which means that we can also write it as an expectation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*Vg37s86YFKRKgxXRFr9yDg.png" /></figure><p>But we are not done yet because we still have this <strong>∇</strong>θ log pθ(τ) term. So let’s work on that a little bit. Let’s bring up again our equation for the trajectory distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*ZsNOV22fA_Bz0rz6_4KmhA.png" /></figure><p>pθ(τ) is equal to the product of the probability for the initial state distribution times the sum over the product between the action probabilities and the transition probabilities. If we take the logarithm of both sides, the logarithm of a product is the sum of logarithms, which means that we can write this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*Wu_-fW2r8D7gQczeP1za5A.png" /></figure><p>Now, we’ll substitute this whole thing in for <strong>∇</strong>θpθ(τ) and we’re taking the derivative of this with respect to θ. Now, the derivative with respect to θ of the first and the third terms is zero, because they do not depend on θ. So that means that after the simplification, we’re left with this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*3Jm-3fHzYZUStgJWrQvLfg.png" /></figure><p>Collecting all the terms that remain and expanding out our notation we’re left with this equation for the policy gradient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*fop5rDRb-tt2U73iIi1cFQ.png" /></figure><p>Everything inside the expectation is known because we have access to the policy and we can evaluate the reward. If we want to evaluate the policy gradient, we can simply run our policy, which will generate samples from pθ(τ), sum up their rewards to determine which trajectory is good or bad and then multiply those by the sum of <strong>∇</strong>logpθ. And then once we’ve estimated the gradient in this way , we can improve our policy simply by taking a step of gradient descent, taking the old policy parameters and adding to them the policy gradient multiplied by a learning rate alpha</p><p>This procedure gives us the basic policy gradient algorithm also known as the REINFORCE algorithm, which consists of three steps: sample trajectories according to pθ(a|s) by running the policy in the real world n times, evaluate the policy gradient as for the equation and then take a step of gradient descent.</p><h4>Understanding policy gradients</h4><p>Let’s work a little bit on developing some intuition for what policy gradients are actually doing</p><p>What is <strong>∇</strong>logpθ? Let’s say that our policy for now is just a discrete, a mapping from images to a discrete action space (turn left or turn right). Then logpθ is simply the log probability that this policy assigns to one of those two actions and <strong>∇</strong>logpθ is the derivative of that log probability. A neural network will output those probabilities and you can take the logarithm of that probability. When you do maximum likelihood training supervised learning, you’re typically maximizing log probabilities of observed labels, so it’s instructive perhaps to compare what policy gradients are doing to what maximum likelihood is doing: in maximum likelihood, we would collect some data of humans selecting actions and then we would run supervised learning on that data and that would yield a policy. The maximum likelihood objective is just a maximization of the log probabilities assigned to the observed actions, so the gradient of that is given by the sum over all of your samples and all your time steps of <strong>∇</strong>log<em>π</em>θ(a|s). Of course when we’re doing maximum likelihood, we assume that the actions in our data are good actions. In policy gradient, that is not necessarily true because we generated those actions by running our own previous policy, which might not have been very good. So, the maximum likelihood gradient simply increases the log probabilities of all the actions whereas the policy gradient might increase or decrease them depending on the value of their reward. Intuitively, high reward trajectories get their log probabilities increased, while lower reward trajectories get their log probabilities decreased. So, you can think of it as a kind of weighted version of the gradient for the maximum likelihood objective.</p><p>What if we have continuous actions? In that case, we need to select a representation for the policy that can output distributions over continuous-valued actions. For example we might represent the policy as a multivariate normal distribution or gaussian distribution, where the mean is given by a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*ILGRdFI7FDuxr2ZSXSF2og.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*QdAk2Pk3DyRsturfUnoW0w.png" /></figure><p>If you roll out some trajectories and you compute their rewards and some of them have big positive rewards represented with green checkmarks, while some have big negative rewards represented by the red checkmars, and finally some are kind of neutral, what you’d like to do is you’d like to take the log probabilities along the good trajectories and raise them and take the log probabilities along the bad trajectories and lower them. So, the policy gradient makes the good stuff more likely and makes the bad stuff less likely. In a sense, you can think of the policy gradient as a kind of formalization of trial and error learning</p><h4>What is wrong with the policy gradient?</h4><p>Here is one problem that we could think about: let’s say that the horizontal axis here denotes the trajectory and the vertical axis represents the reward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*m_GZRoZo0V959wDwVdrGhQ.png" /></figure><p>Let’s say that we have three samples and the height of the bars here represents the reward of those samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*7U9n_cuUnaPCHVaZDN52XQ.png" /></figure><p>With these three samples we could now imagine, when we calculate the policy gradient, which way will the blue policy distribution move which way will the trajectory distribution move. We’re going to take each of these three points and we’re going to calculate the logarithm of the policy and multiply it by the value of the reward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*g-3Xc0pwR0hiP3oh9LVxLQ.png" /></figure><p>Now let’s say that the samples on the right are still better than those on the left, but they are all positive. This is how the policy will change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*Cx3uV35tHLAWUARs-NTe3g.png" /></figure><p>You could imagine even more pathological changes to the reward: what if I change the reward so that the two samples on the right actually go all the way to zero? This issue is actually an instance of high variance. Essentially the policy gradient estimator that we’ve described before has very high variance: depending on which samples you end up with randomly, you might end up with very different values of the policy gradient for any finite sample size. As the number of samples goes to infinity the policy gradient estimator will always yield the correct answer, but for finite sample sizes this makes policy gradients very hard to use. In fact, a lot of advances in policy gradient algorithms basically revolve around different ways to reduce their variance.</p><h4><strong>Reducing variance</strong></h4><p>The first trick that we’ll start with is going to exploit a property that is always true in our universe, which is causality. Causality says that the policy at time t + 1 can’t affect the reward at another time step t. This is another way of saying that what you do now is not going to change the reward that you’ve got in the past. Let’s look again at the policy gradient equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*baTpfRO1jqr4rLUcj65FdQ.png" /></figure><p>And let’s rewrite it this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*2Uug1-SIhuYJZvF_4x7QCg.png" /></figure><p>But we can change the summation of rewards, discarding rewards in the past because we know that the current policy cannot affect them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*1XCqeo0JOj0pIsmQildZHA.png" /></figure><p>Having made that change we actually end up with an estimator that has lower variance, the reason being that we’ve removed some of the terms from the sum, which means that the total sum is a smaller number — and expectations of smaller numbers have smaller variances. Now, one aside that I might mention here is that this quantity is sometimes referred to as the reward to go (because it’s the rewards from now until the end of time):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*3iyKIgzxHOw92PywNFd0SA.png" /></figure><p>This quantity actually refers to an estimate of the Q function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*PKtkWFYQbCyEcEofu0ZC4A.png" /></figure><p>A second trick is related to baselines. Let’s think back to this cartoon that we had where we collect some trajectories and we evaluate the rewards and then we try to make the good ones more likely and the bad ones less likely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*9LVukaYSntLC2VA1EmKyQw.png" /></figure><p>Intuitively, policy gradients will do this if the rewards are centered, meaning that the good trajectories have positive rewards and the bad trajectories have negative rewards — but this might not necessarily be true. What if all of your rewards are positive? What we want to do is we want to center our rewards, so the things that are better than average get increased and the things that are worse than average get decreased. For example, maybe we want to subtract a quantity from our reward, which is the average reward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*apR45pTRdHqbKBqsIls36A.png" /></figure><p>This would make policy gradients increase the probability of trajectories that are better than average and decrease the probabilities of trajectories that are worse than average and then this would be true regardless of what the reward function actually is. Interestingly, subtracting a constant b from your rewards in policy gradient will not actually change the gradient in expectation, although it will change its variance — meaning that for any b, doing this trick will keep your gradient estimator unbiased. The average reward turns out to not actually be the best baseline but it’s actually pretty good.</p><h4><strong>Off-policy policy gradients</strong></h4><p>How can we extend policy gradients from the on-policy setting into the off-policy setting? The first part I want to cover is why policy gradients are considered an on-policy algorithm: they require generating new samples each time you modify the policy. The reason this is an issue is that if you look at the form of the policy gradient, it’s an expected value under pθ(τ); the way that we calculate this expectation in policy gradients is by sampling trajectories using the latest policy, but since the derivative evaluated at parameter vector θ requires samples sampled according to θ, we have to throw out our samples each time we change θ, which means the policy gradient is an off-policy algorithm. This is a bit of a problem when we want to do deep reinforcement learning, because neural networks change only a little bit with each gradient step — neural networks are highly non-linear, so we can’t take really huge gradient steps, which means that in practice we usually end up taking a large number of small gradient steps, but each of those small gradient steps requires generating new samples by running your policy in your system. This can make policy gradients very costly when the cost of generating samples is high — either computational cost or practical monetary cost.</p><p>If we do want to use off-policy samplesm we can modify policy gradients using something called importance sampling, which is a general technique for evaluating an expectation under one distribution when you only have samples from a different distribution. What if we don’t have samples from pθ(τ)? What if we instead have samples from some other distribution? This could be a previous policy or even demonstrations from a person. Here’s how we can write out importance sampling in general.</p><p>Let’s say that we’d like to calculate the expected value of some function f(x) under some distribution p(x). We know that the expected value of f(x) is the integral over x of p(x) times f(x). If we have access only to some other distribution q(x), we can multiply the quantity inside the integral by q(x) over q(x). Then, we can rearrange these terms a bit and rewrite everything as an expected value under q(x):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*jblOYG00x3w26iQ9r4qHog.png" /></figure><p>For policy gradients, this is what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*8r5PS1V1f1D-hjdiVSYqYA.png" /></figure><h4><strong>Deriving the policy gradient with importance sampling</strong></h4><p>Let’s say that we have samples from pθ(τ) and we want to estimate the value of some new parameter vector θ prime.</p><p>The objective J of θ prime will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*Li15aNT5mPlCRK7Tmoam_w.png" /></figure><p>In other words, the expected value under pθ(τ) of the importance weight multiplied by the reward. Notice that here the only part of this objective that actually depends on θ prime is the numerator in the importance weight, because now our samples are coming from a distribution from a different policy. That means that when I want to calculate the derivative with respect to θ prime, all I have to worry about is this term in the numerator. So, this is the derivative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*vlrQGEvVrhQChCVAnnjOjw.png" /></figure><p>I have replaced the only term that depents on θ prime with its derivative and then I’m going to substitute my useful identity back in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*EZ_4fLb_RjlHs7ClU0Shag.png" /></figure><p>When you look at this equation, you’ll probably immediately recognize it as exactly the equation that we get if we took the policy gradient and just stuck in an important weight. Interestingly enough, if you estimate this gradient locally (namely, you use this importance sampling derivation to evaluate the gradient at θ = θ prime), the importance weight comes out equal to one and you recover the original policy gradient. But in the off-policy setting, θ prime is not equal to θ and in that case we have to fall back on our importance weights. If we substitute in all three now the terms in this policy gradient, this is how we can rewrite the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*YGcy23LvwET7zs8qQH-rbQ.png" /></figure><p>We just multiply those three terms together. For causality, as we said before, we don’t need to consider the effect of current actions on past rewards, and we can distribute the rewards and the importance weights into the sum over the gradient of the logarithm of the policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*UOJsbDeSMtpwJLqdlGFwcQ.png" /></figure><p>Intuitively, this is the probability that you would have arrived at the state using your new policy (sum of the gradients of the logarithm of the policy times the product of the importance weights in the past) times the sum of the rewards weighted by the importance weights in the future. If we ignore the weights on the rewards (which can be exponentially large), we recover something called a policy iteration algorithm and you can actually prove that a policy iteration algorithm will still improve your policy. It’s no longer the gradient, but it’s it’s a well-defined way to provide guaranteed improvement to your policy. This is not true for the importance weights in the past, which is problematic because they are exponential in T. Let’s say that the importance weights are all less than one: that’s a pretty reasonable assumption because you sampled your actions according to policy θ, so your actions probably have a higher probability under policy θ that under policy θ prime. So, this means that the product of these numbers will go to zero exponentially fast: your variance will go to infinity exponentially fast and policy gradients already have high variance. In order to understand the role that this term plays, we can rewrite our objective a little bit differently and the reason we’re doing all this is because we really just want an excuse to delete that term.</p><p>Here’s our on-policy policy gradient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*GkgdJT6pXyWF3_d1M2gCEA.png" /></figure><p>It’s a sum over all of our samples, a sum over all of our time steps of the gradients of the logarithm of the policy times the reward to go. Now, the way that we sampled actions and states is by rolling out our policy in the environment, but you can equivalently think of it as sampling state-action pairs from the state-action marginal at time step t — because when you sample entire trajectories, the corresponding state and action at every time step look indistinguishable from what you would have gotten if you had sampled from the state-action marginal at that time step. So, you could write a different off-policy policy gradient where instead of importance sampling over entire trajectories, the importance sampling occurs over state action marginals. So now your importance weight is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*DLpI3xENS6rbjRqZj3tYDQ.png" /></figure><p>This is not by itself very useful because actually calculating the probabilities for these marginals is impossible without knowledge of the initial state distribution and the transition probabilities. But writing it out in this way allows us to perform a little trick: using the chain rule we can split up this marginal both in the numerator and the denominator into the product of two terms, a state marginal and an action conditional. And then, we can ignore the state marginal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*165xqOfNJRbM2ctfiN0FjQ.png" /></figure><p>In this case, we get an equation for the importance sampling policy gradient in which the product neglects all of the ratios except at t prime = t. So, if you don’t want your importance weights to be exponential, you could try to ignore the ratio of the state marginal probabilities. You’re still accounting for the ratio of action probabilities, but ignoring the state marginal probabilities. This does not in general give you the correct policy gradient. However, ignoring the state marginal probabilities is reasonable in the sense that it gives you bounded error in the case where θ prime is not too different from θ. This simple insight is actually very important for deriving practical importance sampling policy gradient algorithms that don’t suffer from an exponential increase in their variance.</p><h4><strong>Implementing policy gradients</strong></h4><p>If we want to implement policy gradients naively, we could simply calculate this equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*ZIQz9zWHqbN4si164fVvaw.png" /></figure><p>However, this is very inefficient because neural networks can have a very large number of parameters. In fact, the number of parameters is usually much larger than the number of samples that we’ve produced. Let’s say we have n parameters, where n might be on the order of a million, and we have 100 trajectories, each with 100 time steps. So we have 10.000 total state-action pairs, which means that we’re going to need to calculate 10.000 of these 1 million length vectors. That’s going to be very very expensive in terms of memory storage and also computationally.</p><p>Instead of calculating the derivative of the neural net’s output with respect to its input and then multiplying that by the derivative of the loss, we do the opposite. We first calculate the derivative of the loss and then back propagate through the neural network using the backpropagation algorithm, which is what our automatic differentiation tools will do for us. In order to do that we need to set up a graph such that the derivative of that graph gives us the policy gradient.</p><p>The way that we’re going to figure this out is by starting with the gradients that we already know how to compute, which are maximum likelihood gradients. If we want to compute maximum likelihood gradients, then what we would do is we would implement the maximum likelihood objective using something like a cross-entropy loss and then call dot backward or dot gradients on it, depending on your automatic refreshing package, and obtain your gradients so the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*Gabgf0smb_FMy9--Xa0Cpg.png" /></figure><p>The way that we’re going to implement policy gradients to get our package to calculate them efficiently is by implementing a kind of pseudo loss as a weighted maximum likelihood. We’ll therefore implement the sum of the log probabilities of all of our sampled actions multiplied by the rewards to go. This equation is just a quantity chosen such that its derivatives come out to be the policy gradient. Of course, a critical portion of this is that our automatic differentiation package doesn’t realize that the reward to go is itself affected by our policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*hj0a3tplylFO9hNya3aPNQ.png" /></figure><h4><strong>Policy gradient in practice</strong></h4><ul><li>Remember that the policy gradient has high variance, so even though the implementation looks a lot like supervised learning, it’s going to behave very differently. The high variance of the policy gradient will make some things quite a bit harder: your gradients will be very noisy</li><li>This means that you probably need to use larger batches, probably much larger than what you’re used to for supervised learning — batch sizes in the thousands or tens of thousands are fairly typical</li><li>Tweaking the learning rate is going to be substantially harder. Adaptive step size rules like ADAM can be OK-ish, but just regular SGD with momentum can be extremely hard to use</li><li>In general, just expect to have to do more hyper parameter tuning than you’ve usually had to do for supervised learning</li></ul><h4><strong>Advanced policy gradients</strong></h4><p>The particular issue that I want to discuss is a numerical issue that afflicts policy gradients, particularly in continuous action spaces. To illustrate this issue let me first describe an example problem. Let’s say that you have a one-dimensional state space, so your state is essentially a number line and your goal is to reach the state s = 0 (star in the image below). You also have a one dimensional action space, so let’s say that you’re located at the state with the blue ball in the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*JMliXoXNEGbbBwOfh4vieQ.png" /></figure><p>Your actions can take you left or right; your reward is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*8ihLkU16DtrmOOYbK2KvMA.png" /></figure><p>You get a penalty based on squared distance from s0 and you also get a penalty for taking large actions. Your policy is going to be univariate and normally distributed, with just two parameters, k and a sigma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*2-UK2YD5xnqTc1KOlHXLvg.png" /></figure><p>The policy is a little gaussian centered at your current location and your action is k times your current state. So you’re going to take this kind of noisy walk hopefully towards the goal at s =0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*EvrbvUNm8-rQhdVjhEcHQA.png" /></figure><p>The convenient thing with having a two-dimensional parameter space is that we can actually visualize the entire vector field corresponding to the gradient at all locations in the parameter space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*02PNCb-XO3Z3zXAKiJBU-w.png" /></figure><p>In the above figure, the little blue arrow shows the gradient normalized to the unit length; the horizontal axis is the first parameter k; the vertical axis is the second parameter sigma. The optimal setting for the parameters is k = -1 and sigma = 0, so it’s in the middle at the bottom of this plot. But one of the things you might notice from looking at this plot is that the arrows don’t actually point towards the optimum and the reason for this is that as sigma gets smaller and smaller, the gradient with respect to sigma gets larger and larger. The derivative with respect to k is still there, but the derivative with respect to sigma is comparably much larger, so that when we re-normalize the gradient, the sigma portion completely dominates as sigma gets small. That means that when we follow this gradient it’s going to take us a very very long time to reach the optimal parameter setting, because we’ll spend all of our time just reducing sigma. Those of you that are familiar with numerical methods will probably recognize this as an issue of poor conditioning; the intuition is that this is essentially the same problem as optimizing let’s say a quadratic function, where the eigenvalues of the corresponding matrix have a very large ratio, so if you have a quadratic function with some eigenvalues that are very large and some that are very small, then first order gradient descent methods are really going to struggle.</p><h4><strong>Natural policy gradient</strong></h4><p>When we take a gradient step via policy gradient, choosing the step size for this type of gradient can be very delicate because some parameters affect the policy distribution a lot and some don’t. The derivative with respect to sigma is going to get really really large, whereas the one for k won’t. So, what’s really going on here is that different parameters affect the policy to different degrees; some parameters change the probabilities a lot, others don’t change it very much, but you want all of the parameters to reach their optimal value. Intuitively what you would like to do is to essentially have larger learning rates for those parameters that don’t change the policy very much and smaller learning rates for those that change it a lot.</p><p>What we would like to do is we would like to somehow re-parameterize this process so that our steps are of equal size in policy space rather than parameter space, which will essentially rescale the gradients so the parameters that change the policy a lot get smaller rates, whereas the parameters that change the policy very little get larger rates.</p><p>We can address this problem by using the natural gradient, which simply requires multiplying your gradient by F inverse, where F inverse is an estimate of the Fischer information matrix. You can do this efficiently by using <a href="https://en.wikipedia.org/wiki/Conjugate_gradient_method">conjugate gradient.</a></p><p><em>Feel free to drop me a message or:</em></p><ol><li>Connect and reach me on<strong> </strong><a href="https://www.linkedin.com/in/samuele-bolotta-841b16160/">LinkedIn </a>and <a href="https://twitter.com/SamBolotta">Twitter</a></li><li>Follow me on <a href="https://medium.com/@samuelebolotta">Medium</a></li></ol><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a416a99700a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1 An introduction to deep reinforcement learning]]></title>
            <link>https://samuelebolotta.medium.com/1-an-introduction-to-deep-reinforcement-learning-c5ab792af013?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ab792af013</guid>
            <category><![CDATA[deep-reinforcement]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Sun, 22 May 2022 04:17:44 GMT</pubDate>
            <atom:updated>2022-05-22T20:39:56.067Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first of a series of articles in which I summarize the lectures from <a href="https://www.youtube.com/watch?v=wr00ef_TY6Q&amp;list=PL_iWQOsE6TfXxKgI1GgyV1B_Xa0DxE5eH&amp;index=28">CS285</a> held by Professor Sergey Levine, to whom all credit goes. All images are taken from his lectures.</p><p>On the one hand, reinforcement learning offers a mathematical formalism for the design of algorithms that focus on learning-based decision-making. On the other hand, deep learning offers heavily over-parametrized models that map complex inputs to outputs and allow us to deal handle the unstructured, unpredictable nature of the real world.</p><p>Some reinforcement learning terminology. We can represent a policy as a distribution over actions conditioned on observations; the state satisfies the Markov property, which means that the state at time t + 1 is independent of the state at time t — 1; on the other hand, the observation is some stochastic function of the state which may or may not contain all the information necessary to infer the full state and it does not satisfy the Markov property.</p><p>In reinforcement learning, we define the objective by means of something called a reward function: it is a scalar-valued function of the state and the action, although sometimes it can depend on only the state. Crucially, the objective in reinforcement learning is not just to take actions that have high rewards right now, but rather to take actions that will lead to higher rewards later. Together, the state, the action, the reward and the transition probabilities define what we call a Markov decision process. Let’s build up towards a full formal definition of Markov decision processes</p><ul><li>The Markov chain has a very simple definition: it consists of a set of states s and a transition function t. The state space is simply a set which could be either discrete or continuous. The transition function denotes the probability of the state at time t + 1 conditioned on the state of time t .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*VJf0Xv7i-LWFK3gTrh_3bQ.png" /></figure><ul><li>The markov chain by itself doesn’t allow us to specify a decision making problem, because there’s no notion of actions. So, in order to go towards the notion of actions we need to turn the Markov chain into a Markov decision process, which adds an action space and a reward function. The action space, like the state space, is also a discrete or continuous set. Our transition probabilities are now conditioned on both states and actions, so the transition operator is now a tensor, because it has three dimensions: the next state, the current state and the current action. A partially observed Markov decision process further augments the definition with two additional objects: an observation space o and an emission probability e.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*wp1OOAFThnyGNyI1JFU0Xw.png" /></figure><p>Let’s define an objective for reinforcement learning. We’re going to be learning <strong>π</strong>θ, with <strong>π </strong>corresponding to the policy and θ corresponding to the parameters of the deep neural net that acts as a policy. The state goes into the policy, the action comes out and then the state and action go into the transition probability — basically the physics that govern the world, which produces the next state. In this process, we can write down a probability distribution over trajectories, which are sequences of states and actions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*vCyJUKT0hTI8JmdsGEaY3Q.png" /></figure><p>If we write down the joint distribution of our states and actions, we can factorize it by using the chain rule in terms of probability distributions that we’ve already defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*xMq8eS_-Z9sC8LBIw5heOA.png" /></figure><p>We have an initial state distribution p(s1) and then we have a product over all time steps of the probability of an action given s(t) and the probability of the transition to the next time step s(t+1) given s(t) and a(t). Having defined the trajectory distribution, we can actually define an objective for reinforcement learning and we can define that objective as an expected value under the trajectory distribution. The goal is to find the parameters θ that define our policy so as to maximize the expected value of the sum of rewards over the trajectory; so, we would like a policy that produces trajectories that have the highest possible rewards in expectation and the expectation of course accounts for the stochasticity of the policy, the transition probabilities and the initial state distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*0Dr9x7A6S_8Ibf_OS_lSGQ.png" /></figure><p>One of the things that we might notice about this factorization of the structure distribution is that, although it’s defined in terms of the objects that we had in the Markov decision process, it can also be interpreted as a Markov chain. To do so, we need to define a kind of augmented state space. Our original state space is s, but we also have actions that make this a Markov decision process; we know that the action depends on the state based on the policy, so the policy given the state allows us to get a distribution of our actions conditioned on states. So we can group the state and the action together into a kind of augmented state and now the augmented states actually form a Markov chain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*JUGuLBooyLB6rHJQqD9wTg.png" /></figure><p>So, the transition operator in this augmented Markov chain is simply the product of the transition operator in the Markov decision process and the policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*eqaaJTHnJUMGVhPd-Ky82w.png" /></figure><p>This can allow us to define the objective in a slightly different way that will be convenient to use in some of our later derivations</p><h4>Finite horizon case</h4><p>So so far, I’ve defined the objective as an expected value under the trajectory distribution of the sum of rewards, but remember that our distribution actually follows a Markov chain with this augmented space — and this transition operator is the product of the MDP transitions and the policy. So we could also write the objective by linearity of expectation as the sum over time of the expected values under the state-action marginal in this Markov chain of the reward of that time step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*ZkXWR9J-KF6kprX-eS-hhg.png" /></figure><p>This is just using linearity of expectation to take the sum out of the expectation, so that you have a sum over T of the expectation. Then, since the thing inside the expectation only depends on state and action, we can marginalize all the other variables out. This turns out to be quite useful if we want to extend this to the infinite horizon case.</p><h4>Infinite horizon case</h4><p>What happens if T equals infinity? The first thing that happens is that your objective might become ill-defined. In order to prevent the objective from becoming infinite, there are a few ways. One way is to use the average reward formulation: you take this sum of expected rewards and you divide it by capital T.</p><p>Making the objective finite is pretty easy, but let’s talk about how we can actually define an infinite horizon objective. We have our Markov chain from before and our augmented Markov chain has a transition operator. That means that we can write the vector state(t+1), action(t+1) as some linear operator applied to state and action at timestep t. More generally, we can skip k timesteps ahead and we can say that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*qk1_WwXnjMf1D8VMwhDRBA.png" /></figure><p>One question we could ask is: does the state-action marginal p(s(t), a(t)) converge to a stationary distribution as little k goes to infinity? If this is true, that means that we should be able to write the stationary distribution μ as being equal to t times μ — under a few technical assumptions, namely ergodicity (every state can be reached from every other state with non-zero probability) and the chain being aperiodic, we can actually show the stationary distribution exists.</p><p>“Stationary” means that the distribution is the same before and after the transition; if this holds true, then applying the linear operator enough times will eventually allow you to reach it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*IhI5v8I-XMvlkXSS997ofA.png" /></figure><p>You can solve for the stationary distribution simply by rearranging this equation to see that it is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*OUzavhKmPf32CUejWndxlA.png" /></figure><p>One way you can find μ is by finding the eigenvector with eigenvalue one for the matrix defined by T. So μ is eigenvector of T with eigenvalue one and it always exists under the ergodicity and aperiodicity assumptions. If we know that if we run this Markov chain forward enough times, eventually it’ll settle into μ, that means that as t goes to infinity, this sum over the expectations of the marginals becomes dominated by the stationary distribution terms. So, you have some finite number of terms initially that are not in the stationary distribution, but then you have infinitely many terms that are very very close to the stationary distribution. Which means that once you put in the average reward case and then take the limit as t goes to infinity, the limit is basically going to be the expected value of the reward under the stationary distribution . That allows us to define an objective for reinforcement learning in the infinite horizon case as t goes to infinity.</p><h4>Expectations and stochastic systems</h4><p>Reinforcement learning is really about optimizing expectations, so although we talk about reinforcement learning in terms of choosing actions that lead to high rewards, we’re always really concerned about expected values of rewards. The interesting thing about expected values is that they can be continuous in the parameters of the corresponding distributions, even when the function that we’re taking the expectation of is itself highly discontinuous. This is a really important fact for understanding why reinforcement learning algorithms can use smooth optimization methods like gradient descent to optimize objectives that are seemingly non-differentiable, like binary rewards for winning or losing a game.</p><p>Example: let’s imagine that you’re driving down a mountain road and your reward is +1 if you stay on the road and -1 if you fall off the road. The reward function here appears to be discontinuous and if you try to optimize the reward function with respect to, for example, the position of the car, that optimization problem can’t really be solved with gradient-based methods because the reward is not a continuous or much less a differentiable function of the car’s position. However, if you have a Bernoulli random variable with parameter θ (with probability θ you fall off, with probability 1-θ you don’t), the expected value of the reward with respect to <em>π</em>θ is actually smooth in θ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*qBBdLEr2r2nj47g2o5eZzg.png" /></figure><p>This is this is a very important property that will come up again and again and that really explains why reinforcement algorithms can optimize seemingly non-smooth and even sparse reward functions: expected values of non-smooth and non-differentiable functions under differentiable and smooth probability distributions are themselves smooth and differentiable.</p><h4>Value functions</h4><p>Value functions are a very useful mathematical object both for designing reinforcement learning algorithms and for conceptually thinking about the reinforcement learning objective. As I mentioned earlier, the reinforcement objective can be defined as an expectation of a sum of rewards with respect to the trajectory distribution or equivalently a sum over time of the expected reward for every state-action marginal. One of the things we could do with this expectation is we can actually write it out recursively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvsXLOXcmz2DTWa0CsVkNg.png" /></figure><p>We can apply the chain rule and write out an expected value with respect to that distribution as a series of nested expectations. The outermost expectation here would be over the probability of s1; inside of it, we have an expected value with respect to a1 distributed according to the policy (probability of a1 given s1). Since we have an expectation for both s1 and a1, we can put in the first reward r(s1, a1) and notice that this inner expectation, the one over a1, is conditioned on s1. We add to that all the other rewards, but those require putting in another expectation, over s2, distributed according to p(s2|s1, a1); and inside of that, we have another expectation over a2 distributed according to the policy (probability of a2 given s2). Since we have both s2 and a2, we can put in the reward and proceed with the other expectations.</p><p>One thing that we could think about is: what if we had some some function that told us the stuff that goes inside of the second expectation? Let’s define a symbol for this, let’s say Q(s1, a1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBVTf3o77Fr5ZuZb0Qmmsw.png" /></figure><p>The important point about this definition is that if you knew Q(s1, a1), then optimizing the policy at the first time step would be very easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*Fh4gZtr416uptiNJ6yS9NQ.png" /></figure><p>This basic idea can be extended to a more general concept: the Q function.</p><p>The Q function can be defined at other time steps, not just time step one. And the definition is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*S7xMAXVKfB_e2lpU0HGxTw.png" /></figure><p>A closely related quantity that we can also define is something called the value function, which is defined in much the same way, only it’s conditioned on only a state, rather than a state and an action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*3IxA8_VXmmn7SrmpA5xcgg.png" /></figure><p>The value function can also be written as the expected value over actions of the Q function, because if the Q function tells you the expected total reward if you start at (st, at), then taking the expectation of that with respect to at will give you the expected total reward if you start in st:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*NIOjkZZ7Ihcko5s6OEEpHA.png" /></figure><p>One observation we could make is the expectation of the value function at state s1 is the entirety of the reinforcement learning objective.</p><h4>Using Q-functions and value functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*KdUu-AbqOECXrF4A0tPegA.png" /></figure><p>If we have a policy and we can figure out its full Q-function, then we can improve the policy, for example by picking a new policy that assigns a probability of 1 to a given action if that action is the argmax of the Q function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*_NoDDcNf-R7UsojTnL0qSg.png" /></figure><p>The intuition is that if the Q function is larger than the value function, then the action is better than average. Therefore, you could modify the policy to increase the probability of actions whose value under the Q function is larger than the value at that state.</p><h4>Types of algorithms</h4><p>The RL algorithms we’ll cover will generally be optimizing the RL objective that I defined before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*DrTCpR0QQ5o6bGcam9jg3w.png" /></figure><p>Policy gradient algorithms attempt to directly calculate a derivative of this objective with respect to theta and then perform a gradient descent procedure using that derivative.</p><p>Value-based methods estimate value functions or Q functions for the optimal policy and then use those value functions or Q-functions to improve the policy. Oftentimes pure value-based functions don’t even represent the policy directly, but rather represent it implicitly as something like an argmax ofr a Q- function.</p><p>Actor-critic methods are a kind of hybrid between the two. They learn a Q-function or value function and then use it to improve the policy, typically by using them to calculate a better policy gradient</p><p>Model-based reinforcement learning algorithms will estimate a transition model. They’ll estimate some model of the transition probabilities T and then they will either use the transition model for planning directly without any explicit policy or use the transition model to improve the policy.</p><p>If we consider that each RL algorithm consists of three components, this is how the various algorithms differ in relation to those components:</p><ul><li>Generate samples (run the policy)</li><li>Fit a model / estimate the return. <strong>Model-based algorithms</strong> learn some model for the probability of state (t+1) given state (t) and action (t). <strong>Value function based algorithms</strong> fit some estimate of the value function or of the Q-function. <strong>Policy gradient algorithms</strong> estimate the total reward along each trajectory by adding the rewards that were obtained during the rollout.<strong> Actor critic algorithms</strong> also fit a value function or a Q-function, just like value-based methods.</li><li>Improve the policy. <strong>Model-based algorithms</strong> have different options. One option is just using the learnt model to plan directly; another option is using the learnt model to compute derivatives of the reward function with respect to the policy through backpropagation; another option is using the learnt model to learn a value function and then use that function to improve the policy. <strong>Value function based algorithms </strong>simply choose the policy to be the argmax of the Q-function. <strong>Policy-gradient algorithms</strong> take a gradient ascent step on theta using the gradient of the expected value of the reward. <strong>Value function based algorithms </strong>take a gradient ascent step on the policy, utilizing the value function or the Q-function to obtain a better estimate.</li></ul><h4>Tradeoff between algorithms</h4><p>These algorithms have a number of tradeoffs that will determine which one works best for you in your particular situation.</p><p><em>Tradeoff 1. </em>One important trade-off between different algorithms is sample efficiency, meaning: when you generate samples in the environment, how many samples will you need before you can get a good policy?</p><p><em>Tradeoff 2.</em> Another trade-off is stability and ease of use: reinforcement learning algorithms can be quite complex and require trading off a number of different parameters. How you collect samples, how you explore, how you fit your model, how you fit your value function, how you update your policy. Each of these trade-offs and each of these choices often introduce additional hyper parameters, which can sometimes be difficult to select for your particular problem.</p><p>Different methods will also have different assumptions, for example: do they handle stochastic environments or can they only handle deterministic environments? Do they handle continuous states and actions or can they only handle discrete actions and discrete states? Do they handle episodic problems or do they handle infinite horizon problems where t goes to infinity?</p><p>In some settings it might be easier to represent a policy even if the physics of the environment are very very complex, while in other settings it might be easier to learn a model than it is to learn the policy directly. Each of these trade-offs will involve making some set of design choices. For instance, you might opt for an algorithm that is not very sample efficient for the sake of having something that is easier to use or maybe for the sake of having something that can handle stochastic and partially observed problems. Or you might opt for a very efficient algorithm because your samples are very expensive, but then be willing to accommodate some other limitations like for example only allowing for discrete actions.</p><h4>Sample efficiency</h4><p>Sample efficiency refers to how many samples we need to obtain a good policy, basically how many times do we have to sample from our policy until we can make it perform well. One of the most important questions in determining the sample efficiency of an algorithm is whether the algorithm is what’s called an off policy algorithm or not.</p><p>An off policy algorithm is an algorithm that can improve the policy by using previously collected samples, whereas an onpolicy algorithm has to throw out all of its samples each time the policy changes even a little bit and generate new samples. For this reason, on policy algorithms can be a lot less efficient</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbgzI-L8_hOk3uBXNpCeLw.png" /></figure><p>Why should we even use the algorithms on the right? Because other tradeoffs come in. For example, wall clock time, the amount of computation the algorithm needs, is not the same as sample efficiency. So maybe generating samples for your application is actually very cheap and in that case you probably don’t care nearly as much about sample efficiency — interestingly enough, the wall clock time for these algorithms is often flipped, so if your simulation is very cheap you might actually find the stuff on the right end of the spectrum to be computationally less expensive and the stuff on the left side of the spectrum to be computationally much more expensive.</p><h4>Stability and ease of use</h4><p>When it comes to stability and ease of use, we might ask questions like: does our algorithm converge, meaning if we run it long enough, is it guaranteed to eventually converge to a fixed solution or will it keep oscillating or diverging?I If it does converge, what does it converge to? Does it converge to a local optimum of the RL objective or a local optimum of any other well-defined objective? And does it converge every time?</p><p>In reinforcement learning, convergent algorithms are a rare luxury and many methods that we use in practice are not guaranteed to converge in general. So the reason for this is that reinforcement learning often is not pure gradient descent: many reinforcement algorithms are actually fixed point algorithms that only carry convergence guarantees under very simplified tabular discrete state assumptions which often do not hold in practice. And in theory the convergence of many of the most popular RL algorithms, such as Q-learning algorithms, is actually an open problem</p><p>Value function fitting is a fixed point iteration. At best, it minimizes error fit and minimizes what’s called Bellman error, which is not the same as expected reward. At worst, it doesn’t optimize anything and many popular deep reinforcement learning value fitting algorithms are not guaranteed to converge to anything in the non-linear case (the case where you use neural networks</p><p>In model based RL, the model minimizes the error of fit, which will definitely converge to a good model, but there’s no guarantee that a good model will lead to a better policy.</p><p>Policy gradient is the only one that actually performs gradient ascent on the true objective, but as I said it’s the least efficient of the bunch.</p><h4>Assumptions</h4><p>One common assumption that many RL algorithms will make is full observability, meaning that you have access to states rather than observations. This is generally assumed by most value function fitting methods. It can be mitigated by adding things like recurrence and memory, but in general it can be a challenge.</p><p>Another common assumption is episodic learning: the agent makes a trial, then resets and then makes another trial. So this ability to reset and try again repeatedly is often assumed by pure policy gradient methods and although it’s not technically assumed by most value-based methods, they tend to work best when this assumption is satisfied. It’s also assumed by some model-based RL algorithms.</p><p>Another common assumption is continuity or smoothness. This is assumed by some continuous value function learning methods and it’s often assumed by model based RL methods derived from optimal control, which really require continuity or smoothness to work well.</p><p>Check out the next article, which is about policy gradients!</p><p><em>Feel free to drop me a message or:</em></p><ol><li>Connect and reach me on<strong> </strong><a href="https://www.linkedin.com/in/samuele-bolotta-841b16160/">LinkedIn </a>and <a href="https://twitter.com/SamBolotta">Twitter</a></li><li>Follow me on <a href="https://medium.com/@samuelebolotta">Medium</a></li></ol><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ab792af013" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative modeling]]></title>
            <link>https://samuelebolotta.medium.com/generative-modeling-7a88e847f62e?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a88e847f62e</guid>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[generative-model]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Sun, 02 Jan 2022 16:16:48 GMT</pubDate>
            <atom:updated>2022-06-27T18:35:40.789Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fourth of a series of articles in which I summarize the lectures from CS182 held by Professor Sergey Levine, to whom all credit goes. All images are taken from his lectures. These are <a href="https://medium.com/mlearning-ai/basic-concepts-in-machine-learning-a20de41137cc">the first</a>, <a href="https://medium.com/mlearning-ai/convolutional-networks-recurrent-neural-networks-and-transfomers-ee6a63ddb57f">the second</a> and <a href="https://medium.com/mlearning-ai/detailed-basics-of-deep-learning-part-three-b930c40cf7f8">the third articles.</a></p><p>The central idea of generative modelling stems around training a generative model whose samples x ∼ pθ(x) come from the same distribution as the training data distribution, x ∼ pd(x).</p><p>Consider a medical diagnosis problem in which we have taken an X-ray image of a patient, and we wish to determine whether the patient has cancer or not. Generative modelling first solves the inference problem of determining the class-conditional densities p(x|Ck) for each class Ck individually. Also, it separately infers the prior class probabilities p(Ck). Then, it uses Bayes’ theorem in the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*oZyj46mAFLSfksPzyEIcvw.png" /></figure><p>Equivalently, we can model the joint distribution p(x, Ck) directly and then normalize to obtain the posterior probabilities. Having found the posterior probabilities, we use decision theory to determine class membership for each new input x. Approaches that explicitly or implicitly model the distribution of inputs as well as outputs are known as generative models, because by sampling from them it is possible to generate synthetic data points in the input space.</p><p>While the range of applications to which generative models have been used continue to grow, we can identify three fundamental inference queries for evaluating a generative model:</p><ol><li><em>Density estimation:</em> given a data point x, what is the probability assigned by the model, i.e., pθ(x)?</li><li><em>Sampling:</em> how can we <em>generate</em> novel data from the model distribution, i.e., xnew∼pθ(x)?</li><li><em>Unsupervised representation learning:</em> how can we learn meaningful feature representations for a data point x?</li></ol><p>This is a taxonomy of generative models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4g4DUDQkuZMdlwsFDLrQw.jpeg" /></figure><p>Specifically, we will discuss four generative models:</p><ol><li>Autoregressive Models</li><li>Variational Autoencoders</li><li>Normalizing Flow Models</li><li>Generative Adversarial Networks</li></ol><h4><strong>Autoregressive generative models</strong></h4><p><em>Autoregressive generative models implicitly define a distribution over sequences using the chain rule for conditional probability, whereby in each step the distribution of the next sequence element is predicted given the previous elements</em>. The main principles for training autoregressive generative models are:</p><ol><li>We divide x into its dimensions x1, …, xn</li><li>We discretize each of these dimensions into k values (for example, when we’re generating images, the image pixels are naturally discretized into 256 values because pixels can only take take on 256 different colors)</li><li>We represent the full joint over all the pixels or over all the dimensions of x by the chain rule</li><li>Use your favorite sequence model to actually model this p(x)</li></ol><p>Let’s walk through one popular class of models in this category, that is specific to autoregressive generative modeling of images. This is called “PixelRNN”; the idea is that we’re going to generate the pixels one at a time, left to right, top to bottom in scan-line order. So, the probability of the whole image is given by the product over all the pixels and each pixel depends on its predecessors, which are defined as all preceding scan lines and all preceding pixels to the left of the current pixel in the current scan line.</p><p>Each pixel consists of three color channels, so we also have to generate one color channel at a time — there’s actually a small network for every pixel that generates the red color given all the previous pixels, then the green color given all previous pixels and this pixel’s own red color and then generates the blue color given all previous pixels and this pixel’s red and green color. And then every color channel is a 256-way softmax, so every color channel’s brightness can take on 256 possible values.</p><p>With this model, once you’ve trained it, you can give it for instance the top half of an image and it can complete different random realizations for the bottom half.</p><p>Some practical considerations:</p><ol><li>It is quite slow, because while the basic recipe is the same as a language model, if the image is 32 by 32 pixels, that means that there are about a thousand pixels in that image — so that would be like a sentence of a thousand words. Plus, each pixel itself has three color channels, so that raises it to 3000.</li><li>Generating the image row by row like this might fail to capture some of the spatial context that is present in images, because the pixels that are located right above in the scan line are considered to be far away in the RNN ordering.</li><li>There are many practical improvements and better architectures that are possible to improve PixelRNN (PixelCNN, PixelTransformer, …).</li></ol><p><strong>Conditional autoregressive models</strong></p><p><em>Conditional autoregressive models solve this problem: what if we want to generate something that is conditioned on another piece of information?</em></p><p>For example, we could generate images of specific types of objects or we could have a conditional autoregressive model for imitation learning that generates distributions over actions.</p><p>The recipe is very similar to a conditional language model; you have some something that you’re conditioning on, which we will call “context”. The context is processed using some kind of encoder network, which could be just a feed-forward model, a CNN, or another RNN and that is used to start the first time step of the autoregressive generative model.</p><p>The encoder could be extremely simple, if for example you’re generating images of a class, or it could be very complex, if for example you represent the policy in imitation learning.</p><p>To sum up:</p><ul><li>Autoregressive generative models are basically like language models, but for other types of data — although it’s more accurate to say that language models are just a special type of autoregressive generative model. In other words, the notion of an autoregressive generative model is actually more general than a language model</li><li>You can represent autoregressive models in many different ways (RNNs, LSTMs, PixelCNNs, Transformers, …)</li><li>There are some interesting trade-offs for these models compared to other models we’ll talk about later. <em>One really good thing about these kinds of autoregressive generative models is that they provide full distributions with probabilities, so they will assign a probability to every possible x and those probabilities are easy to get</em>. The downside is that they are slow for large datapoints (like images) and generally limited in image resolution.</li></ul><p>To summarize, some pros of pixelRNNs and pixelCNNs:</p><ul><li>They allow you to explicitly compute likelihood P(X). It’s an explicit density that we can optimize.</li><li>Being able to do this also has another benefit of giving a good evaluation metric. You can measure how good your samples are by this likelihood of the data that you can compute.</li><li>It’s able to produce pretty good samples</li></ul><p>However, this is still an active area of research and the main disadvantage of these methods is that the generation is sequential and so it can be pretty slow.</p><h4><strong>Autoencoders</strong></h4><p>Autoencoders are a very widely used class of models for all sorts of unsupervised learning tasks. Not all autoencoders are generative models; in fact, the autoencoders that we’ll discuss here are difficult to use for generation, but we’ll talk about a special kind of autoencoder called the variational autoencoder that is actually a very good generative model.</p><p>More broadly, <em>an </em><strong><em>autoencoder</em></strong><em> is a type of artificial neural network used to learn efficient codings of unlabeled data (unsupervised learning). The encoding is validated and refined by attempting to regenerate the input from the encoding</em>. The autoencoder learns a representation (encoding) for a set of data, typically for dimensionality reduction, by training the network to ignore insignificant data (“noise”). Variants exist, aiming to force the learned representations to assume useful properties.</p><p>Let’s start with a very very high level view of probabilistic unsupervised learning models, for example things like language models. At a very high level you can think of them as having inputs where the input corresponds to the pixels in the image and the goal is to produce that same image — but in the middle you have some structure that makes this task of reconstructing the image somewhat non-trivial. So, a PixelRNN for instance doesn’t get to look at pixels that it hasn’t generated yet; it has to generate a pixel before it actually sees what that pixel is.</p><p>You can think of this as a general design for generative models: you have some input (which could be an image, a link, a natural language sentence) that goes into a model and that model has a loss, which is to produce the same thing as output. <em>An arbitrary model could just learn the identity function, but some kind of structure is imposed on the model that makes this task of reconstructing the input image not easy and forces the model to learn meaningful representations</em>. Examples of that structure in the middle:</p><ul><li>RNN/LSTM sequence models that have to predict a pixel’s value based only on previous pixels</li><li>PixelCNN models that must predict a pixel’s value based on a masked neighborhood</li><li>Pixel transformer, which makes predictions based on masked self-attention</li></ul><p>All of these models have spatial structure, which has to do with the arrangement of the pixels in the image or the arrangement of the words in the sentence. But can we use more abstract structure once we recognize that all these models basically read in x and then output that same x? More broadly, models that take in some input and then are tasked with producing that same thing as output are called autoencoders and <em>the basic idea behind an autoencoder is to train a network that encodes an image into some hidden state and then decodes that image as accurately as possible from that hidden state.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*vrtaFVjm0lEOasu_QJzO_A.png" /></figure><p>Something about the design of the model or something in the data processing or regularization has to force the autoencoder to learn a structured representation.</p><ul><li><strong>Dimensionality</strong>: make the hidden state smaller (in terms of the number of dimensions) than the input/output, so that the network has to compress it.</li><li><strong>Sparsity</strong>: force the hidden state to be sparse, meaning that most entries in the hidden state are zero, so the network has to compress the input.</li><li><strong>Denoising</strong>: corrupt the input with noise, forcing the autoencoder to learn to distinguish noise from signal</li><li><strong>Probabilistic modelling</strong>: force the hidden state to agree with a prior distribution. This is the approach that we can use to get autoencoders to also be very good generative models.</li></ul><ol><li><strong>A bottleneck autoencoder</strong> relies on the fact that whatever the dimensionality of your input is, you pick the dimensionality of the hidden state to be much smaller. If you have a 100 by 100 pixel image and the hidden state is only 128 dimensions, it can’t possibly learn the identity function, because it can’t store the values of every single pixel in those 128 dimensions. This is very straightforward and it does have some interesting properties. This is a non-linear generalization of principal component analysis, because if both the encoder and the decoder are linear, then training this kind of bottleneck autoencoder with mean squared error for reconstruction exactly recovers principal component analysis — and the dimensionality of the hidden state is the number of principal components that you’re going to get. To sum up, the upside is that it is very simple to implement; the downside is that simply reducing dimensionality often does not provide the structure we want.</li><li><strong>A sparse autoencoder</strong> relies on this basic principle: we can describe the input with a small set of attributes — instead of describing the image of a dog by specifying the color of each pixel, which is not structured and interpretable, you could give a 1 for each property that the dog possesses (ears, wings, wheels, etc.). An interesting property of these kinds of representations is that most attributes will be zero for most images, because there are a huge number of possible objects in the world that do not possess most attributes. That goes hand in hand with the structure; the sparsity principle says that what you want is this kind of attribute dictionary, that is very structured and that tends to be sparse. This is neat, because then the attributes that are present are very specific to that object and they’re very descriptive of it. As an aside, this idea originated in neuroscience, where researchers believe that the brain uses these kinds of sparse representations to represent things in the world (“sparse coding”). Practically speaking, the only thing we really have to do to get a sparse autoencoder is we have to choose a sparsity loss. We’re going to train the sparse autoencoder with backpropagation to minimize some loss function on reconstructing the input, but it will have an additional loss function applied to the hidden state that will encourage that hidden state to be sparse. To sum up, the upside is that it is a principled approach that can provide a disentangled representation; the downside is that it is harder in practice as it requires choosing the regularizer and adjusting hyperparameters.</li><li><strong>A denoising autoencoder</strong> relies on the idea that a good model that has learned meaningful structure should be able to fill in the blanks. If you take an image and you corrupt it in some way and then you ask your model to remove the corruption, then your model will have to learn something about what realistic images look like. To sum up, the upside is that it is very simple to implement; the downside is that it is not clear which layer to choose for the bottleneck and there are many ad-hoc choices to make.</li><li><strong>A variational autoencoder</strong> performs probabilistic modelling: it connects up autoencoders to probabilistic generative models. It also addresses a big problem that other autoencoders have: sampling or generation from them is very hard, which limits their uses. In general, variational autoencoders are meant to compress the input information into a constrained multivariate latent distribution (encoding) to reconstruct it as accurately as possible (decoding).</li></ol><p>Autoregressive models define a tractable density function and based on that we can directly optimize the likelihood of training data. On the other hand, variational autoencoders define an intractable density function with latent z. Our data likelihood p(x) is now an integral over taking the expectation over all possible values of z — however, we cannot optimize this directly.</p><p><strong>Latent variable models</strong></p><p>As an introduction to variational autoencoders, let’s discuss latent variable models first. In statistics, <em>latent variables are variables that are not directly observed but are rather inferred (through a mathematical model) from other variables that are observed (directly measured)</em>. Mathematical models that aim to explain observed variables in terms of latent variables are called latent variable models.</p><p>More in general, let’s say that our distribution p(x) is very complex and we can’t represent it easily. Let’s then introduce another distribution over another variable z; p(z) is just a zero mean unit variance normal distribution. Then, we’ll build our generative model as a probabilistic mapping from z to x. <em>In other words, we are trying to represent p(x) as a composition of two very simple distributions.</em> One of them is p(z), which is just a Gaussian; the other one is p(x|z), which is a simple distribution as well, but its parameters are very complex and deterministic functions of z.</p><p>p(x) is now the integral over p(x|z) p(z) dz. All the complex models we will discuss are based on this principle: you have an easy distribution over a very abstract latent variable z and you have an easy conditional distribution over your complicated variable x, but the mapping from z to x are represented by a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*FByRmQIRq625zJzOwDLaDQ.png" /></figure><p><strong>How do we train latent variable models?</strong></p><p>We’re going to have some model pθ(x) and we have a dataset of x’s. We train with maximum likelihood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*Ha6lvx9YT7OetJOzgQHm_A.png" /></figure><p>Since each of your p(x) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*j1qbM32CNEgo3qSCSKS0lQ.png" /></figure><p>We substitute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*4y5izNN2ik8EcdtiK5iBHQ.png" /></figure><p>But this objective is completely intractable, because you can’t integrate over all possible z’s — this integral does not have a closed form solution. Instead, when we train latent variable models, we need to use something a little more manageable: the expected log likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*yYgMQJxnPjbTrpKDR1APvg.png" /></figure><p>Instead of integrating z, we essentially guess what the z is by estimating p(z|x) for every image and then we maximize the probability of that x with that z. But how do we calculate p(z|x)? This is called probabilistic inference.</p><p><strong>Latent variable models in deep learning</strong></p><p>Some variable z has some prior distribution p(z). This prior distribution is typically set to something very simple, because the meaning of z is not fixed; the meaning of z is entirely determined by your model, so you don’t need to learn or design p(z) and you can choose something simple like a zero mean identity covariance multivariate normal distribution. Then, you have a decoder, which maps vector z to distributions over x: this is a neural network.</p><p>Using the model for generation works like this:</p><ol><li>Sample z from p(z): random number generation.</li><li>Sample z from p(x|z): turn that vector of random numbers into an image</li></ol><p>A latent variable deep generative model is usually just a model that turns random numbers into valid samples.</p><p><strong>How do we represent latent variable models?</strong></p><p>The easy part is representing p(z): generating random Gaussian numbers. Representing pθ(x|z) is a bit more complex.</p><ol><li>Option one is to say that your pixels are continuous values; you would represent them as a multivariate normal distribution with a diagonal covariance, which just amounts to saying that every pixel is going to have a mean and every pixel is going to have a variance. Both the mean and the variance of every pixel could in general be functions of z, so they might be the output of a neural network. Very often, we will simplify this and make sigma be a constant — in which case you just get a mean squared error loss</li><li>Another option is to say that your pixels are discrete valued and in that case pixels all depend on z, but conditioned on z they can be seen as independent. This actually works very well, but it’s a little bit slow.</li><li>There are other choices (discretized logistic, binary cross-entropy, …)</li></ol><p><strong>What architecture should we use for pθ(x|z)?</strong></p><p>An easy choice for tiny images or for non-image data is to just use a big fully connected network. A better choice for more complex data is to (a) run the z vectors through a fully connected layer to turn them into a lower resolution convolutional map (b), use transpose convolutions and unpooling to get the resolution up until it gets to the full resolution that you want for your final image.</p><p><strong>Training latent variable models</strong></p><ol><li>Choice one is to perform inference to figure out p(z|x) for each training image x and then minimize the expected negative log likelihood (this is what variational autoencoders do)</li><li>Another choice is to use an invertible mapping z to x</li><li>Do not bother getting the z’s for each individual x, but try to match the distributions themselves. Basically sample a z at random, sample the x given that z and try to match those samples at the population level to the training data (this is what generative adversarial networks do)</li></ol><p>The way that we’re going to guess the z is by taking an expected value under p(z|xi) for every data point xi in our data set and then we’ll maximize the joint log probability of xi and the z that we guessed. In reality, p(z|xi) is a distribution, meaning that we don’t know exactly which individual z goes with which xi, but we can guess the probability of differences: what we have to do is average over all those possibilities and that’s what an expected value does. The big challenge with this scheme is the way we calculate p(z|xi): we’ve essentially transformed this problem of evaluating an intractable integral into the problem of somehow estimating and then sampling from p(z|xi). This is called probabilistic inference, because we are inferring which z goes with a particular x.</p><p><strong>The variational approximation</strong></p><p>The basic idea behind what we’re going to do is called variational approximation. Instead of actually calculating the real distribution p(z|xi), we’re going to approximate it with some much simpler distribution that’s much easier to deal with. For example, we might just say that p(z|xi) for a particular image xi is some Gaussian qi(z) with some mean and variance — and it’s going to be a different mean and a different variance for every image.</p><p>Of course, the real p(z|xi) is not just a Gaussian, it might be some really complicated thing — so this is an approximation and perhaps a fairly crude one. <em>The remarkable fact is that for any choice of qi(z) we can construct a lower bound on log p(xi), so the quantity that we’ll work out is not equal to log p(xi)but it but it is less than or equal to it</em>. This means that if we’re trying to maximize log p(xi), we can maximize this lower bound quantity instead.</p><p>Here’s how we can do it: let’s start with the expression for log p(xi) that uses that intractable integral from before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*buP6Yj4YEhG-75nkBhWuOg.png" /></figure><p>Then, we multiply by 1 and rewrite the logarithm as an expected value under qi(z):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*QgQeiG2a12EgsqV3Az-tdw.png" /></figure><p>Now we’re going to apply a mathematical identity that is at the core of variational approximation, which is Jensen’s inequality: it allows us to bound any concave function of an expectation below by the expectation of the concave function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*DUX5chPfwWk-WjC7O7K4xQ.png" /></figure><p>In other words, if you have the logarithm of an expected value, that quantity is always greater than or equal to the expected value of the logarithm. If it’s a convex function, then the inequality goes the other way.</p><p>This is what we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*Q7bobGwFmgle3jMB2gW2-g.png" /></figure><p>Now we’ll do a little bit of algebra to turn this last line into something that we can actually optimize with gradient descent. First, we’re going to apply the very useful identity that says that the logarithm of a product is equal to a sum of logarithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*79tF01UOOWmofh5d4ZJV4A.png" /></figure><p>The last term is the negative entropy of qi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*l0N4VuLycGW93PZKuqoTbg.png" /></figure><p>The conclusion of all this discussion is that <em>maximizing this quantity that we have at the end is going to push up on a lower bound to log p(xi), which means it will eventually maximize log p(xi) as well</em>. A brief parenthesis about entropy:</p><p><strong>Entropy allows us to ask:</strong></p><ol><li>How random is the random variable? Entropy represents how random a distribution is; if all outcomes are equally likely, then you have the highest entropy, whereas if one outcome is guaranteed, then you have the lowest entropy.</li><li>How large is the log probability in expectation under itself? For example, if you have two distributions like these:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*kKHkH3uETKqIUcfIZmIMaA.png" /></figure><p>These are continuous-valued distributions. We could ask: which one has the higher entropy? Since entropy quantifies how random a random variable is, the top one has higher entropy because there are more values that are possible, which means the probability of each of those values must be lower (because distributions always integrate to one).</p><p>Then, what do we expect from this expression?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*l0N4VuLycGW93PZKuqoTbg.png" /></figure><p>We’re maximizing entropy over qi and we’re also maximizing the expected value of those log probabilities.</p><ul><li>The first term is going to encourage putting a lot of probability mass on a value of z for which log p(xi|z) +log p(z) is large</li><li>The second term is going to encourage broadening this probability mass</li></ul><p><em>What that means is that we’ll capture the point with the largest probability under p, but we’ll also make the resulting distribution q as broad as we can, so that it covers as much probability mass as possible and has the highest entropy.</em></p><p><strong>KL-Divergence</strong></p><p>Another concept in information theory that we should discuss is KL-Divergence. It can be thought of as:</p><p>1 A measure of how different two distributions are, because if q and p are exactly the same, then the divergence is zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*xOBBAgwrtwgn9t9K-vUSlQ.png" /></figure><p>2 A measure of how small the expected log probability of one distribution under another is, minus entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*XGslWU_GpMCl4H3RsBFiWg.png" /></figure><p><strong>The variational approximation</strong></p><p>The expression that we derived before by using Jensen’s inequality is actually a KL-Divergence. We call this the evidence lower bound and it’s a function of two distributions: p, which is the distribution we’re learning, and qi, which is our approximation to the posterior. So what makes qi(z) good? Being able to accurately approximate p(z|xi) with a low KL-Divergence between them.</p><p>One can prove that the log p(xi) is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*mwuo2JzAtOax-ul19TaP5A.png" /></figure><p>Where the second term is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*qmQLQ0GkgrgcDiE8-TLH_w.png" /></figure><p>Therefore, if we want qi(z) to approximate p(z|xi) well, the KL-Divergence has to be low.</p><p>If we want to know how to train our model, we can train our model by maximizing the evidence lower bound with respect to the model p and, if we want to get the best qi, we also maximize the same evidence lower bound with respect to qi. This is telling us that if we just maximize the lower evidence bound, we are in fact minimizing the KL-Divergence.</p><p>The goal is then to maximize the evidence lower bound: for every xi in our dataset, we’re going to calculate the gradient of the evidence lower bound with respect to the parameters of our model. The way we do that is we first sample a z from qi(z); then, we approximate our gradient as the gradient for our model for that one sample; then, we take one gradient descent step and we update our qi to also maximize the lower expected bound (there are different ways of doing so).</p><p>Let’s start with something simple: let’s just say that qi is a Gaussian distribution over z, with a mean and a variance. For every image in our dataset, we have a different mean and a different variance that we’ll keep track of.</p><ol><li><strong>Regular variational inference<br></strong>One way that we could update mean and variance is we could compute the gradient of the evidence lower bound with respect to those quantities and then just do gradient descent on those. But there are two problems with this approach. The first is the number of parameters we need to optimize grows (at least) linearly with the number of observations. Not ideal for massive data-sets. The second is that if we get new observations, or have test observations we would like to perform inference for, it is not clear how this fits in to our framework. In general, for new observations we would need to re-run the optimization procedure.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*vHOu81k1oJ2hTDgShUuCdA.png" /></figure><p><strong>2. Amortized variational inference<br></strong>Amortized VI is the idea that instead of optimizing a set of free parameters, we can introduce a parameterized function that maps from observation space to the parameters of the approximate posterior distribution. In practice, we might (for example) introduce a neural network that accepts an observation as input, and outputs the mean and variance parameter for the latent variable associated with that observation. We can then optimize the parameters of this neural network instead of the individual parameters of each observation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*M-XdCn0Qfo32jxJ5yS906A.jpeg" /></figure><p>Notice that this directly addresses the issues mentioned earlier. First, the number of variational parameters is now constant w.r.t. to the data size! In our example, we only need to specify the parameters of the neural network, and that is not dependent in any way on the number of observations we have. Second, for a new observation, all we need to do is pass it through the network, and we have an approximate posterior distribution over its associated latent variables. At the constant cost of a forward pass through a network! These gains are the source of the term amortized.</p><p>Taking a gradient ascent step on φ: by computing the gradient with respect to φ of L. φ appears in two places in the evidence lower bound: (1) it appears as the parameters of the distribution under which we compute the expectation (2) it appears inside the second entropy term</p><p>This is our evidence lower bound:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*urKt7yd_TKlnVXWWgewB9Q.png" /></figure><p>The gradient of the entropy term is easy to handle, but the first part is a little more complex. One way that we can think about calculating the gradient of the first part is to note that all the stuff inside the expectation does not depend on φ, so we can collect those terms into a single expression I’m going to call r(xi,z):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*MKBgUjwFBoInKvfiX6wssQ.png" /></figure><p>This is similar to the objective in reinforcement learning, which is to maximize the expected value of the reward where the expectations are taken with respect to a distribution determined by the policy. Here, we have the expected value of some function r, where the distribution is determined by qφ: we could just use policy gradient.</p><p>The simple version would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*SzWwxEUXYMhePQTKIy1utg.png" /></figure><p>The shortcoming of this expression is the same as the shortcoming of policy gradient in general: the variance is large, which means that we might in practice have to generate quite a few samples zj to get an accurate gradient estimate.</p><p>There is a much better way that we can train these models that’ll be much faster and more effective in practice; it’s going to leverage the fact that unlike in the case of reinforcement learning, in the case of latent variable models we can actually calculate the derivative of r. This is called the reparameterization trick.</p><p>Here’s the idea. We have our expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*2wws0luKBJEaFN-ykXI3dw.png" /></figure><p>For which we want to calculate the derivative with respect to φ, but φ is not just any distribution: it’s a normal distribution. This means that we could also write z as a deterministic function of the mean and variance and epsilon, which is a standard Gaussian sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*kimDk3hs1aYoT9RIbmUJkA.png" /></figure><p>This is because a Gaussian with a non-zero mean and a variance that is not one can just be expressed as a affine transformation of a zero-one Gaussian. Now everything here is deterministic except for epsilon, but epsilon does not depend on φ. It doesn’t depend on the neural network, so we can equivalently write our objective as the expected value with respect to epsilon, where we substitute this equation for z:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*JYPdQa1oq5gfOBThd0WTyQ.png" /></figure><p>φ only appears inside the expectation: the distribution with respect to which we’re taking the expectation is not dependent on φ anymore. We’ve re-parameterized the distribution and that’s why it’s called the reparameterization trick. So now we can estimate the gradient with respect to φ as follows: we can sample a bunch of epsilons from a zero mean unit variance Gaussian and then the derivative with respect to φ is just applied by using the chain rule of differentiation. The reason that we cannot do this in reinforcement learning is that the derivatives of the rewards are not known to us.</p><p>Another way that we can look at our evidence lower bound objective works this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*MkQsNlSc8raXPLsVOLb3zg.png" /></figure><p>Theta only enters into the first term; the second and third terms are independent of theta and if we group them together we’ll notice that it’s just the negative KL-Divergence. It’s very convenient to express the evidence lower bound like this because all the hard stuff is basically in the first term</p><p>If we apply the reparameterization trick, then both theta and phi now appear inside the expectation and the distribution under which we’re taking the expectation does not depend on either of the parameters. We can estimate this using just a single sample of epsilon by just plugging in that epsilon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*MYPXNMBthLFVd6Ul3uzrKQ.png" /></figure><p>It might be instructive at this point to draw the resulting neural networks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*PbIm0Lz7tkacHk5PO7FopA.png" /></figure><p>This is how you implement a variational autoencoder. The reason this is called a variational autoencoder is because if you look at the structure of this neural network, it looks like an autoencoder. It has an encoder with parameters φ, which has this unusual noise, mean and variance thing at the end; then, it has a decoder with parameters θ. So, it’s just an autoencoder where, unlike for the denoising autoencoder, the noise is put into the hidden state z instead of being put in in the beginning. But the variational autoencoder has this very appealing interpretation as a latent variable model.</p><p><strong>Reparametrization trick vs policy gradient: </strong>what are the tradeoffs?</p><p>The policy gradient:</p><ul><li>Can handle both discrete and continuous latent variables</li><li>It has high variance and requires multiple samples and small learning rules</li></ul><p>The reparameterization trick:</p><ul><li>It only handles continuous latent variables</li><li>It’s very simple to implement and does work quite a bit better if you can use it</li></ul><p>Now, let’s put things together and go through the full variational autoencoder.</p><p>The variational autoencoder is a latent variable model that has latent variable z and it has observed variables x</p><ul><li>It has an encoder, which performs inference:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*ZKhgM7Yxlbe7OpmdUhB_4g.png" /></figure><p>This is a neural network that takes in x and it produces a mean and a variance over z.</p><ul><li>It has a decoder:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*vDMcff7X3mwUC84NdxVhXA.png" /></figure><p>This is a neural network that takes in z and it produces a mean and a variance over x.</p><p>This is the objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*unuTafDGwuBBF8ahuac3Lg.png" /></figure><p>The first part of the objective looks like an autoencoder objective: you encode xi into mean and variance, get z and then you decode to get the resulting distribution over x and you try to maximize the probability of the real image.</p><p>The second part can be thought of as a kind of penalty that penalizes how much qφ(z|xi) deviates from the prior p(z). From this, we can derive a little bit of intuition as to why the variational autocoder works: because that second KL-Divergence term encourages the encoded z’s to look similar to samples from p(z), at test time the decoder will know what to do with those z’s.</p><p>We can also train conditional models of variational autoencoders; if you have a conditional model, then you are mapping x to some output variable y and you would like p(y|x) to be some fairly complex distribution. We’ll use the same intuition as before: p(y|x) might be complex, but p(y|x, z) will be simple. Everything is just like before, only now we’re generating y and everything is conditioned on x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*fBELK8ha2OmlO1bu6M5lIg.png" /></figure><p><strong>VAEs with convolutions</strong></p><p>Let me walk you through a potential architecture we might use for a VAE with convolutions. You have your image and first it has to go into the encoder. This is the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1VyBxMmq5Y-b5MgMzfaWUw.png" /></figure><p>So far, everything is the same as any other convolutional autoencoder, but now we’re going to have one fully connected layer that outputs a mean and another fully connected layer that outputs a variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*uktTkuX4Y6qBE9xzWe2Gpw.png" /></figure><p>Then we’re going to sample our normally distributed epsilons, multiply one of them by sigma and this gives us z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*hBzJXqXlfirjVOGF7cJ2cw.png" /></figure><p>This is our bottleneck representation: if we want to use a variational autocoder for representation learning, for example for a downstream classification task, this is the vector that we would use as our compressed representation of the image.</p><p>But to train the VAE we also need a decoder. For that, we’re going to use transpose convolutions that up sample the vector all the way back up to a 64 by 64 image. Then, we train this whole thing end to end with backpropagation by using two loss terms:</p><ul><li>Negative log probability of the image</li><li>KL-Divergence between the distribution determined by μz and σz and our prior p(z), which is typically a zero mean unit variance Gaussian.</li></ul><p>Our decoder outputs two numbers for each pixel: a mean and a variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*AiChrxOkOOxe4_x8Ybdnyg.png" /></figure><p><strong>VAEs in practice</strong></p><ul><li>One common issue is that it is very tempting for VAEs to ignore the latent codes or generate poor samples. The reason is that if you can approximate your x with just a regular Gaussian distribution, it’s much easier especially for conditional VAEs to do this, because initially the z just looks like noise and figuring out how to use it can be pretty hard. You can tell that this is happening when you get back a blurry “average” image that does not look like the input.</li><li>A second problem you might get is that the latent code is not compressed. You can tell this is happening when your reconstructions are great, but when you sample a z from p(z) and then decode, you’ll get an unrealistic image.</li></ul><p>For problem 1, the KL-Divergence is too low: typically, qφ(z|x) ignores x and just outputs a zero mean a unit variance. This means the z’s carry no information about x, which means your decoder pθ doesn’t use the z’s. That is why it produces those blurry average images: there’s no information in z that would be useful for actually reconstructing x.</p><p>Problem 2 is characterized by the opposite, the KL-Divergence being too high: there is too much information being packed into z, which means that you can reconstruct x perfectly but because it’s so far from the prior when you sample z from it, your decoder doesn’t know what to do with it.</p><p>To control the KL-Divergence, a very common trick is to put a multiplier in front of that KL-Divergence. You adjust this hyperparameter depending on which problem you’re seeing: if you have problem one, then you need to decrease beta, whereas if you’re seeing problem two, then you need to increase beta.</p><p>Sometimes it is difficult to find the beta that both produces good samples and good reconstructions early on in training. Intuitively, early on in training the VAE needs to learn to pay attention to z and later on in training it needs to do a better job of compression. It can then be very useful to actually schedule beta to alter beta. For example, you could begin with very low values of beta, so that the VAE learns to use z and then later on raise beta to get the samples to be good. In other words, once your reconstructions look good you can increase beta and then your samples will become better too</p><p><strong>Invertible models and normalizing flows</strong></p><p>We’re going to talk about a different kind of model that is structurally a little bit similar to a variational autoencoder, but can be a lot simpler to train. Here’s the idea: instead of having the decoder represent a distribution over x given z, we’ll have a deterministic decoder that directly turns z into x.</p><p>Now if we want to compute p(x) for training, we can use the change of variables formula, which says that if x is a deterministic function of z, then p(x) is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*bI3BddNLK1fL81yo6YYbNA.png" /></figure><p>What it means is that if you have some distribution over z and z is transformed in a deterministic way to get x, then to get a density over x all you have to do is modify the density over z by how much of the volume changes according to f.</p><p>If we can calculate the determinant of the jacobian df/dz and we can calculate the inverse, then we can implement a model of this sort with a deterministic function that maps these stacks. So that determinant is just a correction for the change in local density due to f. The basic idea is therefore that if we can learn invertible mappings from z to x, that can make this determinant easy to compute and we can build these kinds of models without having to worry about all that variational inference stuff. We also don’t need lower bounds and can get exact probabilities.</p><p>This class of models is sometimes referred to as normalizing flow models. Our training objective is just maximum likelihood: maximize the log probability of all the xi’s in your dataset. We use the expression from the change of variables formula on the previous slide to write p(x) in terms of p(z); p(z) is still some very simple distribution. If we substitute this formula into the training objective, our objective is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*aOkxQsWku31ZTz7YqGE1cw.png" /></figure><p>We are going to choose a special structure that makes this easy to calculate. A normalizing flow model consists of multiple layers of invertible transformations, so all we need to do in order to implement these types of models is figure out how to make an invertible layer and then compose many of these invertible layers to make a deep network.</p><p>A few observations:</p><ul><li>If each layer is invertible, the whole thing is invertible</li><li>Oftentimes, invertible layers also have very convenient determinants</li><li>Log-determinant of whole model is just the sum of log-determinants of the layers</li><li>Our goal is to design an invertible layer and then compose many of them to create a fully invertible neural net</li></ul><p>There are many different ways to design invertible layers; I’ll start with one of the simplest types, called non-linear independent components estimation (NICE).</p><p>Ordinarily, a layer in neural net would be some mapping from z to x. For example, x is given by a ReLU applied to (Wz+b). But we can’t use this because this is non-invertible. Here’s an idea: what if we force part of the layer to keep all the information so that we can then recover anything that was changed by the non-linear part?</p><p>We can take our z and split it into two parts. The first part goes from number 1 to d, the second part goes from number d+1 to n. X will also have two parts: the first part is copied entirely to the first part of z, but it is also passed through some neural net and it is added to the second part of z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*sk_9wDXZ0fJJ2_qJkKe-Wg.png" /></figure><p>The question becomes: if we have x, can we recover z? If so, then this layer is invertible. We can then compose an entire net of such invertible layers.</p><ol><li>Recover z(1:d) = x(1:d)</li><li>Recover gθ(z(1:d))</li><li>Recover z(d+1:n) = x(d+1:n) — gθ(z(1:d))</li></ol><p>The trick that we needed to make this work is that the first part is preserved losslessly and the non-linear component depends only on that first part. This means that you can recover the nonlinear components and subtract them off.</p><p><strong>What about the Jacobian?</strong></p><p>We need the determinant to compute our normalizing flow objective; both x and z have these two parts, so this would be df/dz as a matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*oANB_7dJ2jOum89q8aCd5g.png" /></figure><p>The derivatives of this matrix are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*-9bzcLoss7jhfuAsX1vk-A.png" /></figure><p>However, you might know that the determinant is not affected by the lower left block, because the upper right block is zero. So the determinant for a matrix like this is a lower triangular matrix; it is just determined by the diagonal entries and the diagonal entries are all one, therefore the determinant is 1.</p><p>That’s very convenient: because of this particular form, for these invertible layers the determinants are always one, which means that that term in the objective has no effect on training the model whatsoever. Unfortunately, it’s representationally a bit limiting, because the determinant is always one and thus we can’t change the scale the determinants always. This kind of network only transforms z’s into x’s, but it never rescales them, so it can be very difficult to train very complex distributions in this way.</p><p>So in practice what we see is if we take this kind of invertible layer and we stack a few of these layers and use them to train a generative model, we can do a pretty good job of modeling simple datasets (MNIST), but when we start looking at more complex images, it tends to break down (CIFAR10).</p><p>There’s a small change we can make to this model that makes it substantially more expressive and this is something called Real-NVP: Non-Volume Preserving Transformation. We are going to split z and x into two parts like before, but now we’ll have two neural nets: a scaling network and a biasing network. We’ll take the second half and we’ll multiply it by the first neural net and then we’ll add the term from the second neural net, so that the second half of x is given by the second half of z times the exponential of the output of the first neural net plus the second neural net:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*zbpBGEFMS30cYJxOz8x3nw.png" /></figure><p>This is also an invertible operation and the way you derive the inverse is very similar to before. You recover the first half of z by just using the fact that it’s equal to the first half of x; once you’ve recovered that you can recover gθ and hθ and then you can solve for the second half of z by just taking the second half of x, subtracting g and then dividing by the exponential h.</p><p>Now the jacobian has a much more interesting form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*DJ0hYHD1iwXpFa45cu1wzg.png" /></figure><p>The bottom right block now is the diagonal of these exponential values, which means the determinant is not one anymore. It is significantly more expressive at the cost of adding a second non-linear component and this can generate much higher-quality images</p><p>Some concluding remarks about normalizing flows</p><ul><li>One big advantage of normalizing flows is you can get exact probabilities or likelihoods from them; you can actually evaluate p(x), whereas a variational autoencoder only gives you a bound on p(x)</li><li>You don’t need any lower bounds</li><li>It’s conceptually somewhat simpler</li></ul><p>It also has a few major disadvantages:</p><ul><li>It requires a special architecture, so you can’t just use regular layers</li><li>Since each layer is invertible, the dimensionality at every layer has to stay the same and this can be a really big deal with high resolution images. If you have a million pixels in your image, then you need a million dimensions in z, whereas a variational auto encoder can have a latent code that is much lower dimensional than the image and this can be a major limitation</li></ul><h4><a href="https://www.youtube.com/watch?v=39CmbTX1S8M&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=58">Generative adversarial networks</a></h4><p>The idea that we’re going to explore in today’s lecture is whether instead of training an encoder, like we did with VAEs, we could just train the whole model to generate images that look similar to real images at the population level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*dguM5wm3SDb2YTby9OzKow.png" /></figure><p>In other words, instead of trying to guess for every real image what its corresponding z is and then using that to supervise our network, what if we just generate a bunch of random images and then try to alter our network so that those random images at the population level resemble the population of realistic images given to us in our training set? <em>This means that we want to sample from complex, high-dimensional training distribution and there is no direct way to do this; the solution, therefore, is to sample from a simple distribution (like random noise) and then learn a transformation to the training distribution (using a neural net).</em></p><p>An example: let’s say that I have two sets of faces. No two faces are the same, but they look kind of similar at the population level, so if I were to take five samples from one distribution and five samples from the other distribution, probably you would not be able to tell which distribution those came from. In that case, we would say that these two distributions are similar at the population level. This is how we can basically try to match distributions without having to figure out what the latent variables for any particular image actually are. I might also ask you whether you can guess which set of faces is actually real: if I tell you that some of these faces were in fact generated by a latent variable model, would you be able to guess which set it is? These kinds of models that match distributions at the population level can get extremely good and much better than this.</p><p>Here’s how we’re going to set this up: we’re going to set up a game where the only winning move is to generate realistic images. In other words, <em>the idea is to train a network that is going to guess which images are real and which are fake; this classifier is going to output a probability that this image is a real image</em>. In order to train a network like this, all you need is a labeled training set; the fake images can come from our generative model, whereas the true images can come from our training set.</p><p>This model can then serve as a loss function for our generator: in other words, the loss function of our generator that turns z’s into x’s could be the realism score of the resulting image as produced by this classifier. The basic intuition behind this approach is that we’re going to learn a loss function by training a classifier to classify between fake images and real images and then we’re going to use this as a negative loss for our generator to get the images that it generates to be more real according to this classifier.</p><ul><li><strong>Generator network</strong>: try to fool the discriminator by generating real-looking images</li><li><strong>Discriminator network</strong>: try to distinguish between real and fake images</li></ul><p>The core idea of a GAN is based on the “indirect” training through a discriminator, which itself is also being updated dynamically. This basically means that the generator is not trained to minimize the distance to a specific image, but rather to fool the discriminator. This enables the model to learn in an unsupervised manner.</p><p>Here is a potential algorithm:</p><ol><li>Get a true dataset of real images</li><li>Get a generator Gθ(z), which can even be initialized randomly</li><li>Generate a dataset of false images</li><li>Train your discriminator, which is just a classifier that tries to predict whether the image came from the true dataset or the false one</li><li>Use this discriminator to construct some kind of loss function for training G(z)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*mFE0fhmQrwWyAkc0X7rdbg.png" /></figure><p>This recipe almost works, but it has a few major problems that we need to address before we can construct a viable method.</p><p>If we do step five only once, the big problem is that in step five it’s very easy for G(z) to fool D(x). If D(x) was trained for fake images coming from a really bad generator, then the new generator against step five just needs to be better than the old one, but it might still not be very realistic. In order to make it work, we choose an iterative approach. After getting a generator, we’re going to sample our false images and then update our discriminator with only one gradient step: we won’t actually train the discriminator convergence, we’ll just take one gradient step. That will give us a slightly better discriminator, then we will update our generator also for only one gradient step and then we’ll generate new false images; so instead of just generating all the false images up front and training your discriminator convergence, you’ll actually alternate between updating the discriminator to get better at classifying real from fake and then updating the generator to generate more realistic images. <em>It’s going to be a kind of game where the discriminator will keep trying to keep up with the generator and the generator will keep trying to fool it.</em> Because they have this kind of competitive process, the only way for the generator to win the game is to produce images that are truly indistinguishable from real images</p><p><strong>Summary</strong></p><p>A known dataset serves as the initial training data for the discriminator. Training it involves presenting it with samples from the training dataset, until it achieves acceptable accuracy. The generator trains based on whether it succeeds in fooling the discriminator. Typically the generator is seeded with randomized input that is sampled from a predefined latent space. Thereafter, candidates synthesized by the generator are evaluated by the discriminator. Independent backpropagation procedures are applied to both networks so that the generator produces better samples, while the discriminator becomes more skilled at flagging synthetic samples.</p><p><strong>A little bit more intuition for why this basic idea actually works</strong></p><p>What does G(z) want to do? Ideally, its goal is to somehow persuade the discriminator to output 0.5 for all generated images. In order to do this, it has to generate images that look realistic; but the the somewhat more subtle point is that in order to really get 0.5 on all of your generated images, you don’t just need to generate images that look realistic, <em>you actually need to generate all possible realistic images and this is why GANs match distributions.</em></p><p>Let’s say that we have a dataset that has photographs of cats and dogs; half the pictures are cats and half of them are dogs. Our generator has gotten really good at generating very realistic images, but it only generates dogs, so it has not covered the whole distribution. Imagine what the discriminator is going to do in this case:</p><ul><li>If we take a picture of a cat and we pass it to the discriminator, the discriminator will say that the probability that it is a true image is 1. This is because the training set has about half the true images containing cats, but none of the false images contain cats.</li><li>If we take the picture of a dog and we pass it to the discriminator, the discriminator will say that the probability that it is a true image is 0.25. This is because the training set has about half the true images containing dogs, but all the false images were dogs.</li></ul><p><em>This is why in order for the generator to win this game against the discriminator, it really has to not only generate realistic images, but all of the realistic images.</em> For full disclosure, a particular issue with GANs that I will not talk about too much in this lecture is that in reality in practical instantiations these models do often suffer from something called the mode collapse problem. The mode collapse problem is a type of overfitting and when that happens GANs do in fact fail to capture the entire distribution.</p><p><strong>Technical details of actually setting up GANs</strong></p><p>The classic GAN described by the previous procedure can also be expressed as a two-player game — a min-max problem where you have two players that are respectively trying to minimize (the generator) or maximize (the discriminator) the same objective. This expression is basically just cross-entropy loss: it takes the positive labeled images and maximizes the log probability of those; then, it takes the negative labeled images and maximizes the log probability of those.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*bhleogvBKRDbuZThiOIATA.png" /></figure><p>In a binary classification problem, the probability of a negative label is just 1 minus a positive label, so that’s why you see “1 — D”. Both these are expected values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*8GUNZA8KSmjVnhEMXpMsvg.png" /></figure><p>D is trying to maximize the log likelihood, such that D(x) is close to 1 (real) and D(G(z)) is close to 0 (fake); G is trying to do the opposite. It is no longer a conventional gradient descent optimization, it is in fact the problem of finding the Nash equilibrium in a two-player game. Here is the GAN game, rewritten in terms of θ (parameters of G) and φ (parameters of D):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Ur_nKLekqg9addRB4vqstA.png" /></figure><p>The algorithm is basically the same as alterning between a gradient ascent step on φ, because φ is maximizing, and a gradient descent step on θ, because θ is minimizing. These two steps just alternate.</p><p>There are two important details that we have to get right in order for this to work:</p><ol><li><strong>How to make this work with stochastic gradient descent or ascent, because we want to use a mini-batch</strong></li></ol><p>For using stochastic gradient ascent or descent, we approximate the gradient by using a mini batch of training points for the first expectation and then for the second expectation we sample the same number of z’s and run them through the generator. That basically gives us a mini batch gradient ascent or mini batch gradient descent version of this. The loss is cross-entropy loss. The generator loss is just estimated with the same mini batch of z’s; you just run them through the generator, ask the discriminator what probability lends to them and then use that as the loss for your generator.</p><p><strong>2. How to compute gradients</strong></p><p>Computing these gradients is pretty straightforward; the gradient for the discriminator is just cross-entropy loss; the gradient for the generator may be a little bit more elaborate, because computing the loss function for the generator requires generating images and then passing them into the discriminator. The way that we calculate gradients for the generator is we backpropagate through the discriminator into the generator</p><p><strong>What particular objective does the GAN actually optimize?</strong></p><p>Can we somehow take this two-player game, analyze it and be able to state formally that at convergence this should minimize some measure of discrepancy between the data distribution and the distribution of images produced by our GAN?</p><p>For the purpose of theoretical analysis, we express the optimal D(x) in closed form as a function of G(z); we have an outer minimization and inner maximization, so maybe the solution of that inner maximization can be expressed in closed form as a function of G. We obviously can’t implement that in code, we need to actually train a neural net to do that, but maybe at least theoretically we can characterize the solution for D as a function of G</p><p>A very useful property for this is an identity that can be used to describe the Bayes’ optimal classifier. Let’s say that we have a set of positively labeled images (coming from p(x)) and a set of negatively labeled images (coming from q(x)). P(x) is p(data) and q(x) is the distribution of our images obtained by sampling z from p(z) and then running that through G. The optimal discriminator which I’m going to call D* is just the arg max of the log likelihood, which we can write as the expectation under p of log(D) plus an expectation under q of log(1-D).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*hjCzemPD4YVJXr-btObc7g.png" /></figure><p>Now we’re going to take the derivative of this with respect to D; we’re not taking the derivatives of any parameters, we’re just taking the derivative with respect to the function D and we’re going to set that derivative to zero and solve for D. If we can solve for the D that sets us to zero, we will have recovered the optimal discriminator. Crucially, that doesn’t mean that your neural net can represent that optimal discriminator — this is more in a case where we have a very expressive function and we can just not worry about parameters and just characterize the function that would be the optimal solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*aqAtKWDRqZUZ4l7vSzcOaA.png" /></figure><p>What I’m going to claim is that if I plug this in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*fVJIPRQYmcrPOCkk8SizkA.png" /></figure><p>Then the derivative will be 0. An expected value is just a sum over all possible x’s of the probability times the quantity inside the expectation, so the expected value under p(1/D(x)) is just a sum over all x’s of p(x) divided by D(x):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*I0yoULaX9O6_tVloSpb14g.png" /></figure><p>The same goes for the second term. In both expectations, the denominator and the distribution with respect to which we’re taking the expectation cancel out, so we’re just left with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*8lOHJhtwhBhIkqDcEaVHkQ.png" /></figure><p>Which equals 0. This expression D*(x) is in fact the optimal classifier that we can get if our positively labeled points come from p of x and our negatively labeled points come from q of x. This is the Bayes optimal classifier.</p><p>Taking p data(x) to be p and pG(x) to be q, we can derive the optimal classifier D*(G) as a function of G. If G is fixed and we optimize the discriminator’s convergence, if our neural net is very very expressive, in the limit this is what we should get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*J9ggkZQ0SC6-FpgoUCTQpQ.png" /></figure><p>Now, what’s the objective for G? We can simply plug in D*G(x) into the min-max optimization of above and turn it into just a minimization over G. I emphasize that this is purely a theoretical exercise, the only reason we’re going through this is in order to understand what the GAN objective really is. So if we substitute this in. we basically just have to write out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*tr2quGz4gesYJvJVVRL7Gg.png" /></figure><h4>What does the GAN optimize?</h4><p>Here’s the expression that we arrived at: it has these two funny expected value expressions. Do they actually mean something?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*aaS3k2U2MGbxz4jmiaAbWg.png" /></figure><p>Well, let’s define another distribution that we’re going to call q, which is the average of p data and pG. So, we’ll define q(x) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*mcB2_qBEmdmk_89TwgRUNg.png" /></figure><p>Then, we can write our expression for the generator objective as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*CGYi_yguyYpK0aqGudWxGA.png" /></figure><p>Each of these terms is a KL divergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*y9qfDm3KU1YHBlTlsPtOcQ.png" /></figure><p>It turns out that this expression is actually another divergence measure called Jensen-Shannon divergence. It has some interesting properties:</p><ul><li>It goes to zero if the distributions match</li><li>Unlike the KL divergence, it’s symmetric</li></ul><p>This means that the GAN really is trying to match the data distribution</p><p><strong>A small practical aside about GANs</strong></p><p>Following all the derivations that we had so far, the conclusion should be that the generator loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*TvyW4ZipUsL38EfG8nV11A.png" /></figure><p>Which amounts to saying: let’s minimize the probability that the image is fake. In practice, we actually often use a slightly different loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*mxdhM_gZRamMA1UAwCcyrA.png" /></figure><p>Which amounts to saying: let’s maximize the probability that the image is real. These two things are very similar and they represent the same concept, but their gradients look a little bit different when you’re very far from the optimum. The reason why it is better to maximize the probability that the image is real has to do with the shape of the function log x and the function log 1 minus x:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*mAcUVdqivInpEDIDlI7ySg.png" /></figure><ul><li>If you have a very bad generator, you’re going to have a large loss value, so you’re going to be on the left side of these two curves.</li><li>If you have a very good generator, you’re going to have a low loss value, so you’re going to be be on the right of these two curves</li></ul><p>The problem with minimizing the probability that the image is fake is that the gradient tends to be pretty small when the generator is bad and then it becomes really steep on the right once the generator is good; we don’t really want that because it’s most important for the generator to learn very well when the generator is bad. If it can’t make progress when it’s bad, it’s never going to get good</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*jC25CcNQS0nFBGA5JmENtA.png" /></figure><p><strong>A few practical notes on GAN architectures: how do you actually set up the GAN?</strong></p><ul><li>You could have a fully connected architecture. You could take your your z’s and mount them through two fully connected layers with 512 units each and produce an MNIST digit. Then you could have your discriminator also have two fully connected layers of 512 units each and produce a true/false output, with a sigmoid non-linearity at the end.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*53hehQvGvihBbT8RpiXfeA.png" /></figure><ul><li>You could have a more complex convolutional GAN, maybe similar in spirit to some of those VAE architectures where you might have some transpose convolutions actually produce a higher resolution image and then a convolutional discriminator that produces your true/false label</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*QRwDeM-HLxZZIsp-R4ogLg.png" /></figure><ul><li>A BigGAN is a very modern GAN that produces high resolution images. This architecture is much more complex but it is conceptually quite similar to the previous one. The basic principle is the same: it’s going to be some kind of transpose convolutional style structure</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1q4eCEpi8SzobeveHaQzTA.png" /></figure><ul><li>Conditional GANs generate images of a particular class. All you have to do is you have to concatenate your class label shown here as y to both the input to your generator and the input to your discriminator. You take your class label represented as a one-hot vector and just concatenate it to z and then for the discriminator concatenate it to x</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*PwpfGqoH_vy-tJitD3BHxg.png" /></figure><ul><li>CycleGAN is concerned with a very particular problem: not just generating any image, but specifically translating from one domain into another. For example, if you get a large collection of photographs of zebras and a large collection of photographs of horses, can you turn a zebra photograph into a horse? The problem is that you would be given these images but you won’t be given pairs: it’s not like english to french translation, where you get a sentence in english and a corresponding sentence in french. You just get one collection of horses and a different collection of zebras</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*5IKX2wBm9XKwy2tBZWQ4sw.png" /></figure><p>We have two conditional generators and two discriminators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*FwFT7CItDnf6rq00rs348A.png" /></figure><p>G turns X into Y, so it’s conditioned on x, which might be a photograph of a horse, and its job is to generate y, photographs of zebras.</p><p>Dx is trained where positives are real pictures of horses and negatives are generations from G and Dy is trained where positives are real pictures of zebras and negatives are generations from F. But of course in order for F to generate a sample it needs to be given some x, so F will generate a zebra given a horse. We can now imagine training these two generators and two discriminators and now we’ll have a generator that turns horses into zebras and another generator that turns zebras into horses. But we’re not done yet, because nothing about this says which horse or which zebra you should generate. So the problem is why should the translated zebra look anything like the original horse?</p><p>That’s where the cycle consistency loss comes in: if I turn this horse into a zebra and then turn that zebra back into a horse, I should get the same horse and that’s measured in terms of distance. Literally, the pixels in the image should be close together in terms of their absolute value difference. So, that is the idea behind CycleGAN: two GANs, one for each domain, and a loss that says: if you map from one domain to another and then back, you should end up in the same place where you started.</p><p><strong>Brief summary</strong></p><ul><li>The GAN is a 2-player game. This is the equation for it:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*bHT0TXw56bLbSQjW32Jguw.png" /></figure><ul><li>We can derive the optimal discriminator and from this determine what objective is actually minimized at the Nash equilibrium</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*R35MNRo72WQeyEdCwdRGew.png" /></figure><p>This does not guarantee that we’ll actually find the Nash equilibrium; so, this derivation just shows that if we find the Nash equilibrium, the fixed point for this GAN, it will minimize the divergence.</p><ul><li>We can train either fully connected or convolutional GANs and there’s a lot of liberty that we have in terms of determining their architecture</li></ul><h4><a href="https://www.youtube.com/watch?v=RdC4XeExDeY&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=60">Modern techniques for training GANs</a></h4><p>If you just implement GAN training the way I described until now, you’ll probably find that in all about the simplest problems, it requires an enormous amount of hyperparameter tuning for it to work well. One particularly difficult scenario for GANs that perhaps illustrates this problem is the following: let’s say that x’s are one-dimensional, so that I can draw them on the slide. Now, let’s say that these blue circles represent real data; let’s say that these orange circles represent samples generated by your current generator. You could imagine the distributions like these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*1haK2OD9JW26rrcO80Jv3w.png" /></figure><p>If I train my discriminator with pdata and pG, my discriminator might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*3wMMXkAk5O5-TdK_vfHEKA.png" /></figure><p>It’ll be perfectly 1.0 close to the real data and it’ll be perfectly 0.0 close to the generated data and we’ll have some decision boundaries somewhere in the middle, very far from either distribution.</p><p>Remember that the generator learns entirely by using the gradient through the discriminator, so what will the generator gradient actually be near the generated data? Well, the discriminator is outputting zero pretty uniformly over all those points.</p><p>How can we make sure that even when the generator is very bad compared to the discriminator and when the generated data is very far from p data, the discriminator still gives us a meaningful gradient signal?</p><ul><li>One thing we can do is we can somehow alter our discriminator; maybe we can somehow change how the discriminator is trained, so that even if it can perfectly classify p data from pG, it is still encouraged to produce a smoother slope between these two distributions to give the generator some gradient signal to guide it towards p data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*pGO6pRwoQ8lEtRAyNiZV5Q.png" /></figure><ul><li>Another thing we could do is we could basically alter the distributions a little bit, maybe we can somehow modify p data and pG so they overlap more and then the discriminator will not be quite so sharp — then we’ll see a stronger gradient signal</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*PIfPsQnINyEAdQAaUFtNjw.png" /></figure><p>Both of these are viable ideas and we can actually instantiate this intuition in some practical methods. Here are some improved GAN techniques that are good to be aware of in no particular order:</p><ul><li>Least-squares GAN is a way to modify the GAN discriminator to output a real valued number instead of a probability between zero and one and train the discriminator so that it produces a smoother slope</li><li>The Wasserstein GAN is a way to modify the discriminator to be Lipschitz-continuous, which also encourages it to have more of a cleaner slope between p data and pG</li><li>Gradient penalty is a way to improve the Wasserstein GAN, so the discriminator is constrained to be continuous even harder</li><li>Spectral norm is a way to really constrain the discriminator to be continuous</li><li>Instance noise is trying to change the distributions by adding a lot of noise both to p data and to generated samples in the hopes of getting their distributions to overlap more</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*g9SnFEEW7w0A3Z1lt7GvfQ.png" /></figure><p>In this article, I’m going to focus primarily on Wasserstein GAN and then briefly remark gradient penalty and spectral norm, but do keep in mind that things like least-squares GAN and instance noise are also viable choices</p><h4>Wasserstein GAN</h4><p>The high level intuition is that the Jensen-Shannon divergence used by the classic GAN doesn’t have any way to account for distance. Essentially if you have this scenario:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*iHCqplBeyZtqxLwBpFLbDg.png" /></figure><p>You can say these two distributions are really far apart. Or you can have this scenario and notice that these two distributions are really close together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*vxScjaKQ4PbLTsDkBbxBUQ.png" /></figure><p>In terms of JS divergence, these two cases are about the same because in both cases the overlap between the distributions is negligible. So, the JS divergence, KL divergence and most other divergences that purely use the probabilities are almost identical in these two cases, even though clearly the bottom one is much much better. This is the high-level reason why it is so difficult to get a meaningful gradient in a GAN when the generator is very bad: because a good gradient should tell you that the way to improve the situation up above is to move towards a situation down below, but if your divergence measure thinks these two distributions are almost the same, then of course it’s not going to have much gradient.</p><p>The reason that this is true mathematically is if you look at the form of the JS divergence in the form of the of the GAN objective, you’ll see that basically it’s expressed in terms of log probabilities under one distribution in expectation under another distribution. So if p data is approximately zero for all the x’s where pG is not zero and pG is approximately zero for all the x’s where p data is not zero, then these expressions will just not give you any meaningful gradient. That basically explains why the top situation is considered to be very similar to the bottom situation, as far as JS divergence is concerned, despite the fact that in the bottom case these distributions are really close together.</p><p>What we can do to rectify this problem is to try to come up with a way to train a GAN with a different divergence measure that better captures how far apart two distributions are. Here’s how you can think about a better metric: consider how far apart all the bits of probability are in Euclidean space; imagine those distributions are basically piles of material piles. How far do you have to travel to move the dirt from one pile into another? This is sometimes referred to as an optimal transport problem. How far do you have to go to transport one distribution to another? The total distance you have to travel is how far apart these two distributions are.</p><p>Wasserstein distance is formally defined as the expected value of the distance between y and x, where y and x are distributed according to the optimal choice of joint distribution gamma. So, you find the best gamma for minimizing this expected value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*Pql8lu_vUGwkGIQR545XSQ.png" /></figure><p>Gamma is a joint distribution over x and y, where the marginal with respect to x is p data and the marginal with respect to y is pG. The intuition is that correlations between x and y in gamma(x,y) indicate which x should be transported to which y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*X1yF4uaMgjh82d7_TgX01g.png" /></figure><p>In order to evaluate the Wasserstein distance, you find the gamma that minimizes the expected value of these distances, that minimizes the discrepancy between the x and the y for every y that goes to that particular x. Intuitively, finding gamma is like finding the optimal plan for moving all the points in p data into pG.</p><p>Unfortunately, actually learning gamma directly like this is very very hard, because p data is unknown and gamma(x,y) might itself be some really really complex distribution</p><p>There’s a really cool theorem that we can use based on Kantorovich-Rubinstein duality, which provides us with a much more tractable way to solve for the Wasserstein distance. The statement is that the Wasserstein distance is also equal to the supremum over all possible functions f of the expected value under p data of f minus the expected value under pG of f:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*MEJdFqmazEGUmVSQxVupHQ.png" /></figure><p>The crude intuition is that f is gonna come from the same place where you get a Lagrange multiplier. So, you have a constraint on gamma, which is the marginals of gamma need to match p data and pG and you’re gonna basically take the dual of that. The really appealing thing about this expression for the Wasserstein distance is that it expresses the difference of expectations under pG and p data, just like a regular GAN</p><p>The supremum was taken over this funny expression that says:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*S70jPQR-FAg1VDbGO9sgHQ.png" /></figure><p>That’s shorthand for saying that you should do this over functions that are 1-Lipschitz. This means that the difference between f of x and f of y should be less than or equal to the difference between x and y. This is kind of equivalent to saying that the function is bounded slope — so it should never be too steep, because if f is too steep, then it can arbitrarily maximize f of x under p data and arbitrarily minimize it under pG. This limit on slope is a kind of speed limit on how fast you can travel when you’re carrying bits of one distribution to another.</p><p>How do we enforce that the slope of f should be bounded by some constant? That is basically the hard part of instantiating WGAN. Here’s an idea, which is not necessarily the best one, but it’s one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*1RyoAwTS-GIypCqSXpVl4A.png" /></figure><p>If you have just a 1-layer network, so one linear layer followed by a ReLU non-linearity and all of your entries in W are between -0.01 and +0.01, then the slope can’t be bigger than 0.01 x D.</p><p>If you have a 2-layer network, then you can constrain all the entries in both weight matrices to be between -0.01 and +0.01. Then your slope is also going to be bounded; of course it’s a lot bigger than before, because you’re actually multiplying these w’s together, but it’s still bounded by a constant so this doesn’t guarantee that it’s 1-Lipschitz, but it does guarantee that it’s something-Lipschitz for some constant, which means the slope will be bounded, which means that you will get some multiple of the Wasserstein distance.</p><p>The caveat is that weight clipping is clearly terrible as a way to enforce a Lipschitz constraint. If the clipping parameter is large, then it can take a long time for any weights to reach their limit, thereby making it harder to train the critic until optimality. If the clipping is small, this can easily lead to vanishing gradients when the number of layers is big, or batch normalization is not used.</p><p>But if we want to work through this Wasserstein GAN procedure, here’s how it works. We would have our generator just like before and we would have a discriminator that now instead of outputting the probability that the image is real, it actually just outputs a real number. That real number is unconstrained, so you just have a bunch of linear layers with ReLUs and no sigmoid at the end. The discriminator is going to use weight clipping, so here’s how that’s going to work.</p><p>Every iteration of your stochastic gradient algorithm you would update the discriminator using the WGAN objective. Then, you would clip all the weight matrices inside theta to be between some constants and that would ensure that the discriminator is k-Lipschitz for some fixed finite k. Finally, you would update your generator to maximize the expected value of f of G(z)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*QXzqy5Zroq8Sk1cFHuLo2A.png" /></figure><p>How do we do better discriminator regularization, as weight clipping is a terrible way to enforce a Lipschitz constant?</p><ul><li>One very simple and very effective method is called gradient penalty. If what we started with is the idea that we want to bound the slope, why don’t we just directly write down an expression for the slope and just add that to our objective?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*OPay1_-29lmv42wtOE23jw.png" /></figure><ul><li>Spectral norm is a somewhat more complex approach. The trouble with gradient penalty is that it’s not actually a constraint, it’s just a penalty. So you really need a Lipschitz constraint, but this is just giving you a penalty. If you actually want a constraint, you can bound the Lipschitz constant in terms of singular values of each weight matrix in your network.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*2SVE4-XedQeBxFlmyLDXXQ.png" /></figure><p>If your function f of x is a composition of multiple functions, the Lipschitz constant can be written as a composition of three functions. All we have to do is to bound the Lipschitz constant of every layer of our network. The maximal slope of ReLUs is one, so you don’t have to worry about them; the maximal slope of linear layers is the spectral norm of w, which is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*wHg_17N6vE5BzOjgtCTzzw.png" /></figure><p>All you have to do is to ensure after every step that the spectral norm of every weight matrix in your network is less than or equal to one; to ensure this, you just divide every weight matrix by its spectral mass</p><h4>Summary</h4><p>GAN training is really hard, because the discriminator can provide poor gradients. Various tricks can make this much more practical. For example, you can have:</p><ul><li>Smooth real-valued discriminators (LSGAN, WGAN, WGAN-GP, spectral norm)</li><li>Instance noise</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*U3lA5TulkGpChYa2Yg4JUg.png" /></figure><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a88e847f62e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convolutional networks, recurrent neural networks and transfomers]]></title>
            <link>https://samuelebolotta.medium.com/convolutional-networks-recurrent-neural-networks-and-transfomers-ee6a63ddb57f?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee6a63ddb57f</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 17:31:05 GMT</pubDate>
            <atom:updated>2022-05-19T02:00:38.042Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second of a series of articles in which I summarize the lectures from CS182 held by Professor Sergey Levine, to whom all credit goes. All images are taken from his lectures. These are <a href="https://medium.com/mlearning-ai/basic-concepts-in-machine-learning-a20de41137cc">the first</a>, <a href="https://medium.com/mlearning-ai/detailed-basics-of-deep-learning-part-three-b930c40cf7f8">the third</a> and <a href="https://samuelebolotta.medium.com/7a88e847f62e">the fourth articles.</a></p><h4><a href="https://www.youtube.com/watch?v=jNW1Hi7Yi4c&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=17">Convolutional networks</a></h4><p>Let’s say you have the picture of a cute puppy. You want to classify whether it’s a picture of a puppy, of a cat, of a hippopotamus or of a giraffe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*vGYG1ZPsJmKMcPbzyGCb_Q.png" /></figure><p>You could train a fully connected network to solve this task:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*39xw8P27QF0v98xfEvvOSQ.png" /></figure><p>However, there are at least two problems:</p><p><strong>1 Computationally intractable</strong></p><p>If we look at the first linear layer in such a network, we see it reads in an image and produces the first vector of activations. The number of weights in this linear layer is going to be equal to the number of activations in the first hidden layer z(1) times the number of numerical values in the entire image. For every pixel in the image and for every colour channel, we need a number of weights equal to the number of outputs.</p><p>Let’s say:</p><ul><li>This image is 128x128x3 (49.152 numbers)</li><li>Our first hidden layer has 64 dimensions, which is actually a pretty small hidden layer</li></ul><p>Even then, the total number of parameters in this first weight vector will be 64 times 49.152, which is over 3 million:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*FvEMCXm2r61v3KItJ9Y7kQ.png" /></figure><p>That’s just in the very first layer for this tiny 64-dimensional hidden layer.</p><p><strong>2 Not robust to shifts</strong></p><p>If the photograph of the puppy is shifted to the left or to the right by even a single pixel, it’ll look totally different to the network.</p><p><strong>An idea</strong></p><p>A lot of the visual features that we care about are, in some sense, local. If we wanted to recognize that this is a picture of a puppy, first we would extract edges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*_9NE1FgYvGL5bXd6ZZbg9A.png" /></figure><p>And then we would extract some local regions like ears and noses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*hAq_dmd9ue_aPWwPVO4YEg.png" /></figure><blockquote><strong><em>The interesting thing about these properties is that they’re all local features: to determine if there’s an edge in a particular location, you only need to look at nearby pixels.</em></strong></blockquote><p>We can use this observation to design a type of neural network that can get away with having many fewer parameters, by first doing local operations and then performing global operations only when the amount of information has been reduced to a much more manageable level.</p><p><strong>Convolution</strong></p><p>We will build a small detector for edges and will apply it to every region in the image — because the way you recognize an edge in an image doesn’t change depending on where you’re looking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*YzbtWZSQqtz0_BjYnuGiTw.png" /></figure><ul><li>Our small detector will be called filter (or kernel).</li><li>It will have the same depth as that of the input image (3 colour channels, in this case).</li><li>Since there are 64 features, we will stack 64 filters together for every 3x3x3 region. Here I drew only four:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*e33L7BoIfaRz8kT2MncAYQ.png" /></figure><ul><li>We have 64 filters for each position in that input image, which produces a little vector of length 64 for each 3x3x3 region.</li><li>We will apply this 3x3x3 (27 numbers) filter to every patch in the image and compute 64 features. Now, 64 times 27 is only 1728, and not 3 millions. As the convolution filter slides along the input matrix for the layer, the convolution operation generates a feature map, which in turn contributes to the input of the next layer.</li><li>After that, we apply non-linearity to each of them, just like we did in the regular neural network</li><li>We now get another box, which has a depth of 64 and a width and height of also 128.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*-YscRgumFlO6ztP3mEpUeg.jpeg" /></figure><p>We have now turned our 128x128x3 image into a 128x128x64 map of activations. It’s as if every pixel has become a vector of 64 features. What do filters look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*tyR6ZuzHR4_yAdFQzHBvlQ.png" /></figure><p>You can imagine passing each of those filters over the image and for the corresponding filter the activation will be the degree to which that feature is present.</p><p>As an aside, one advantage of convolutional neural networks is that the network learns to optimize the filters through automated learning and they are therefore independent from prior knowledge and human intervention.</p><p>Convolution leverages three important ideas that can help improve a machine learning system: sparse interactions, parameter sharing and equivariant representations.</p><ol><li>Traditional neural network layers use matrix multiplication by a matrix of parameters with a separate parameter describing the interaction between each input unit and each output unit. This means that every output unit interacts with every input unit. Convolutional networks, however, typically have sparse interactions (also referred to as sparse connectivity or sparse weights). This is accomplished by making the kernel smaller than the input. For example, when processing an image, the input image might have thousands or millions of pixels, but we can detect small, meaningful features such as edges with kernels that occupy only tens or hundreds of pixels.</li><li>Parameter sharing refers to using the same parameter for more than one function in a model. In a traditional neural net, each element of the weight matrix is used exactly once when computing the output of a layer. It is multiplied by one element of the input and then never revisited. As a synonym for parameter sharing, one can say that a network has tied weights, because the value of the weight applied to one input is tied to the value of a weight applied elsewhere. In a convolutional neural net, each member of the kernel is used at every position of the input (except perhaps some of the boundary pixels, depending on the design decisions regarding the boundary). The parameter sharing used by the convolution operation means that rather than learning a separate set of parameters for every location, we learn only one set.</li><li>In the case of convolution, the particular form of parameter sharing causes the layer to have a property called equivariance to translation. To say a function is equivariant means that if the input changes, the output changes in the same way.</li></ol><p>But there’s a problem here: we haven’t made things any smaller. We’ve reduced the number of parameters, but our activations are still these giant maps that have the same resolution as the original image and potentially more depth because we might want more features than there were colour channels in the original image.</p><p><strong>Pooling</strong></p><p>To reduce the resolution of the layer, we’re going to take every 2x2x64 patch and turn it into a 1x1x64, by taking the maximum activation for each channel over each region. Why max? Intuitively, if the activations in this map represent the degree to which that feature is present, it makes sense that we would evaluate the presence of that feature in that region by taking the maximum activation. This makes it robust to small translation changes too: if the image moves by a small amount, the max in each region will probably remain the same anyway.</p><p>After the pooling, you can perform another convolution, apply another non-linearity and then perform another pooling. In general, a typical layer of a convolutional network consists of three stages.</p><ol><li>In the ﬁrst stage, the layer performs several convolutions in parallel to produce a set of linear activations.</li><li>In the second stage, each linear activation is run through a nonlinear activation function, such as the rectiﬁed linear activation function. This stage is sometimes called the detector stage.</li><li>In the third stage, we use a pooling function to modify the output of the layer further</li></ol><p><strong>Convolution and pooling</strong></p><p>Recall the concept of a prior probability distribution. This is a probability distribution over the parameters of a model that encodes our beliefs about what models are reasonable, before we have seen any data. Priors can be considered weak or strong depending on how concentrated the probability density in the prior is. A weak prior is a prior distribution with high entropy, such as a Gaussian distribution with high variance. Such a prior allows the data to move the parameters more or less freely. A strong prior has very low entropy, such as a Gaussian distribution with low variance. Such a prior plays a more active role in determining where the parameters end up. An inﬁnitely strong prior places zero probability on some parameters and says that these parameter values are completely forbidden, regardless of how much support the data give to those values. We can imagine a convolutional net as being similar to a fully connected net, but with an inﬁnitely strong prior over its weights. This inﬁnitely strong prior says that the weights for one hidden unit must be identical to the weights of its neighbor but shifted in space. The prior also says that the weights must be zero, except for in the small, spatially contiguous receptive ﬁeld assigned to that hidden unit. Overall, we can think of the use of convolution as introducing an inﬁnitely strong prior probability distribution over the parameters of a layer. This prior says that the function the layer should learn contains only local interactions and is equivariant to translation. Likewise, the use of pooling is an inﬁnitely strong prior that each unit should be invariant to small translations.</p><p><strong>What does a CNN look like?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*F3_G28DEh20Cn-3wL58Q6Q.png" /></figure><p>For example, this is LeNet, a network that was used for handwritten digit recognition.</p><ul><li>It takes 32x32 handwritten characters as input</li><li>C1 Convolutional layer: 28x28x6 (28 instead of 32 because of the edges (which we’ll discuss below) and 6 because it has 6 features)</li><li>Non-linearity</li><li>S2 Pooling (subsampling): 2x2 pooling that turns 28x28 maps into 14x14 maps.</li><li>C3 Convolutional layer: 10x10x16 (10 instead of 14 because of the edges and 16 because it has 16 features)</li><li>Non-linearity</li><li>S4 Pooling (subsampling): 2x2 pooling that turns 10x10 maps into 5x5 maps.</li><li>5x5x16 is small enough that now you can flatten those activations into a big vector and put them into a standard fully connected linear layer</li></ul><p><strong>Implementing convolutional layers</strong></p><p>We will need N-dimensional arrays, often used synonymously with “tensors”. Tensors are higher dimensional generalizations of matrices.</p><p>For example, the input image could be a 3D array; the filter could be 4D; the activations could be 3D. This is analogous to the weights and activations that we see in the standard neural networks, where we have 2D weight matrices and 1D activation.</p><p>Let’s say that I have an activation a(1) and I’m going to turn it into z(2):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*qYAJSdHikxGm3Uz3aLN7aQ.png" /></figure><p>Our filter is specified by a W tensor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*1kEOPoHV1859Ei9RD2b4ig.png" /></figure><p>The convolution operation will take this filter, place it at every position in the input map and produce the corresponding map. Let’s write this as an equation for position i along the vertical axis and j along the horizontal axis in z(2):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*mh9qR8CBm3e-t6P0K1W1dA.png" /></figure><p>We’re going to multiply W(2) by a point in the input activation map; we’re going to get that point by centering it at (i, j) and then by going left or right depending on l and m. This is a way of saying that, in a convolution, you have a little linear layer at every single position and you’re sliding it across.</p><p>After you do this, don’t forget to apply your non-linearity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*NElH3gW4I_FFn-g8dRaQNg.png" /></figure><p><strong>Padding and edges</strong></p><p>What if, with your kernel, you go two steps to the left and you go off the end of the image?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*e_Nn-5qSX2mHLsQr_djE6w.png" /></figure><p>You have two options:</p><p><strong>1 Cut off the edges</strong></p><p>You disallow the filter from ever being evaluated at a point where some of the indices become negative or larger than the image width</p><p>If the input is 32x32x32 and your filter is 5x5x6, the output is going to be 28x28x6.</p><p>Here’s how we can think about it. We could imagine that the filter has a radius, which we can calculate by dividing by two its height minus one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*LOKjxx6-XPGzs-DhQoOPjg.png" /></figure><p>In our example, the radius is therefore 2. If that radius goes off the end of the image, then it’s invalid — this is why we cut off on each side (bottom, up, left, right) a number of locations that is equal to the radius. 32x32 will thus become 28x28.</p><p>However, when you cut off the edges like this, our activations shrink with every layer. Some people don’t like this, especially once these activation maps get pretty small towards the end of your network.</p><p><strong>2 Zero padding</strong></p><p>With zero padding, you do evaluate the filter on the corners and the edges: any point that goes off the end of the of the image or activation map is replaced with a zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*HFHZ95m_r72ObL-3SY7oaw.png" /></figure><p>It’s important to remember to subtract the image mean first, because these zeros that you put in will be lower than any activation in the original image. Typically, you take the average pixel intensity and you subtract it from the pixel intensity at every location, so that the image is kind of centered.</p><p>One advantage of zero padding is that it is in some sense simpler: the size of the activation map is preserved and you don’t have to worry about things getting smaller.</p><p><strong>Strided convolutions</strong></p><p>As we said, the standard structure at each layer consists of three steps:</p><p>1 Convolution<br>2 Activation function<br>3 Pooling</p><p>However, the first step can be computationally very expensive, because it doesn’t require many parameters but you’re repeating matrix multiplication many many times.</p><p>Here’s an idea to make it a little cheaper: what if you skip over some of the positions? Instead of evaluating the filter at every point in the input image, you could skip by an amount called stride.</p><p>Importantly, strided convolutions are not the same as pooling, because in pooling you do compute the activations at every location and then you take the max, whereas in strided convolution you skip some locations all together.</p><p><strong>Examples of convolutional neural networks</strong></p><p><strong>AlexNet</strong> is a classic medium depth convolutional neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*cO4ekyk2CBqy-D0eyAhDCQ.png" /></figure><p>The reason why it’s drawn this way is that the net was implemented to run on two GPUs and was manually split into two parts. This doesn’t have any bearing on the functionality of the network.</p><ul><li>The input is a 224x224x3 image</li><li>The first convolutional layer is 11x11x96</li><li>These filters are applied with a stride of 4. You’ll reduce the size of the image by about a factor of four minus the edge effects due to the padding on the sides; that gives us an activation map that is 55x55x96</li><li>ReLU activation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*ri-TfxWVc0p6M6jQk_8a2g.png" /></figure><ul><li>3x3 max pooling layer, with a stride of 2. You get down to 27x27x96</li><li>Normalization layer. This is not widely used anymore.</li></ul><p>Pop quiz: how many parameters are there in the first convolutional layer? The number of parameters depends only on the filter and the filter is 11x11x96.</p><p>Remember that the size of the W matrices in each of those convolutional layers is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*1kEOPoHV1859Ei9RD2b4ig.png" /></figure><p>So you end up with 11x11x3x96, which amounts to 34.848 parameters. We are missing the number of parameters in the bias vector, which just depends on the number of outputs (96).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*c-_mqrUpllhwdm98-z1J6g.png" /></figure><p>These are quite a few parameters, but it’s still much much lower than what we would need if we had a fully connected layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*0jMwEN2lgQlMDTocOvS0kQ.jpeg" /></figure><p>Finally, we have fully connected layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*0gErWPV_cLpxBCYR2rGL8w.png" /></figure><p>You can see a few patterns:</p><ul><li>Pooling layers reduce the size of the activations</li><li>The number of features tends to go up as you go deeper: we’re trying to summarize all the information in the image with lower resolution activation maps that are deeper, which helps us represent more abstract features.</li><li>Once things get small enough, we flatten them and put them through a few fully connected layers to produce an answer</li></ul><p>These patterns are valuable. But AlexNet is not used anymore and the best nets for processing visual inputs these days tend to be quite a bit deeper.</p><p><strong>VGG </strong>is built trying to pursue standardization and modularization, which really helps when we have to build very deep networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*kAIQpMA3xBSfQ5U6a4MG1Q.png" /></figure><ul><li>The input is a 224x224x3 image and we hit it with stride 1 and zero padded convolutions: there is no resolution reduction. These are gigantic activation maps, but the filters are very small (3x3x64).</li><li>Non-linearity</li><li>2x2 max pooling layer to reduce resolution.</li><li>Two layers of convolution</li><li>Non-linearity</li><li>2x2 max pooling layer</li><li>Three layers of convolution</li><li>2x2 max pooling layer</li><li>Three layers of convolution</li></ul><p>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*FZhUZIU7pIRJmXskS9CG1g.png" /></figure><p>You can see the motifs here: we have two to three layers of convolutions that don’t reduce the resolution at all, interspersed with pooling layers that reduce the resolution by half. Each time we reduce the resolution by half we typically increase the number of filters and at some point it’s small enough that we could construct our first fully connected layer.</p><p>A few observations:</p><ul><li>More layers means more processing and that’s why we see these repeated blocks</li><li>Most memory is actually used at the beginning, because at the beginning we have these gigantic activation maps</li><li>The number of parameters is largest in the fully connected layers in which we flatten the activations into a giant vector</li></ul><p><strong>ResNet </strong>was originally introduced with 152 layers, but since then people have used similar ideas to scale up networks.</p><p>I will show a diagram of a heavily simplified 18-layer prototype: the full 152 layer version is analogous to this, except that everything is stretched out quite a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*R4UCKPpv__xjFcCcs1PlGg.png" /></figure><ul><li>We start off with one 7x7 convolution, which gets us down to a lower resolution. Then, we have these repeated blocks of 3x3 convolutions with resolution reduction in between them; the number of filters goes up by a factor of two as we go until you hit 512 and then you stay there.</li><li>We have generic blocks with many layers, interspersed with a few pooling operations.</li><li>The other notable feature of this model is that instead of having this giant fully connected layer at the end, we simply take our last convolutional response map and we average the feature vectors at every location</li><li>Then we have one linear layer going right into the softmax</li></ul><p>Let’s see why ResNet can train with such a large number of layers. These are some experiments that were conducted by the authors of the ResNet paper, studying the effect as we increase the number of layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*HmPmC7xe8H0RO9o5WxyMAw.jpeg" /></figure><p>On the left you can see their experiments with a standard convolutional network as you increase the number of layers from 20 to 32 to 44 to 56. What you can see here is that the error rate increases as the number of layers increases. What the the ResNet people figured out is that with a modification to the neural net architecture, you could reverse this trend and see accuracy increasing as the number of layers increases.</p><p><strong>What is the main idea?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*RGhizyp2O4sE_Rm8OpYUfA.png" /></figure><p>In the regular network on the left, you have your weight layers, which can be convolutions or fully connected and you apply them in series. On the other hand, for a residual network you take every group of two convolutions and you add the input to the first one to the output of the second one.</p><p>So if in the regular net you consider every group of two convolutions computing some function h(x), in the residual net that group of two convolutions will be computing h(x), where h(x) equals what happens in the regular network plus x. X gets to bypass those convolutions and gets added at the end. The intuition is that you compute a change to x instead of computing an entirely new x.</p><p>To understand this intuition, we have to reconsider why it’s so difficult to train very deep networks. The chain rule just looks like a multiplication of a bunch of jacobians; for some arbitrarily deep network, the derivative of the loss with respect to the weight matrix of the first layer will be a product of a huge number of jacobian matrices. Then at the end you multiply that number dL / dz(n):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*qzvIu05tmvO5jzkIMhuD2w.png" /></figure><p>These jacobian matrices can be all sorts of different things. Derivatives of non-linearities, derivatives of linear layers, derivatives of convolutions. If we simplify for a second and think about scalars, the problem with multiplying many numbers together is that there are two possible outcomes: if most of the numbers are less than one, we’re going to get zero, whereas if most of the numbers are larger than one, then we get infinity. There’s a very small set of cases where the answer is more interesting and that small set of cases is when all the numbers are close to one: the only time that you get a reasonable answer from multiplying together many scalars is if they’re all close to one.</p><p>By the way, this is why we prefer ReLUs instead of sigmoids; the derivative of a rectified linear unit is the indicator of whether the input is positive, which means that a large fraction of those derivatives are just 1.</p><p>For matrices, being close to one doesn’t mean that every entry is one, it means that the eigenvalues of the matrix need to be close to one.</p><p>If we look back at our image, with the residual layer dH/dx is given by dF/dx plus identity, because you’re just adding x. As long as the weights in the convolutional layers are not too big, you might hope that this dF/dx would not be too big either. At that point, this sum would be pretty close to identity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*IHr1n-QZN4zYMRi6mUtaAw.png" /></figure><h4><a href="https://www.youtube.com/watch?v=0dNAhN4ypFc&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=20">Getting neural nets to train</a></h4><p>Remember that neural network optimization landscapes are problematic and the neural networks are messy. They require lots of tricks to train well and knowing those tricks is really important for good results, just as important as understanding all of the theoretical nuances. We’re going to talk about:</p><ul><li>Normalizing inputs and outputs</li><li>Normalizing activations (batch normalization)</li><li>Initializing weight matrices and bias vectors</li><li>Gradient clipping</li><li>Best practices for hyperparameter optimization</li><li>Ensembling, dropout</li></ul><p><strong>Normalizing inputs and outputs</strong></p><p>Let’s say that you have this neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*3D2-9hAPzIa6Phjc-aJkQw.png" /></figure><p>It takes in a 2D input and some of our data points look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*szWCR_CCc1vqnyv3yfKFKQ.png" /></figure><p>Here, everything looks normal. X1 and x2 vary and this is a standard setting where you’d expect everything would work well. But if we look at this scenario:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*XC-ZHqWI6O2iTh3PRqj-7Q.png" /></figure><p>The first dimension is on a very different scale from the second dimension. Its numerical value is larger and its range is larger. The actual information represented by these data points might be exactly the same and it could be that if you were to rescale the bars for the data points on the right, you might get things that look exactly the same as the distribution on the left. The resulting gradients will be poorly conditioned and the network will be biased towards paying attention to the larger numbers before passing into the smaller numbers, even though they’re not necessarily more important for the prediction problem.</p><p>Standardization is what we do to solve this issue: we transform our inputs so that they tend to have means of zero and standard deviations of one. All you have to do if you want the mean to be zero is subtract the mean from every dimension of x:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*tIqnZlJheY3umvEsJoOUiQ.png" /></figure><p>The expected value of x is the mean and you estimate it by averaging all the x’s in your data set.</p><p>If you want to also make the standard deviation one, then you do the same exact thing and you also divide by the standard deviation of x in the data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*nNF4FilQqDZBt6m80G6dpA.png" /></figure><p>It’s also a good idea to do this for outputs, if you’re solving a regression problem.</p><p><strong>Normalizing activations (batch normalization)</strong></p><p>To also standardize the activations, we will use mini-batches to estimate mean and standard deviation. Instead of estimating the mean by averaging the activations over every data point in the data set, which would be very expensive, we will estimate the mean by averaging together the activations of all the data points in the batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*7sl8L3cfvwXDA0rTcpMdkQ.png" /></figure><p>We do the same thing for the standard deviation. Instead of computing the standard deviation over the entire data set, we compute it only over the batch. In a practical implementation, we would also have two additional parameters for our activations (gamma and beta). After we subtract the mean and divide by the standard deviation, our activations will be in a particular range, but we might not want that going into the next layer. And we might want to have a transformation on them instead, by multiplying them by a scale and adding a bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*l-Y8nm3bLKSu4T1lKLIlLg.png" /></figure><p>You can think of batch normalization as a layer that calculates mean and std from all the activations going into the batch norm layer in the current batch and then has parameters gamma and beta.</p><p>A few practical details:</p><ul><li>If you do use batch norm, you can often use a larger learning rate because it’s going to make your derivatives more well conditioned and will prevent to some degree these really awkwardly scaled objective landscapes, where some dimensions have much bigger gradients than others.</li><li>Models with batch norm can train much faster and generally require less regularization</li></ul><p><strong>Initializing weight matrices and bias vectors</strong></p><p>We’re not going to try to initialize our weights so that they’re close to a good solution, we’re just going to initialize them so that, at initialization, the derivatives of the neural network are of high quality — meaning they point in a direction of an optimum.</p><p>One very simple choice for small networks is to initialize the weights to some small random numbers; for example, we could pick a normal distribution with a mean of 0 and a standard deviation of 0.0001. But as your network gets deeper, this will quickly give you bad answers, because if the activations are zero, then the gradients are zero. And if the gradients are zero, then you’re not making any progress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*knVBMJZMPf6J-eV99v89Uw.png" /></figure><p>In fact, this corresponds to a really bad plateau.</p><p>To avoid this issue, we use Xavier initialization. The goal of Xavier Initialization is to initialize the weights such that the variance of the activations is the same across every layer. This constant variance helps prevent the gradient from exploding or vanishing. I won’t explain all the details of the mathematical justification, because it is not the purpose of this article. A rough description follows.</p><p>Let’s say that we’ll initialize our weights at some linear layer so that our weights are sampled according to a gaussian distribution with a mean of 0 and some variance sigma w squared</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*dygG4lI2DpzBBIHDeh2l_A.png" /></figure><p>What should we set the variance to be?</p><ul><li>The biases will be initialized to zero and this is the formula for every entry in z</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*kRKpAVkjofdK3N4ZxHsy8A.png" /></figure><ul><li>We standardize x and therefore the activations are gaussian.</li></ul><p>What will be the magnitude of these z’s? If the means are all zero, then the magnitude of the z’s is their standard deviation. If we write out the the variance of z, since z is zero mean, that’s just the expected value of z squared:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*83c52HFZS_8iVGB0u_2m9Q.png" /></figure><p>You take the expected value of the squared sum and you take each of the terms in the sum squared. This simplifies to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*Xx5XcdZTdOKvMlso9ys-Ow.png" /></figure><p>The dimensionality of a times sigma w squared times sigma a squared.</p><p>We got on this track because we were worried that our choice of initialization for the weights will either increase or decrease the magnitude of the activations. If the previous layer has activations with a variance of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*TZ8FoHWtD1wztMQXu4qHuQ.png" /></figure><p>And the next layer has activations of magnitude:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*Xx5XcdZTdOKvMlso9ys-Ow.png" /></figure><p>Then we know that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*s31JpYUfIk-oZAhhnXT82g.png" /></figure><p>If we want the magnitude of the activations to stay about the same layer after layer, we need to somehow make sure that Da sigma w squared is about one. We could choose sigma w squared to be one over Da:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*xGgezfzghWdJ4DwURbkpTQ.png" /></figure><p><strong>The basic principle is that we need the standard deviation to be 1 over the square root of the dimensionality of the incoming vector.</strong></p><p>There’s a detail that we missed: we forgot about non-linearities. After we apply this linear layer, we’re going to then apply some non-linear function to the z’s and that nonlinear function will change their magnitudes. One very commonly used nonlinear function is the rectified linear unit. Deeper networks will almost always use ReLUs, because they’re much better behaved than sigmoids. However, the problem is that the ReLU will zero out many of our activations; in fact, if our activations are normally distributed and have zero mean, the ReLU would zero out about half of them.</p><p>If half of our activations will be removed, this will indeed decrease our variance. To avoid this, we make the variance two times bigger or equivalently make the standard deviation square root of two times bigger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/88/1*i_dJUruMGfk0aM251GdgYw.png" /></figure><p>An even smaller detail: biases. Earlier, we said that we’ll initialize all these bias vectors to be about zero; but again, the ReLU would kill half of them. Oftentimes, especially when people don’t use that one half factor, it’s pretty common to initialize the biases to some small positive constant like 0.1 because dead units.</p><p><strong>Advanced initialization</strong></p><p>The basic initialization I have described so far is going to work well for most problems. However, we’ll now discuss a more advanced form of initialization, both because sometimes it works well and because it helps understand what’s going on with network initialization.</p><p>The derivative of the loss with respect to the weights at some layer is given by a product of lots and lots of matrices, specifically all the jacobian matrices between that layer and the loss. Without worrying what those matrices are we can just write it as a big product. If you multiply lots of stuff together and all that stuff is less than one, the product will be about zero; on the other hand, if it’s greater than one, it’ll be about infinity. You only get a reasonable answer if all of these jacobians are close to one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*FVXuIxaPfIV1fgV7rGGZFg.png" /></figure><p>For a matrix to be close to one, its eigenvalues have to be close to one.</p><p>We can write any of this jacobians as a product of three matrices (for example, with singular value decomposition):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*7kTXjVLWpN6H8KwqrAWkoA.png" /></figure><ul><li>U and V are scale-preserving transformations; they’re orthonormal bases. That means that when you multiply a vector by the matrix U or V, it will not change that vector’s length and it’ll just rotate it in various ways.</li><li>Lambda is diagonal and the diagonal entries of lambda are the eigenvalues of the jacobian. Roughly speaking, lambda captures all the rescaling that this matrix does and U and V capture all the rotations</li></ul><p>If we can force lambda to have scales of one along each dimension, that would be enough to ensure that this big product of jacobians doesn’t yield huge or tiny numbers. Remember that the jacobian for a linear layer is just the transpose of its weight matrix, so if we want these jacobians to have eigenvalues of around one, we have to take our weight matrices and perform something like singular value decomposition on them and then somehow force that lambda to be the identity matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*-UasbzhpVaeIvjdvbFii_g.png" /></figure><p>We could take some arbitrary initialization, run singular value decomposition on it, force the diagonal to be identity and then put it back together. Forcing the diagonal to be identity just means discarding that and constructing the the final matrix as U times V.</p><p><strong>Gradient clipping</strong></p><p>Sometimes, it might happen that you take the direction of steepest descent, everything is fine, you think you’re making good progress and then you get some monster gradient that completely messes up your network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*gvjMXEUcPnUjoH0dWkqXDw.png" /></figure><p>Gradient clipping can often be a reasonable kind of band-aid to patch this issue. There are two ways that you can clip your gradients.</p><ul><li>One way is you can clip every entry in the gradient so that it’s no larger than some constant c and no smaller than negative c.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*lb4cucppFcz0yR0scBovEA.png" /></figure><ul><li>Another thing you could do is you can clip the norm of the gradient : you maintain the direction and just clip the length.</li></ul><p>To choose c manually, you can run a few epochs of training and just look at what healthy gradient magnitudes look like. This is meant to be a measure of last resort.</p><p><strong>Ensembles and dropout</strong></p><p>We’ll go from talking about how to get neural networks to optimize better to talking about how to get them to generalize better.</p><p>When we’re doing machine learning, we worry about whether our model will make a mistake and presumably how to get it to make fewer mistakes. Neural networks are going to have many parameters and thus high variance. Here’s an interesting idea: if we have multiple high variance learners and we train many neural networks instead of one, maybe these multiple neural networks will all agree on the right answer, but they’ll disagree on the wrong answers.</p><p>This is another way of saying that tere are many more ways to be wrong than to be right. Those networks will hopefully make independent mistakes, which means that when one of the models makes a mistake, another one might too but the in different ways. That’s the basic intuition behind ensembles.</p><p>Let’s say that we are solving a regression problem and let’s say that this green curve represents the true function, while the blue points are my training set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*zPUHqHKpXJdOK3LLxbKASw.png" /></figure><p>I train a large neural network model and its solution is represented by this orange line so the orange line, which is pretty good in the vicinity of my training data but it’s pretty bad away from the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*TGRe4piCS6vKL-oAWSSEzA.png" /></figure><p>I can train another model with a very different initialization and get another solution. Both these models are good on the training set and both of them are pretty bad in the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*attmCzaL1We-PARe1VKOIQ.png" /></figure><p>I’ll train another one. And if I look at the average of all three of these models, it might be pretty good. They will all disagree, but on the whole their mistakes will be centered around the right answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*icxq-l7w6GJmbH9ZQFwWXg.png" /></figure><p>Of course, this picture is a little bit idealized, but that’s the basic intuition.</p><p>What I’ll describe next is the theoretically principled way to construct bootstrap ensembles. Variance is quantified as the expected value of the difference between the model that we get from training on some dataset D and the average of all models over all possible datasets from that training distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*qdiYC2QODKUU_8Ttrb-Xfw.png" /></figure><p>If variance is high, you would expect your error to be high. But if we can estimate f bar, then we should be able to eliminate a lot of our variance. Could we somehow get m different training, sets train a different model on each one and then average together those models? We would expect that if all these different models disagree and make different mistakes on test points, then their average will be forced to agree on something close to the right answer.</p><p>But where do we get these datasets? Can we cook up multiple independent datasets from a single dataset without having to deal with less data?</p><ul><li>A simple naive approach would be to take a big dataset and just chop it into m non-overlapping parts, but that’s wasteful because then you’re training each model on a much smaller amount of data</li><li>Maybe we don’t need those m data sets to be non-overlapping and we can somehow construct independent datasets out of one large dataset, with those independent days being the same size as the original</li></ul><p>That is possible and this is called resampling with replacement. We are going to resample data points from the original dataset. Let’s say our original dataset has three points (of course, in reality we would have a lot more).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*xTDMZNey3hosytMvIMBEVw.png" /></figure><p>We’re constructing our first resampled dataset; we roll a three-sided die and we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*H5wzOj-ry85SBjMwufsx9w.png" /></figure><p>Then again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*HfCHvj8dWVTr_FlsWBH4wA.png" /></figure><p>If we sample new data points i.i.d. from the original training set, they will also be i.i.d. samples from the original training distribution. And because they are sampled independently, they end up being i.i.d. samples from the same original distribution. These datasets are going to end up being independent.</p><p>What distinguishes these models from one another is that they have different parameter vectors, because they were trained independently of one another on different but closely related data sets. Once we have these different models, then we have to somehow combine their predictions when classifying a new test point.</p><ul><li>The principled approach is to average together their probabilities, so you run these models forward, get the probabilities out of their soft max and then you average together the probabilities to get the ensembles’ predictions</li><li>A slightly simpler but still effective approach is to simply do majority voting. Instead of looking at the actual probabilities coming out of these networks, we could also just ask them to predict what they think the right answer is and then output the answer corresponding to the majority vote of the networks</li></ul><p>In practice, when we do deep learning, we rarely use this kind of resampling with replacement approach, because there’s a simpler approach that is very commonly used and that seems to work just as well. The purpose of resampling with replacement is to get enough variability between the different models, so intuitively we don’t want all the models to end up with the same incorrect solution. Resampling the data with replacement is one way to get them to differentiate, but the methods that we typically use for training deep networks already have a lot of randomness (different random initializations, random minibatch shuffling, stochastic gradient descent). No two training runs, even for the same exact model and the same exact data, are going to look the same, because of all these sources of randomness. In practice, we therefore get much of the same benefit of the ensemble without even generating these separate datasets. If we just take m different models and we train them on the exact same training set, we’ll get sufficiently different models.</p><p>The practical way to construct an ensemble out of a deep network is to simply train m different models on the same training set and then average together their probabilities or do majority voting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*JOjdEZla3Ts33ETY3E1UxA.png" /></figure><p><strong>Even faster ensembles</strong></p><p>These networks can be very large and they can be very costly to train. But remember, deep learning is all about representations, and the last layers are those that are generally task-specific and are trying to figure out the representation. That means that we can try to only ensemble those last few layers. We can train multiple different networks, but have them share the trunk that performs feature extraction and then have a different group of fully connected layers for each head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ecmNas8YhPubNmao-WsAFA.png" /></figure><p>That’s not quite as good as real ensembling, but is a lot faster to train and often easier to set up</p><p>Usually, ensembles work better when they’re bigger, but making huge ensembles is really expensive, especially if you’re training m independent models. That computation is easy to parallelize, but it still costs you something. So, can we make a huge ensemble out of just one network.</p><p>That’s what a technique called dropout tries to do. The idea behind dropout is that you’re going to take your neural network and you’re going to randomly kill some of the activations — you’ll go into each of the hidden layers and, with some probability, you would just delete some units setting them to zero.</p><p>What does this have to do with ensembles? You can think of this process of killing off some of the activations as constructing a different network out of the old one; every group of activations corresponds to a different network, so by selecting different random groups of activations to delete, you’re constructing new networks. But these networks don’t have separate weights, they actually share all of them, they just have different architectures.</p><p>The way we implement this is: during each forward pass, each time we come to some layer, we’ll compute the activations of that layer by deleting half of them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*uLpYZxUwDIBoUL5IIrYKbA.png" /></figure><p>The backward pass works exactly the same way. The gradient is an outer product with a, so if the activation was set to zero, its derivative will also be set to zero. In effect when you do this, you delete that activation from your network.</p><p>The intuition behind why dropout works is that it forces the neural network to build redundant representations and to deal with the fact that every feature has some probability of being deleted — so it can’t make predictions based on only a single feature. It forces the networks to be robust and to be more reliable. When you train in this way, you get something that looks like a really really huge ensemble, because every combination of feature deletions can be thought of as a different model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*NbQAoNhG2vcOiC3NMhijRA.png" /></figure><p><strong>What happens at test time?</strong></p><p>At training time, half of dimensions are forced to 0. At test time, we don’t use any dropout, so the product between weights and activations is twice as big. We thus divide the weights by two to compensate and get them back to their original scale.</p><p><strong>Hyperparameters</strong></p><p>With all these tricks that we’ve talked about, we’re going to end up with a lot of hyperparameters. Some of them affect optimization:</p><ul><li>Learning rate</li><li>Momentum</li><li>Initialization</li><li>Batch normalization</li></ul><p>Some of them affect generalization:</p><ul><li>Ensembling</li><li>Dropout</li><li>Architecture</li></ul><p>How do we select all these parameters? One important thing to do is to recognize which type of parameters are supposed to affect what.</p><p>For example, bad optimization hyperparameters are going to show up early in the training process. We can therefore adjust them, start training the network, look at the training error and see how it evolves in the first few epochs. Other hyperparameters are going to affect the validation error. It’s often a good idea when adjusting hyperparameters to start with a very broad sweep over hybrid parameters, train for only a little while and see how basic training progresses. Then you adjust your hyper parameters again, narrow down their range and repeat.</p><p>In grid search, parameters are defined and searched exhaustively. In random search, not all the specified parameters will be tried. Compared to exhaustive search, this method is advantageous because you can choose the maximum number of trials wanted for this search.</p><h4><a href="https://www.youtube.com/watch?v=PyZvbaC5oQY&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=30">Recurrent neural networks</a></h4><p><strong>What if we have a variable size input?</strong></p><p>A sequence input can be of variable length. For example, they might be sentences in English (the first sequence has four elements, the second one has three elements and the third one has five elements):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*-tP6xKHNeK2JL2KfxmmcDw.png" /></figure><p>This could involve:</p><ul><li>Sequence of words → The problem of sentiment classification: you have a review online and you want to guess whether this is a positive or a negative review.</li><li>Sequence of sounds → The problem of recognizing a phoneme from a sound</li><li>Sequence of images → The problem of classifying the activity in a video</li></ul><p>You need a network that can:</p><ul><li>Accommodate multiple inputs and multiple different numbers of inputs</li><li>Share features</li></ul><p><strong>One idea</strong></p><p>The number of layers becomes the same as the number of inputs. In other words, you get a separate input for every layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*MsJmtun9KfDFDNAujVZuRQ.png" /></figure><p>If you have a sequence of length four, then you’ll have four layers; if you have a sequence of length three, then you’ll have three layers; if you have a sequence of length five, then you’ll have five layers.</p><p>At each layer, we have two inputs now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*zNVNpqfGqw-obwsx5cGwsg.png" /></figure><ul><li>The activations of the previous layer</li><li>The new input x</li></ul><p>Then we apply a regular linear operation to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*TZDk_SymQyDfgrDa-Qt1MA.png" /></figure><p>As usual, we apply a non-linearity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*A_cH3UJ905kxAGGLYuHnFw.png" /></figure><p>This is very much like the standard linear layers; the only difference is that, instead of applying the linear layer to the previous layer activations, now you concatenate the new input to those previous layer activations and then pass them through the linear and non-linear operations.</p><p>What happens to the missing layers? If you have a sequence of length five, then you’re gonna have five layers, whereas if you have a sequence of length three, then you’re gonna have three layers.</p><p>Here’s a funny trick: if we have a shorter sequence, we’ll just pretend that the activations at the layer prior to the first input (this layer doesn’t exist) are all zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*g8iGGEeGKwBE79_my6_KZw.png" /></figure><p>In fact, we’ll do this regardless of the length of the sequence; even for the longest sequence, we’ll still have a virtual preceding layer where the activations are all zero. When performing our usual operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*fxM3gMYsgJtj4zODtgHFyg.png" /></figure><p>At the very first layer, we will just concatenate the input to a big vector of zeros</p><p>One big problem with this design is that we still have a different weight matrix at every layer. Really long sequences will end up requiring many of those weight matrices. However, the last few layers will be trained for all the sequences, whereas the the very first layer that is only used for the longest sequences might have been trained very rarely.</p><p>The one additional modification that we need to turn this design into a full-fledged recurrent neural network is to share the weight matrices.</p><p>What that means is W(l) will be the same for all of these layers</p><ul><li>Everything about how you evaluate this network doesn’t change</li><li>At test time, everything is exactly the same. We just initialize this virtual first layer to zero and then we proceed with these operations:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*HWFgBZXBMKOGWvDD9Ws5Zg.png" /></figure><ul><li>This only affects training. During training we have to force the matrices W(l) to be the same for all the layers:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*yX3j8oLPQR4auVo-Par6eA.png" /></figure><p>The very long sequences might require those weights at the very early layers (that we only see for very long sequences), but now those weights are the same as the ones used in the later layers and they have already been trained pretty well.</p><p>If we force the weight matrices to be exactly the same at every layer, we can have as many layers as we want</p><p>Basic design of a RNN:</p><ul><li>Very deep network whose depth is equal to the length of your sequence</li><li>Every layer gets a different input: it concatenates the previous layer’s activations with the input at that time step, it passes them through a linear layer and then a non-linearity</li><li>The very first layer gets a zero as input from the from the virtual previous layer</li><li>The weight matrices are shared at all the layers, which means that we don’t need a number of weight matrices equal to the length of the longest sequence</li></ul><p><strong>How do we train RNNs?</strong></p><p>The short answer is that we’re going to slightly modify backpropagation.</p><p>When we run backpropagation, the basic design is the same. First, we run a forward pass to calculate all the a’s and z’s at each step. Then, for the backward pass we proceed in the same way. We initialize delta to be the derivative of the final loss with respect to the last layer output and then for every linear layer and for every ReLU we calculate the derivative with respect to its parameters and the derivative with respect to its inputs (which is the previous layer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*_fyDZZ91U7RAWw8TkbtavA.jpeg" /></figure><p>The issue is that the parameters are now the same at all these layers. That means that θf at layer 4 is the same variable as θf at layer 3. If we were to run this algorithm on the following layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*kGEkfPiPbvEBSiF4HPQwqA.jpeg" /></figure><p>Starting on the right, we would compute delta to be the derivative of the loss with respect to the output at layer four and then at layer four we would compute the derivative of the loss with respect to the weights and with respect to the bias. Then, we would compute the new delta, we would go back to layer 3 and at layer 3 we would override the gradient with the gradient of the w and b at layer 3. So, taken literally, the gradient at layer l-1 will overwrite the gradient of layer l — and we don’t want that. <strong>We want the derivative of the loss with respect to w and the derivative of the loss with respect to b to account for the effect of w and b on every layer, not just the first layer.</strong></p><p>It turns out to be very very simple to fix this problem. Instead of setting the derivative “df / dθf” to be “df / dθf” x “δ”, you just need to add it to the value of the derivative:</p><p>You’ll do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*FU-VOF1R7ltpH_Pp6WT-Gw.png" /></figure><p>Instead of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*_OZvemdw6gi3qRjayZiyOA.png" /></figure><p>At the beginning of backpropagation, you initialize all your gradients all your derivatives to zero and then at every step of backpropagation, for every layer you add “df / dθf” x “δ” to the current value of the derivative.</p><p><strong>What if we have variable-size outputs?</strong></p><p>For example, we may want to generate a text caption for an image, to predict a sequence of future video frames or to generate an audio sequence. Before, we had an input at every layer; now, we are going to have an output at every layer.</p><p>One immediate thing that comes up is that each of these outputs has their own loss. At each step, just like before, we’re going to perform these operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*khTCELv42FiuX-4qFA3ZzQ.png" /></figure><p>Now, y hat at that layer will be some function applied to a (l) and that’s some kind of readout function — sometimes referred to as a decoder. The parameters of f are going to be shared across all the time steps, just like the parameters of the linear layer. We’re going to have a loss on each y hat(l) and our total loss will just be the sum of the losses at every step. That’s a very simple way to combine the losses.</p><p>The problem we have is that it’s not completely obvious how to use backpropagation at this point, because regular neural networks are a chain — where you get your delta from the next layer and you backpropagate it into the previous layer. Now, we’re in a situation in which a neural network has branches; at every time step, we’ll have a delta coming in from the loss of that step and we’ll have another signal coming in from the next step. We then need to produce a delta going back into the previous step.</p><p>We’re going to draw the computation graph for this procedure.</p><p>You have your input x, which goes into a linear layer, then a non-linearity and then we have our first readout function f1 — which could be a linear layer followed by a softmax and goes into the loss of the first time step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*UYQZuz4iM24Roy_MVdbBdg.png" /></figure><p>Sigma 1 also goes into the second linear layer. So, it produces a value, let’s say a1, and that same a1 is used by two downstream functions: f1 and lin2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*MIneWJM9b5ZAbaYVovH06g.png" /></figure><p>Then lin2 goes into sigma 2 and again, same mechanism. The losses at all time steps are added up and that’s what ends up producing the final loss value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*tzSWFMEQnFTB5yZ60zhMdg.png" /></figure><p>We can think of each layer as a function f that takes as input xf and produces as output yf. We always start backpropagation at the last function, where initial delta is just one. This is a graphical way of representing backpropagation for regular neural networks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*cokkdap1nAqCe562y3kWFg.jpeg" /></figure><p>The algorithm for regular nets is just a loop that starts at the last layer and proceeds backwards, and in each of those layers it’s going to calculate these delta “yf’s” and use them to calculate delta “xf’s” and “dL/dθ’s”.</p><p>Now, we’re going to generalize this a bit. The issue we have to deal with with RNNs is that we have some nodes whose output goes into multiple nodes. If you have a look at the computation graph I drew above, you’ll notice that the output of sigma1 goes into f1 and also goes into lin2. <strong>During backpropagation, there’s going to be one delta coming in from one of those outputs and another delta coming in from another one of those outputs. All we do is we just add them together and then we just plug them into the same algorithm.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*SKvo45LtJneyx3WehoexKw.jpeg" /></figure><p>This is also sometimes referred to as “reverse mode automatic differentiation”</p><p><strong>What if you have multiple inputs and multiple outputs at each step?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*qv1QKOugAlgTn7nXXhCn6w.png" /></figure><p>We simply combine the two concepts we saw before. At each step, we:</p><ul><li>Concatenate the activations of the previous layer with the new inputs</li><li>Apply linear layer</li><li>Apply non-linear layer</li><li>Have some readout function (which could be just a linear layer and a softmax) to produce the output y hat at that step</li></ul><p><strong>What makes RNNs difficult to train?</strong></p><p>RNNs at their most basic level are very deep networks</p><p>We have to reconsider why it’s so difficult to train very deep networks. The <a href="https://medium.com/mlearning-ai/backpropagation-6a2575f09537">chain rule</a> just looks like a multiplication of a bunch of jacobians; for some arbitrarily deep network, the derivative of the loss with respect to the weight matrix of the first layer will be a product of a huge number of jacobian matrices. Then at the end you multiply that number dL / dz(n):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*bG2s-1JilZCN6wuS" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/0*TR9Idwr00CnwCRcx.png" /></figure><p>These jacobian matrices can be all sorts of different things. Derivatives of non-linearities, derivatives of linear layers, derivatives of convolutions. If we simplify for a second and think about scalars, the problem with multiplying many numbers together is that there are two possible outcomes: if most of the numbers are less than one, we’re going to get zero (vanishing gradients), whereas if if most of the numbers are larger than one, we get infinity (exploding gradients). There’s a very small set of cases where the answer is more interesting and that small set of cases is when all the numbers are close to one: the only time that you get a reasonable answer from multiplying together many scalars is if they’re all close to one. By the way, this is we we prefer ReLUs instead of sigmoids; the derivative of a rectified linear unit is the indicator of whether the input is positive, which means that a large fraction of those derivatives are just 1.</p><p>For matrices, being close to one doesn’t mean that every entry is one, it means that the eigenvalues of the matrix need to be close to one. Exploding gradients are not too difficult to deal with because we can always clip our gradients to prevent them from exploding; the big challenge with RNNs comes from vanishing gradients. An intuitive interpretation is that if your gradient vanishes, the gradient signal from later steps never reaches the earlier steps: when that happens, your neural network becomes unable to maintain memory</p><p><strong>Promoting better gradient flow through an RNN</strong></p><p>At each layer, we’re going to concatenate the new input to the previous layer activations and then pass them through the linear and non-linear operations. We call this the “RNN dynamics”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*EiR-iZsj8j-F6Gi3LyMyTw.png" /></figure><p>The particular derivative that we care about when we talk about vanishing gradients is the jacobian of the RNN dynamics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/71/1*x7enK3rO0UxH47YbdOYM4w.png" /></figure><p>This is the derivative of q with respect to previous activations. Of course, we don’t just want to force the derivative to always have eigenvalues that are close to 1 (or to be close to identity), because sometimes we do want to forget things and sometimes we want to transform them in various interesting ways. We only want it to be close to identity when we really want to remember.</p><p>In other words, don’t just force them to be identity, but come up with some design where the network can decide that it wants to remember something; when it decides it wants to remember, then this derivative really ought to be close to identity.</p><p>The intuition is that for each unit, we have a little neural circuit that decides whether to remember or to forget. If you’re remembering, you just copy the previous activation as it is and don’t change it; if you’re forgetting, then you override it with something else</p><p>We’ll have a cell state and multiply it by some number f(t), which is between 0 and 1. This is referred to as a forget gate, because if it’s set to 0 you forget what you had, otherwise you remember:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*F6HsWdgIJD0EaUnOWUU51A.png" /></figure><p>Then, we add some number g(t)to it.</p><ul><li>If f(t)is close to zero, then the cell state is replaced by g(t)</li><li>If f(t)is close to one and g(t)is close to zero, then the cell state is retained</li><li>if f(t)is close to one and g(t)is non-zero, then the cell state is modified in an additive way and that becomes our new cell state a(t)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*Ao0RsLRI1huZLG4YxWn-Cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*Mjsv8eVRGxC4pVlmd7sThg.png" /></figure><p>Where do we get these f(t) and g(t)?</p><p><strong>LSTM cells</strong></p><p>The way that we’re going to decide whether to remember or to forget is based on another temporal signal h (t-1). H (t-1) comes as an output from the previous time step, along with a (t-1).</p><p>Then we have our input at this time step, x(t). We’ll do the same thing that we did before: we concatenate x(t) with h (t-1) and we apply a linear and a non-linear layers to them. This linear layer is going to produce an output that is four times larger than the output we had before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*UxSiwV84UeErp4knus2EJQ.png" /></figure><p>Each of those 4 rows is going to serve different functions. One of them is the f(t) we saw as a forget gate earlier and one of them is the g(t) we added to the product earlier.</p><p>1. We take f(t) and pass it through a sigmoid, which puts it in the range of 0 and that becomes the forget gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*d2YmvDRv8acnHUdciCcc5g.jpeg" /></figure><p>2. We take i (t) and also pass it through a sigmoid. This is called the input gate and it controls the modification to the cell state</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*go5xXvHQ_YWy-t8RKooSgQ.jpeg" /></figure><p>3. We take g (t) and we pass it through some non-linearity. It could be a tanh or a ReLU</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*d1mN8DmGvhVtkGkncZNrLg.jpeg" /></figure><p>g (t) is multiplied point-wise by i (t) and then you add the product to the cell state after the forget gate. Intuitively, i (t) determines whether you want to have a modification of the cell state and g (t) determines what that modification will be. This is very nice because it allows the network to independently choose whether to modify or not and separately choose how to modify</p><p>4. o (t) is called the output gate, it’s also passed through a sigmoid and it controls the next h (t). After the forget gate and after the addition of g (t), we take our cell state a (t) and pass it through a non-linearity. Then, we point-wise multiply by o (t) and that becomes the new h (t)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*BHBARhZySsCmI5BzcIjsxQ.jpeg" /></figure><p>This new h (t) is also what we use if we want a readout function / a decoder at that time step.</p><p>What is going on here is: we’re trying to preserve the role of a (t) as a linear signal. All the non-linearities are applied to the h’s and as a result the gradients on a (t) are going to be pretty simple</p><ul><li>Not having non-linear functions affecting a (t) makes its derivatives very well behaved</li><li>At the same time, we still retain the benefit of non-linearity by having a non-linear modification through g (t) and a non-linear readout through h (t)</li></ul><p>Why do these LSTM cells work better? The simplest reason is that a (t) is modified in a very simple way at each step</p><p>You can think of a(t) as the long-term memory, while h(t) is the short-term memory — it changes all the time and performs complicated non-linear processing.</p><p><strong>Practical notes</strong></p><ul><li>RNNs almost always have both an input and an output at each step</li><li>Naive RNNs like the ones in part one almost never work; in practice, if you want an RNN you will probably be using something like an LSTM cell, even though it requires more hyperparameter tuning than standard fully connected or convolutional networks</li><li>There are also some alternatives to RNNs for processing sequences that can work a lot better in practice (temporal convolutions and transformers)</li><li>There are some variants of the LSTM that are a bit simpler and work just as well (gated recurrent units)</li></ul><p><strong>Autoregressive models and structured prediction</strong></p><p>Most RNNs that we actually use in practice have multiple inputs and multiple outputs, because most problems that require multiple outputs have strong dependencies between these outputs.</p><p>These kinds of problems are sometimes referred to as structured prediction, because the thing that you are predicting has structure, in contrast to something like a label. A classic example is text generation. Regardless of whether the output of text is the right answer or not, there are relationships between words and text that determine whether it’s a valid text.</p><p>Let’s say that you have a training set that consists of three sentences:</p><ul><li>“I think therefore i am”</li><li>“I like machine learning”</li><li>“I am not just a neural network”</li></ul><p>Let’s say for now that you don’t care about generalization: you just want your model to memorize these three sentences. We’ll treat words as categorical variables; every time step will be a different word and it’ll just be one of n possible words.</p><p>Your neural network will read as input the word “I”. Then we ask it to complete the sentence and it can complete it in three different ways: “think”, “like”, “am”. Then we have a softmax distribution that turns these words into probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*Z4yZhJOXLrzGAvhV_wSyOw.png" /></figure><p>We’ll sample randomly from this softmax distribution and pick the second word. Now the network is completing the sentence and says “I think”. We then proceed to the next time step; we we have a linear layer that uses the previous activations to compute the new activations and then we have our output at the second time step, which again goes through a softmax distribution.</p><p>The trouble is that the network doesn’t know which word was randomly sampled from that softmax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*T7H5X3rca49wHDP70Uo1hA.png" /></figure><p>The network thought it produced an output that is 30% “think”, 30% “like” and 40% “am”. The problem is that you’re trying to sample these words independently. At the second time step you might randomly get “machine” and then at the third time step you might randomly get “just”. This generation makes no sense, even though the network did a great job at learning this distribution. We thus get a nonsense output and that’s because in this task the covariances between the words matter just as much as the probabilities of getting the correct words.</p><p>This is why it’s so important to have networks that take in variable length inputs and variable length outputs. When we run this network to complete a sentence, we’re going to sample from the softmax of the first time step and then we will feed our sample as an input at the second time step. This will basically tell the network what we sampled. Now the network knows that it’s not just predicting the third word in any sentence: it’s predicting the third word in a sentence where the first two words are “I think”. It’ll therefore correctly predict that if the first two words are “I think”, the third word is probably going to be “therefore”.</p><p><strong>The key idea is that past outputs should influence future outputs and the way you get past outputs to influence future outputs is by treating yesterday’s output as today’s input.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*XR49nv2p8PYmNFdPXapYWw.png" /></figure><p>This basic design is used for all RNNs that have to output a structured sequence, like image captioning models or video prediction models.</p><p><strong>Autoregressive models</strong></p><p>The simplest way to train it is to set the inputs to be the entire training sequence and the ground truth outputs to be the same sequence, but offset by one step. Instead of asking the neural network during training to just dream up a sentence, you’re asking to complete a sentence. You’re saying: at time step t, take all the words from time step 1 to t and output the word at time step t+1.</p><p>Your x’s are going to be all the tokens in the sentence and your ground truth outputs are going to be all the tokens shifted back by one. The last one will be replaced with a stop token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*HXIOcsEzrhnGOeBTZrGM4w.png" /></figure><p>Basically this network is being taught that if it sees “I”, it should output “think”; if it sees “think”, it should output “therefore” and so on.</p><p><strong>Distributional shift</strong></p><p>There’s an issue with this. The basic design I showed is going to work well, but if you use it to train really complex networks for very long sequences, you might start seeing some problems, which are due to distributional shift.</p><p>Let’s say that you have the same example as before, but the network is making some small mistakes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/87/1*kPxuHgVTv-Ei2hpQ0cLiEQ.png" /></figure><p>Why is it doing that? Maybe it didn’t train very well. Let’s say you got unlucky and you sampled the 10% word. The problem is that now you’re going to use it as the input of the next time step. Since it’s just some random token, the network has never seen it before and is going to be completely confused. At the next time step, it will thus output some completely crazy thing and then it’s not going to produce anything reasonable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*QUbWmYeiXcYTHJsD29zBAg.png" /></figure><p>This is a discrepancy between training and test: the network always saw true sequences as inputs, but at test-time it gets as input its one (potentially incorrect) predictions. This is called distributional shift, because the input distribution shifts from true strings during training to synthetic strings at test time.</p><p><strong>Scheduled sampling</strong></p><p>The basic idea is that during training we’re going to make a random decision at every step in time. With some probability, we’ll give the network the true input at that time step and with 1 minus that probability, we’ll give it its previous output as an input. Crucially, we don’t differentiate through this edge, so the network doesn’t know that it’s getting its own output as an input.</p><p>You can think of this as randomly replacing the true input with the network’s own output of the previous time step with some probability. This really helps because now during training the network sees its own outputs as inputs and therefore, when it sees that a test time, it’s not completely confused.</p><p>How do we want to choose this probability for replacing the true input with the model’s own previous output? Intuitively, we want to mostly feed in the true inputs at the beginning and then once the network gets pretty good we want to mostly feed the model’s own predictions to mitigate this distributional shift. We therefore put a schedule on this probability: the probability of using the true input starts off really high and then gradually drops. And since the probability of using the model’s output is 1 minus that, over time you’re mostly training the network on its own previous outputs</p><p>One of the big advantages of RNNs is that they afford a great deal of flexibility:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*KKgPYHHOhUfL98G1HDrAwg.png" /></figure><p>With regular feed forward networks, you have one-to-one mappings, whereas with RNNs you can have one input to many outputs, many inputs to one output, many inputs to many outputs and so on.</p><p><strong>Implementation details</strong></p><p>One of the things that we often do with RNNs is that we have an RNN backbone in our model somewhere in the middle and then we use a non-recurrent encoder (a regular convolutional network which then feeds into the RNN). You could also have some kind of complicated decoder and take the output of your RNN or LSTM cell and feed that into multiple layers before producing the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*aUpnnvoykMu03CLZQenXdQ.png" /></figure><p>You could also have multiple RNN layers, take the output of your RNN at a particular time step feed it into another RNN layer and then eventually into a softmax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*-nUB51FnF8PG5jyF4c9YBg.png" /></figure><p>Another trick you can use with RNNs is something called bidirectional models. For example, in speech recognition your inputs are sequences of sounds and you want to produce the corresponding words. Mostly, the word at a particular time step will depend on the the sound at that time step, but sometimes the rest of the sound will influence what word you think it is. So, the word at a particular time step might be hard to guess without looking at the whole utterance. A bidirectional model is an RNN where you first have a layer of recurrent connections running forward and then another layer above it running backward. That means that you have information from both the past and the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*YUWoLz5l4kTxDfka8ieQ4Q.png" /></figure><h3>Sequence to sequence</h3><p>We’re going to talk about how we can use recurrent neural networks to solve some interesting problems; we will focus on how we can train and utilize sequence to sequence models.</p><p>Recurrent neural networks are very flexible and can be used to solve a wide range of different types of sequence processing problems:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*qbVaBmcmBjCk9v_UY0xh0A.png" /></figure><p>In this article, we’re going to focus on the many to many problems. Before that, let’s discuss how we can build a basic neural language model, which assigns probabilities to sequences representing text. Language models are a very important concept for a lot of what we’re going to discuss, because they can not only assign probabilities but they can also oftentimes generate text.</p><p>Here is an example of a neural network model that generates phrases. The training data for this would be a large collection of natural language sentences. Here I’m showing just three:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*22XWZxDfwAJCTAlAsclZag.png" /></figure><p>How are they represented? There are a few choices here and we’ll go into a lot more depth later on, but a very simple choice is to tokenize each of the sentences — which means that every word becomes a separate time step — and then encode that word in some way.</p><p>A very simple way to encode the word is a one hot vector. A one hot vector is just a vector of length equal to the number of possible words in the dictionary and every element in that vector is zero, except for the element corresponding to the index of the word, which is set to one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*8tc1dkJG2XL2DUhYBULoCg.png" /></figure><p>There are more complex ways to represent words. One example is a word embedding, which is a continuous vector-valued representation of words that is meant to reflect their semantic similarity — so that words that mean similar things are located closer together in terms of the euclidean distance.</p><p>For now, let’s just say that words are one hot vectors, which means that our natural language training data just consists of sequences of these one hot vectors</p><p><strong>A few details</strong></p><ul><li>We need to understand when the model is done outputting a sentence. For example, if you give the model “I” and you want it to complete the sentence with “I think therefore I am”, how do you know that you should stop at “m”? “I think therefore I am a hippopotamus” is also a valid sentence. We’ll thus include a special token in the training data at the end of all of our sentences. This is the end of sequence token, sometimes referred to as end of sentence token. It doesn’t represent any actual word, it just represents the fact that the model is done.</li><li>We need to somehow kick off the model. For the second time step, it will use the output of the first time step as input. But what do we use at the very first time step? We could simply compute the frequency with which each sentence starts a word, sample from that randomly and then feed that as the first time step into the model. A slightly more elegant solution, which doesn’t require us to have a special component, is to introduce a start of sentence token. The model will thus learn that it should output a random word with probability proportional to the probability of actually starting a sentence.</li></ul><p>With these start tokens and end of sentence tokens, we know how we can get RNNs to generate completely random sentences. But if we want an RNN to complete a sentence, for example “I think”, doing this does not require changing the training procedure at all. We still feed in the tokens one at a time. You feed in “start”, you let it make a prediction but then you don’t sample from that prediction; instead, you directly feed in the next word that you’re conditioning on, which is “I”. Then, you let it make some prediction, you ignore it and then you feed in “think”, make some prediction and then you actually sample from that and feed that as input to the fourth step. <strong>All you have to do in order to condition your generation on a particular starting snippet is to just force those first few inputs to agree with that snippet regardless of what the network was outputting.</strong></p><p>A conditional language model</p><p>So far, we discussed unconditional language models; now, I’m going to talk about how we can build conditional language models. For these conditional language models, the text is the output of the model, not the input. You’re going to condition this model on some input that’s going to tell it what text you want it to generate. For example, you could imagine a conditional language model for image captioning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*YRS693wPfsHqF6wTRTClPg.png" /></figure><p>We can have some kind of encoder model, read in the conditioning information (the picture of the puppy) with a convolutional network, which will produce a vector representing the starting state of the RNN. This vector, a0, is the initial state of the RNN. This whole thing will then be trained end-to-end — the CNN and the RNN together will be trained together to produce the correct text.</p><p>To summarize, this is one big neural network that consists of a few convolutional layers, maybe some fully connected layers, one of which goes into an RNN. We refer to the RNN part of this network as a RNN decoder, because its job is to decode the information contained in a0 into english text; we call the convolutional part a CNN encoder, because its job is to take the input and encode it into a0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*F7028jUHKS-IYz9uk1M1VQ.png" /></figure><p>Our training data is going to contain pictures and it’s going to have labels.</p><p>If, for example, you want to translate French into English, you could have an RNN that reads in French text and produces the initial hidden state activations for another RNN that produces English text. Now, instead of a CNN encoder, you have an RNN encoder and whatever happens at the last step of the French sentence goes directly to the first step of the English sentence.</p><p>There are a few details to get this to actually work. First, sometimes people read in the input sequence in reverse, starting at the end of the sentence and then going backwards. The reason why this is better is that the beginning of the English sentence probably has more to do with the beginning of the French sentence than with the end of the French sentence. By reversing the input sentence, the first part comes last, which puts it closest to the first part of the output sentence.</p><p><strong>Sequence to sequence models</strong></p><p>We have two different RNNs for the input and the output; encoder and decoder have different weights and the encoder produces the initial hidden state activation for the decoder. This is a more realistic example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*YZCXQQ3Y0zlmVh4t9BnYoQ.png" /></figure><p>1 We read in the input sentence backwards and <br>2 We added multiple layers; multiple LSTMs (between two and five) are stacked on top of each other <br>3 The net is trained end-to-end on pairs of sequences<br>4 The sequences can be of different lengths</p><p><strong>Performing the decoding</strong></p><p>So far, the obvious way of getting a sentence from one of these RNNs is to do it one step at a time and then on the first step we have to output something, we get a softmax distribution. This means we get some vector of length equal to the number of possible words, you apply a softmax to it and that turns it into a vector of probabilities. That’s a probability distribution over the first word in the decoded sentence. The obvious thing to do at this point might be to pick the word with the largest probability and and then you feed that chosen word as the input at the next time step. This way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*Quxf_zujRlVc4nBcqDqoXA.png" /></figure><p>But notice that the network made a small mistake. On the first time step, it had a couple of possible words to choose from (of course, in a simplified scenario) and the correct word would have been “a”, but the word “one” had a similar probability, that was a little bit larger, because the French word “un” could mean both words. This seems a reasonable choice, but it ends up throwing off the rest of the decoding. It picks the word “puppy” for the second one, but “one puppy cute” is not a correct English sentence. So, the network chooses “is”, which produces a valid English sentence… But is not the correct translation.</p><p>So, what went wrong? The problem is we committed to selecting “one” before seeing the rest of the decoding. That first mistake, which was not that unreasonable, led to a completely unreasonable result. If instead of selecting “one” on the first time step, we had selected “a”, then we would have got a pretty reasonable generation later on. By choosing “a”, the probability for “puppy” at the third time step would have been way higher.</p><p>Here, probabilities depend on the entire input sequence and on all of the previous words that we generated for the output sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*ZJUHqlcNgB7-Gy0hTElB2g.png" /></figure><p>The idea is <strong>we want to maximize the product of all the probabilities</strong>, which allows us to get the most likely output sequence out of our decoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*h0_RsL3I1oEOK6387wbKvw.png" /></figure><p>Since dealing with products of lots of probabilities is annoying, we prefer expressing them in log space, where products become sums:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*h1ei5u8umNXzz3Wit9zbrw.png" /></figure><p>In order to maximize the product of all the probabilities, we should not just greedily select the highest probability on the first step. That means that we might choose a word early on with a slightly lower probability for the sake of getting a word later that has a much higher probability: it’s not always optimal to greedily pick the most likely word.</p><p>How many possible decodings are there? For M words, there are M ^ T sequences of length T. If we have only four tokens at every step, in principle we could select any of these four tokens on the first time step and any of these four tokens on the second step and any of these four tokens on the third step and so on. Of course, most of those sequences would have very low probability, but in principle any one of them could be the optimal one. Fundamentally, decoding is a tree search where the cost of a transition is the negative of its log probability (because in tree search you sum up the cost as you go) and the number of search paths increases exponentially. We could use any tree search algorithm to solve this problem, but exact search in this case is very expensive, because this problem doesn’t really have a nice structure that makes things like breadth first search and depth first search work really well. Fortunately, the structure of this problem makes some simple approximate search methods work very well.</p><p>The basic intuition, based on what we know about sequence decoding, is that while choosing the highest probability word at the first step may not be optimal, choosing a very low probability word is very unlikely to lead to a good result — this is not always true in search in general. So, we can’t be greedy, but we can be <strong>somewhat </strong>greedy. This algorithm is called beam search and instead of greedily decoding the best word at every step, it stores the k best sequences so far and then updates each of them. The special case where you set k to 1 is just normal decoding, because you always take the most likely word.</p><p>Here’s an example of beam search with k = 2. There’s a sentence in French that we’re going to translate to English and it’s intentionally chosen to be a somewhat non-trivial translation, in the sense that there’s no perfectly equivalent English word for “entarté”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*KOR_CoFvJ44fVLJ0d7r1ew.png" /></figure><p>Every step of the way, we track the two most likely hypotheses. We begin with a “start” token and we produce the softmax distribution — we run our RNN forward one step, produce a softmax distribution over the first word and track two of the most likely hypotheses. We get “he” and “I”. Now, we’ll step the RNN forward conditioned on the word “he” and then we’ll separately step the RNN forward conditioned on the word “I”. For those two forward steps, we’ll have four different softmax distributions over the second word in total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*f18K4uIfufN_CvLVaUk8dg.png" /></figure><p>Then we’re going to calculate the sums of the log probability for the top two words when we stepped with “he” and for the top two words when we stepped with “I”. We now have four scores and we take the best two: “I was” and “He hit”. We’ll keep expanding those two further:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*5AeIU6qUv9OAWfMnvv-oyg.png" /></figure><p>And again, same as before. When do we stop decoding? Quite simply, if one of our scoring hypothes ends with the END token, we stop expanding it and save it there. We would continue until either some cutoff length or until you have some predefined number of completed sequences. At the end, which sequence do we pick?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*FRi47ldH7VNgsaWK9HPoOg.png" /></figure><p>Remember that each of these scores is a sum of the log probabilities of every step, but the number of steps is different in every sentence. The longer the sentence, the more of these negative numbers we’re adding up, which means that in general longer sentences are going to tend to have lower log probabilities: in order to avoid that short but bad translations get chosen more often than longer and good translations, we actually define a score as the total log probability divided by the number of steps.</p><p>In summary, that’s beam search and it will do a really good job of decoding the most likely sentence most of the time. In fact, oftentimes very small values of k can work well, so 5 to 10 is pretty typical but even numbers as low as 2 might sometimes work well.</p><p><strong>Attention</strong></p><p>Here, I want to briefly introduce the notion of attention for sequence to sequence models. This stems from the fact that in sequence to sequence models we have the bottleneck problem: all the information about the source sequence has to be contained in the activations at the beginning of decoding. The decoder doesn’t know anything about the source sequence, except what the encoder puts into the first hidden state. That can be a big problem when the input sequence is very long.</p><p>Maybe we can relax this a little bit if we allow the decoder to peek into the input sequence a little bit more while it’s decoding. If your input is an entire paragraph and the encoder encodes the general gist of it, we want the decoder to get to that point and reference back into the input sequence in order to pull out the specific token it is interested in. This would greatly reduce the importance of the bottleneck and it’ll be much easier to deal with very long sequences.</p><p>The basic idea is that:</p><ol><li>While encoding, we’re going to have each step of the encoder RNN produce a little piece of information that describes what is present at that time step. This piece of information will not be semantically meaningful to us, it will just be a little vector of activations that doesn’t mean anything in isolation. It will be called “key” and is going to be learned as part of the learning process.</li><li>While decoding, we’re going to have each step of the decoder RNN output a little vector of the same length that we call “query”. Intuitively, it represents the type of information that we need at this time step.</li><li>We compare the query vector to each of the keys to find the one that is the most similar and that will tell us which time step in the input is the most relevant for this time step in the decoding process. Then, we will send that information to the decoder.</li></ol><p>Some crude intuition for what this might do is that one key might encode some notion of what is going on there in the sentence, like “this word is the subject of the sentence”; if the query encodes some notion like “I need to know the subject of the sentence”, then the aforementioned key will get selected because it is the most similar to the query. We then take the corresponding time step, take its hidden state and feed it into the decoder.</p><p>Critically, we don’t have to specify any of these things manually. This whole network will still be trained end-to-end and the actual content of the keys and queries will be determined by the neural network — just like the filters in a convolutional net have some kind of intuitive meaning but are not specified by hand.</p><p>In practice, I’m going to use the letter h to denote the hidden states for the encoder. I’m going to use the letter s to denote the hidden states for the decoder. For the key, I’m going to use the letter k; there’s a separate key at each time step and the key is some function that we apply to the hidden state of the RNN. It could be for example just a linear layer followed by a non-linearity and very often in practice the function k is just a linear transformation. For the query, I’ll use the letter q to denote it, with the subscript l instead of t. For the query, I’ll use the letter q to denote it, with the subscript l instead of t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*NHtQ0ER8WwqfFgVh-yU6iw.png" /></figure><p>The attention dot product “e” is a score that denotes how similar a key is to a query. It will be given by the dot product between kt and ql and we want to pull out the hidden state ht for the time step t for which the dot product is largest.</p><p>To do so, we’re going to create a vector alpha(l) — obtained with a softmax of the attention dot products:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*QJdgC5GZ7o0YewFmhyMrYQ.png" /></figure><p>The larger the attention dot product, the closer this softmax becomes to a arg max. Then, if we want to send the key that roughly corresponds to the largest dot product, we’re going to use alpha in a weighted sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*Iad6xmvCy1g4oK0CmaFJ3A.png" /></figure><p>Intuitively, these alphas will be small numbers for all time steps t except for the one that has the largest dot product; this weighted sum will therefore be dominated by the activation corresponding to the arg max of the dot product.</p><p>The intuition is we’re trying to pull out the encoder RNN state for the time step t corresponding to the largest dot product between the key and the query. The reason we call this attention is that the network is trying to pay attention to the most relevant part of the input. To summarize, for a specific query qt:</p><ol><li>The keys are learned from the hidden states of the encoder, “h”, for example with a linear layer</li><li>The attention scores “e” are produced by dotting the keys with that query</li><li>We apply a softmax to all the dot products “e” and we call the results “alphas”</li><li>The largest alpha gets sent to the decoder</li></ol><p>What does it mean to send alpha to the decoder? Alphas can be used in different ways by the decoder.</p><ul><li>Give it to the function that produces the output, so that the output becomes a function of both decoder state and the encoder state corresponding to the highest attention score</li><li>Give it to the next RNN layer, if you’re using a multi-layer or stacked RNN</li><li>Give it to the next decoder step, so that the attention vector serves as an additional input along with, for example, a new word</li></ul><p><strong>Attention variants</strong></p><ul><li>One simple choice is to use k and q to be identity functions. In this case the key at timestep t is just ht and the query at timestep t is just sl. When you’re decoding, your attention score is the dot product between the input hidden state and the decoder hidden state. It’s very easy to implement, but it can have somewhat limited expressivity</li><li>Another really simple choice is to use a linear multiplicative attention where key and query are just linear functions of the hidden state. This is very reasonable, because the RNN hidden state is already formed by applying a non-linear function. Therefore, this doesn’t diminish our representational capacity very much</li><li>The last variant is a little more complex. It still has keys and queries, but at the end, when you construct your attention vector, you don’t construct a weighted combination of the encoder hidden states, but instead you construct a weighted combination of those hidden states transformed by some learned function v. V here stands for “value” and the interpretation is that during encoding you produce key-value pairs, whereas during decoding you find the time step of the largest product between k and q and you take its value. This can give a bit of added flexibility.</li></ul><p><strong>Summary</strong></p><ul><li>Every encoder step t produces a key kt</li><li>Every decoder step l produces a query ql</li><li>The decoder gets sent the encoder activations ht that correspond to the largest value of the product kt and ql</li><li>Attention is very powerful, because all decoder steps end up being connected to all encoder steps</li><li>Gradients are better behaved, because the number of jacobians that get multiplied together along the attention route is O(1). This becomes very important for very long sequences</li></ul><h4><a href="https://www.youtube.com/watch?v=VDnEnlYzHOU&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=36">Transformers</a></h4><p>Previously, I have talked about how we can build sequence to sequence models and improve their ability to handle long-range dependencies by using an attentional mechanism.</p><p>Here, we’re going to talk about another class of models for processing sequences that does not use recurrent connections, but instead relies entirely on attention. We’ll build towards a class of models called transformers.</p><p>The basic question is: can we get away with using attentional connections without any explicit recurrence? In principle, attention can grab any information you want from the input string and our RNN can be transformed into a purely attention-based model. But with a few caveats:</p><p><strong>If we do this naively using the basic attention mechanism, we can access the hidden states of the encoder, but not previous states of the decoder.</strong></p><p>To fix this issue, we use self-attention. We’re going to take all of the time steps of our sequence and we’ll encode each time step. This is like a feed-forward model. H1 is some function of x1; h2 is some function of x2; h3 is some function of x3. The weights are shared at all time steps because the function is the same in each case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*ZKrtMuWsJxWyuUtWydDq2g.png" /></figure><p>Then, we’re going to produce a value for each time step, where vt is some linear function of ht:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*1lEQLDKQsOW9cBDTU-gxnQ.png" /></figure><p>We are also going to output a key, where the key is some linear function of ht:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*9WNvXy1C8inAn_Gfd9cxwQ.png" /></figure><p>And then, every timestep is also going to output a query; it’s as if we had encoder and decoder together. So far, we’ve got a key, a value and a query and all of them are linear functions of ht.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*5ODt_hu7GiQmKyJ6gq7-vQ.png" /></figure><p>Then, we’ll do exactly what we did with attention before, except that now there’s no distinction between an encoder and decoder. Essentially, every step can index into every other step including itself.</p><ol><li>We’ll compute dot products between every qt and every kt and those will give us our attention scores</li><li>We’ll pass each of them through a softmax and we’ll get alpha values</li><li>Then, we take the values at every step, we weight them by the alphas and that gives us the attention</li></ol><p>This self-attention mechanism has produced an attention vector at every time step. You can think of this as a layer that integrates information across the time steps. We could repeat this process more and more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*ebPJU2-jRlTaSjyt7i1tSA.png" /></figure><p>The actual process of turning this into a viable model requires a number of additional steps. The basic concept of self-attention can be used to develop a powerful type of sequence model called a transformer, but to make this actually work we need to develop a few additional components and address some fundamental limitations of self-attention.</p><p>Here are the things we need to take care of:</p><ul><li><strong>Positional encoding </strong>addresses an issue with self-attention which is that self-attention does not have any notion of proximity and time. All those x’s were processed entirely in parallel, without any regard for their order. If we had switched their order, the self-attentional layer would produce exactly the same answer. That can be a big problem when dealing with data like natural language, where the order of the words actually matters</li><li><strong>Multi-headed attention </strong>allows querying multiple positions at each layer; at each layer we don’t just have one value in query and key, but we can have multiple — so that we can do more complex operations. Crudely, you can think of a (key, value, query) tuple as a filter in a CNN; in practice, you would never build a CNN with just one filter per layer and in the same way you don’t want to build a pure self-attention model with just one attention head per layer</li><li><strong>Adding nonlinearities</strong>, because the model that we have discussed so far is entirely linear.</li><li><strong>Masked decoding</strong> prevents attention lookups into the future. Right now, the attention mechanism doesn’t distinguish between past and future. That can be a very bad thing when you’re trying to use self-attention for a language model to decode</li></ul><h3>From self-attention to transformers</h3><p><strong>Positional encoding</strong></p><p>What we see when we see some sentence involves both the words in that sentence and the order in which those words occur. If for example we have the sentence “he hit me with a pie”, what naive self-attention sees is just a bag of words. If you were to permute the words, you would get exactly the same attention vectors — whereas a recurrent model looks at the words one at a time and it remembers which words it saw before. In general, the position of words in a sentence carries important information and we would very much like to preserve that information when using our self-attention model.</p><p>To solve this, we are going to add some information to the representation at the beginning that indicates where it is in the sequence. Positional encoding just means that this first ht is going to be some function of xt as well as t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*uoRUzkvYItXzMaystgzkXQ.png" /></figure><p>That is going to preserve the order of the tokens in the sequence and allow self-attention to make use of that. Simply appending t to the input x would not be ideal, because absolute position is less important than relative position. If I give you two sentences (“I walk my dog every day” and “every single day I walk my dog”), the important piece of information is the index of the word dog relative to the word walk, not the index of the word dog by itself.</p><p>We could come up with a positional encoding that pays more attention to relative positions than it does to absolute positions. We want to represent position in a way that tokens with similar relative position have similar positional encoding. For example, instead of appending the actual time step, we could append frequencies of the time step. The positional encoding could be a vector of the same length as the embedding of xt; every entry in that vector is a sine or a cosine applied to the time step t divided by some frequency:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*tST5pM4zzpJNzXEOiAgqjw.png" /></figure><p>The earlier entries have very high frequencies, because it’s t divided by some small number; at the end of the vector they have very low frequencies, because it’s t divided by a big number, like 10.000. If you were to draw a picture of these positional encodings, this is what they’d look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*HYezuON1FxpJ5lXagK_63A.png" /></figure><p>Every row here is a different dimension of this positional encoding vector and every point horizontally is the index in the sequence. This frequency domain encoding is very good for getting relative positions.</p><p>However, we could have more sophisticated positional encoding. For example, we could learn it. We could learn the entire matrix I showed above, making the entries in the matrix learnable parameters of our model</p><p>At every position we have an x and that’s different for every input sequence; at every position we also have a p and that’s the same for every sequence, but it’s learned — so it’s a different p at every time step, but p1 for one sequence is exactly the same as p1 for a different sequence, so it’s just a learned constant. This has the advantage of being more flexible and perhaps more optimal in some sense than the sine-cosine encoding, because we do end up learning the positional encodings that work best for our sequence model. The downside is that it’s a little bit more complex and you need to manually pick the maximum sequence length</p><p><strong>How do we incorporate these positional encodings into our self-attention model?</strong></p><p>At each time step, we’re going to have our input xt and our positional encoding pt. Transformers usually embed the input first and they add the positional encoding to that embedding. So the encoding is just the embedding of xt plus the positional encoding pt. That’s an arbitrary choice, you can combine them in any other way.</p><p><strong>Multi-head attention</strong></p><p>Since we’re relying entirely on attention now, it might be desirable to allow the self-attention mechanism to incorporate information from more than one time step. For example, if at position two you need verb and subject of the sentence in order to combine them, it would be cool to have an attention mechanisms that provides the subject and another one that provides the verb.</p><p>The way that you can do this is you can have multiple keys, queries and values at every step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*lF6kYzwB-d8-xQH9-bC2Nw.png" /></figure><p>The different color outlines represent different heads. Each of these heads produces an attention score and the weights are computed independently for each head. At the end, a full attention vector is formed by stacking the three heads. And maybe one of those heads pulls out a subject, one pull out an adjective, one pulls out a verb and so on.</p><p>It’s a really good idea to build self-attention with multiple heads per self-attention layer — oftentimes, something around eight heads seems to work pretty well for big models</p><p><strong>Adding nonlinearities</strong></p><p>So far, self-attention is entirely linear in the values, because our keys, our queries and our values are linear functions of ht. Each self-attention layer has a different set of weights. Then, our alphas are calculated by applying a softmax, which is a non-linear operation, but the actual attention is obtained with a linear combination of the values weighted by those softmax scores. So, the attention is linear in the v’s and the v’s are linear in the h’s. This means that every self-attention layer is a linear transformation of the previous layer with nonlinear weights and this is not very expressive.</p><p>One very simple way to add nonlinearities is to simply alternate self-attention with some kind of non-linear layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*-UaerpEykRcsINx2l_CM8w.png" /></figure><p>This position-wise nonlinear function processes the information, whereas the self-attention layer is the memory fetch.</p><p><strong>Masked decoding</strong></p><p>The trouble with self-attention is that it doesn’t distinguish between past and future; instead, you would like to have the first time step only use information from the first step to generate the output, then you want to use that output as an input to the second step, which can then process that information (including information from the first step) and then produce the output of the second step, and so on.</p><p>The problem is that we have a circular dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*xFDTCrEQg5pIMomD5JV7tw.png" /></figure><p>While encoding, self-attention at step 1 can look at the value at steps 2 and 3, which is based on the inputs at steps 2 and 3. At test time, the inputs at steps 2 and 3 will be based on the output at step 1, which requires knowing the input at steps 2 and 3.</p><p>There’s a very simple fix that we can use to remove this problem, which is called masked attention. You have to allow self-attention into the past, but not into the future:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*djjMplwLs3egFg7k67bioA.png" /></figure><p>Mathematically, to compute the attention scores, you do the same as before only if the key comes before the query, otherwise you set the attention score to negative infinity. This way, when you put it into the softmax, e to the negative infinity is zero and future time steps will always have a weight of zero and never be used. In code, dealing with infinities is annoying, so you directly set the exponential to 0.</p><p><strong>Summary</strong></p><p>We can implement a practical sequence model, based entirely on self-attention and if you incorporate the four modifications that we described, the sequence model will work.</p><ul><li>You have to alternate self-attention layers with non-linear position-wise feed-forward networks to get non-linear transformations</li><li>You have to use positional encoding on the input or input embedding to make the model aware of the relative position of the tokens relative to each other in the sequence</li><li>You have to use multi-headed attention so you can incorporate information from multiple different time steps at each self-attention layer</li><li>If you want to use the model to decode, you have to use masked attention to prevent peaks into the future.</li></ul><p><strong>Transformers</strong></p><p>We’re now going to combine the pieces that we’ve learned about so far to go through the classic transformer model.</p><p>The model designs that use successive self-attention and position-wise non-linearity to process sequences are generally referred to as transformers, because they transform one sequence and another at each layer using these self-potential mechanisms.</p><p>A sequence to sequence RNN model has an RNN encoder and an RNN decoder. These can in general have multiple layers. To make this into a transformer we will replace the encoder and the decoder with successive self-attention layers, alternating with position-wise non-linear transformations.</p><p><strong>The encoder </strong>is going to get a sequence of x’s, with corresponding positional encodings p1, p2 and p3. At every position we will encode these, then we’ll pass them into a self-attention layer. Then, we will take the output of this multi-headed potential and pass it into a position wise nonlinear network. This is repeated n times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*oDItKXKFbe8hXeq3LJFTPA.png" /></figure><p><strong>In the decoder </strong>we’re also going to have a position-wise embedding of the output steps and their corresponding positional encodings. We’ll use masked attention, which means that earlier time steps don’t get to look into later ones. Then, we’ll have a position-wise non-linear network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*rsJfa510WIJxC-e07amOzA.png" /></figure><p>Then, we’ll have cross attention, which uses all of those hidden vectors produced by the encoder. This is very much like the classic attention that we described in the previous lecture, so instead of self-attention which looks at other time steps in that same sequence, cross attention is going to look at the time steps in the encoder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*Nz4af-4SanJ5tHCj0Irl8A.png" /></figure><p>After cross attention, we have another position-wise nonlinear network. This means that every decoder layer has two attention steps: it has a masked self-attention, a non-linear function, cross attention, another non-linear function and then that goes into the next block. These blocks are also repeated n times, so the decoder blocks have twice as much stuff going on as the encoder blocks</p><p>At the very end, after n blocks like these, we apply a softmax at every position and read out the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*BvJgnNXEOipK3S98JlKPag.png" /></figure><p>Let’s look more closely at the cross-attention mechanism, which is a little subtle.</p><p>We’re going to use ht with superscript l to denote the hidden states of layer l in the encoder and sl superscript l to denote the hidden states l in the decoder . These states are produced by the position-wise nonlinear network. In cross-attention, we have:</p><ul><li>A query, which is obtained by applying matrix Wql to the output of position-wise nonlinear network at decoder layer l, step t</li><li>A key, which is obtained by applying matrix Wkl to the output of position-wise nonlinear network at encoder layer l, step t</li><li>A value, which is obtained by applying matrix Wvl to the output of position-wise nonlinear network at encoder layer l, step t</li></ul><p>Then, we compute an attention score between every t and l, we apply the softmax and then we compute our cross-attention.</p><p>In reality, cross attention is also multi-headed. Before presenting the real transformer model, there’s one more little detail: layer normalization.</p><p>Layer normalization does not have anything to do with attention models, but it turns out to be important for the transformer because it’s difficult to use regular batch normalization with it. The main idea is that batch normalization is very helpful, but it’s hard to use it with sequence models for a few reasons:</p><ul><li>Sequences are different in length, which makes normalizing across the batch kind of hard</li><li>Sequences can be very long, so we sometimes have very small batches</li></ul><p>A simple solution that we can use is to replace batch normalization with something called layer normalization, which is like batch normalization but across different activations in a layer rather than across different samples in a batch. In standard batch norm, at every layer, you have a bunch of activation vectors, one from every input; batch norm computes a mean and a standard deviation over all of the points in that batch. Then, when you transform them with batch normalization, everything is per element and for every element you subtract the corresponding element of the mean, divide by the corresponding element of the standard deviation, multiply by the corresponding element of gamma (which is the learned scale) and add the corresponding element of beta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*SQ2Et9EUY83dlYS3s9LOwQ.png" /></figure><p>Layer norm is going to be a more traditional layer, it just uses information within a single data point and instead of computing the mean over different vectors in the batch, it computes a single number by averaging together the activations for every dimension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*vb7Hy97gKqFEfC3BUsXRBA.png" /></figure><p><strong>Putting it all together</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*3mg3JmhG8TtX0OLdfjT1yg.png" /></figure><p>This image is taken from the paper that introduced the transformer, called “Attention is all you need”. What this paper proposed is to use successive self-attention and position-wise non-linear functions to implement a sequence to sequence model — which they apply to machine translation.</p><p><strong>Encoder</strong></p><ul><li>We start off by taking our input sequence, separately embedding every token in that input sequence and adding the corresponding positional encoding to that embedding</li><li>Then we have our first multi-headed self-attention layer</li><li>You concatenate the attention from all the heads to get alpha at every position</li><li>Then you have this thing called “Add &amp; Norm”, which is a residual connection followed by a layer norm. The reason is that they want every layer to be a modification, with the benefit of well-behaved gradients that you get from residual connections</li><li>Then you have a position-wise non-linear function. In particular, it consists of a linear layer, then a ReLU and then another linear layer.</li><li>Then there is another “Add &amp; Norm”</li></ul><p>They have n of these blocks; each block is multi-headed self-attention, add &amp; norm, position wise non-linearity, add &amp; norm, pass it to the next block, multi headed self-attention, add &amp; norm, position wise non-linearity, add &amp; norm, pass it to the next block and so on.</p><p>That’s the encoder. Once you’ve run the encoder all the way forward, you will have computed six of these blocks. The product of the encoder is these keys and values</p><p><strong>Decoder</strong></p><ul><li>The decoder has the same kind of positional encoding business and then for each encoder block there’s a corresponding decoder block — but the decoder blocks are a little more complex. Now, the multi-head attention is masked and only looks at past time steps, because it is going to be used to generate a sequence.</li><li>Add &amp; norm</li><li>There’s a cross attention that produces queries based on the output of the self-attention. Those queries are used to look up the keys and values from the encoder.</li><li>Again, there is an add &amp; norm. This add &amp; norm will add together the results of cross attention and self-attention.</li><li>Then you have a position-wise nonlinear function, which uses the same architecture but different weights as the encoder</li><li>Then you have another add &amp; norm</li><li>Then you pass them to the next block</li><li>At the end of the last block, there’s a linear layer at every position followed by a softmax, which outputs a probability distribution over the token at that position</li></ul><p>The decoder decodes one position at a time with masked attention</p><p><strong>Why transformers?</strong></p><p>A few pros and cons of transformers:</p><ul><li>The attention computation is technically O of n squared, although this is not as big of a problem as it seems because most of the computation time is not spent performing those dot products, but on all the other parts of the network. In practice, in terms of computational cost, oftentimes transformers are actually a lot cheaper than RNNs</li><li>They are somewhat more complex to implement and involve a variety of seemingly weird decisions, like positional encodings which can make them a little tricky to work with. It can take a fair bit of hyperparameter tuning to get transformers to train well</li><li>They have much better long range connections: every position in the output is connected to every other output position and every other input position with a jump of length one. Computationally, implementing a transformer on parallelized hardware like GPUs makes them run much faster for our ends</li><li>In practice, you can make transformers much deeper than stacked RNNs.</li></ul><p>In general, the benefits of transformers seem to vastly outweigh the downsides and transformers work much better than RNNs and LSTMs in many practical sequence to sequence processing cases.</p><p><em>Feel free to drop me a message or:</em></p><ol><li>Connect and reach me on<strong> </strong><a href="https://www.linkedin.com/in/samuele-bolotta-841b16160/">LinkedIn </a>and <a href="https://twitter.com/SamBolotta">Twitter</a></li><li>Follow me on <a href="https://medium.com/@samuelebolotta">Medium</a></li></ol><h3>References</h3><p><a href="https://www.youtube.com/watch?v=lKRatcD9hEg&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=14">CS 182: Lecture 5</a></p><p>All images taken from Levine, CS182, 2021.</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee6a63ddb57f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic concepts in machine learning]]></title>
            <link>https://samuelebolotta.medium.com/basic-concepts-in-machine-learning-a20de41137cc?source=rss-d7523d3d796e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a20de41137cc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Samuele Bolotta]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 17:25:21 GMT</pubDate>
            <atom:updated>2022-01-02T16:21:05.142Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first of a series of articles in which I summarize the lectures from CS182 held by Professor Sergey Levine, to whom all credit goes. All images are taken from his lectures. These are <a href="https://medium.com/mlearning-ai/convolutional-networks-recurrent-neural-networks-and-transfomers-ee6a63ddb57f">the second</a>, <a href="https://medium.com/mlearning-ai/detailed-basics-of-deep-learning-part-three-b930c40cf7f8">the third</a> and <a href="https://samuelebolotta.medium.com/7a88e847f62e">the fourth articles.</a></p><p><a href="https://www.youtube.com/watch?v=aUNnGCxvAg0&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=4">Basic concepts in machine learning</a></p><p>Machine learning algorithms try to imitate the pattern between two datasets in such a way that they can use one dataset to predict the other. Specifically, supervised machine learning is useful for taking what you know as input and quickly transforming it into what you want to know. On the other hand, unsupervised learning also transforms one dataset into another, but the dataset that it transforms into is not previously known or understood. Unlike supervised learning, there is no “right answer” that you’re trying to get the model to duplicate. You just tell an unsupervised algorithm: “find patterns in this data and tell me about them.”</p><h4>Parametricism</h4><p>Parametricism is about the way the learning is stored and often, by extension, the method for learning. A parametric model is characterized by having a fixed number of parameters, whereas a nonparametric model’s number of parameters is infinite (determined by data; this lends itself to methods that generally count in one way or another, thus increasing the number of parameters based on the number of items being counted within the data). As it happens, deep learning is a class of parametric models.</p><p>1 Supervised parametric learning machines are machines with a fixed number of knobs (that’s the parametric part), wherein learning occurs by turning the knobs. Note that each knob represents the prediction’s sensitivity to different types of input data. That’s what you’re changing when you “learn”. Input data comes in, is processed based on the angle of the knobs, and is transformed into a prediction. The notion of trial and error isn’t the formal definition, but it’s a common (with exceptions) property to parametric models. When there is an arbitrary (but fixed) number of knobs to turn, some level of searching is required to find the optimal configuration. In supervised learning, there is an important distinction to learn: a feature is one column of the data in your input set. For instance, if you’re trying to predict the type of pet someone will choose, your input features might include age, home region, family income, etc. On the other hand, a label is the final choice, such as dog, fish, iguana, rock, etc. Once you’ve trained your model, you will give it sets of new input containing those features; it will return the predicted “label” (pet type) for that person.</p><p>2 Unsupervised parametric learning uses knobs to group data, adding new knobs when it finds something new to count. But in this case, it usually has several knobs for each group, each of which maps the input data’s affinity to that particular group (with exceptions and nuance — this is a high-level description).</p><p><strong>Statistical classification</strong></p><p>In statistical classification, two main approaches are called the <strong>generative</strong> approach and the <strong>discriminative</strong> approach. These compute classifiers by different approaches, differing in the degree of statistical modelling. Terminology is inconsistent, but two major types can be distinguished:</p><ul><li>Given an observable variable <em>X</em> and a target variable <em>Y</em>, a <strong>generative model</strong> is a statistical model of the joint probability distribution.</li><li>A <strong>discriminative model</strong> is a model of the conditional probability of the target <em>Y</em>, given an observation <em>x</em>, symbolically</li></ul><p>Analogously, a classifier based on a generative model is a <strong>generative classifier</strong>, while a classifier based on a discriminative model is a <strong>discriminative classifier</strong>, though this term also refers to classifiers that are not based on a model.</p><p>Although this formal generative-vs-discriminative definition is widely used and very useful, it’s somewhat of a false dichotomy which starts falling apart when you consider that it’s in fact a <strong>spectrum</strong> which you can even smoothly interpolate between, and many popular models do not neatly fall into this dichotomy. Furthermore, it assumes the supervised learning setting and is less useful for classifying unsupervised or semi-supervised methods.</p><p>A more general (but more informal) definition to complement it might be:</p><ul><li>Discriminative models learn the boundary between classes</li><li>Generative models learn the distribution of data</li></ul><p>Regardless of precise definition, the terminology is constitutional because a generative model can be used to “generate” random instances, while a discriminative model or discriminative classifier can be used to “discriminate” the value of the target variable <em>Y</em>, given an observation <em>x</em>.</p><p>A few points worth mentioning about the relationship between supervised, unsupervised, generative and discriminative models:</p><ol><li>Not all generative models are learnt using unsupervised learning. Many generative models — -from the basic like Naive Bayes to complex like a GAN or this generative up-convolutional network — are learnt in a supervised or semi-supervised fashion.</li><li>Not every unsupervised learning algorithm is a generative model. Unsupervised learning algorithms fall all across the <strong>generative-discriminative spectrum</strong>, e.g. k-nearest neighbours (kNN) is somewhere in between generative and discriminative (formally generative, informally discriminative).</li><li>Many clustering algorithms are generative models, e.g. latent Dirichlet allocation (LDA).</li><li>Not all discriminative models are learnt using supervised learning. There are discriminative models trained on unsupervised datasets, e.g. monocular depth and optical flow models.</li><li>Every supervised learning algorithm is a discriminative model. There aresome examples of supervised learning algorithms with generative models (for example, Naive Bayes).</li></ol><h4>Some probability theory</h4><p>Let’s define supervised learning a little bit more precisely. We’re going to assume that during training we are given a dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*qfVRFLT1_SXz91gJpSAsFQ.png" /><figcaption>Training set consisting of tuples; the<strong> y’s </strong>are the true labels corresponding to the <strong>x’s.</strong></figcaption></figure><p>For example, if we wanted to solve an image classification problem we would collect some pictures of dogs, cats and giraffes and then we would have humans go through each of those pictures and label them with their true label. We would use this as training data to learn how to classify new pictures. So, the goal in supervised learning is to learn this function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*-7ZV2ROHZgjnAtRzFALY0Q.png" /><figcaption>We want to learn theta (θ, the parameters) so that this function closely approximates the true label <strong>y.</strong></figcaption></figure><p>However, there are a few questions we have to answer to actually instantiate a supervised learning method. One important starting point is that <strong>predicting probabilities often makes more sense than predicting discrete labels.</strong></p><ol><li>If we’re allowed to have probabilities, we can much better express what we think is really going on; we might be able to capture the fact that a 4 is likely to be a 4, but it also has a pretty high chance of being a 9. This uncertainty might be useful for making decisions.</li><li>If we’re allowed to have probabilities, the problem is going to be smoother: intuitively we can’t change a discrete label a tiny bit, it’s kind of all or nothing. However, the problem of finding the optimal θ is made easier by the fact that we can change those probabilities by a tiny amount and see if they change in a direction that is closer to what we want.</li></ol><p>So, given a training set instead of learning a function that maps x to y, now we’re going to learn a function that maps x to a distribution over y:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*T9kvT0cq1-rhVWHUge1NVg.png" /></figure><p>Now, we’re going to be taking our input, for example the picture of a dog, and outputting a distribution over its corresponding label y.</p><p><strong>Refresher on conditional probabilities</strong></p><p>A random variable is defined as a function that assigns values to each of an experiment’s outcomes. We have:</p><ul><li>The input x</li><li>The output y</li></ul><p>We can write the joint probability of x and y as p(x,y). <strong>Joint probability</strong> is a statistical measure that calculates the likelihood of two events occurring together and at the same point in time. In other words, joint probability is the probability of event Y occurring at the same time that event X occurs.</p><p>Joint probability should not be confused with conditional probability, which is the probability that one event will happen <em>given that</em> another action or event happens.</p><p>In fact, joint probability p(x, y) can be decomposed using the chain rule of probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*UG5zW15m33T6zhXiYWykGg.png" /></figure><p>The <strong>chain rule</strong> of probability, not to be confused with the chain rule of calculus, allows the calculation of any member of the joint distribution of a set of random variables using only conditional probabilities.</p><p>In fact, you could also rewrite the above equation by dividing both sides by p(x) to get the definition of conditional probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*IOQFg8sQFjkyDetEdF4OJQ.png" /></figure><p>So if you know p(x) and p(x, y), you could recover your conditional probability.</p><p><strong>Supervised learning</strong></p><p>We’ll focus on learning p(y|x). In order to do this, we will use the “machine learning method”, which is a three-step program. This way of decomposing learning problems is closely related to Marr’s levels of analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*S30PEAWARzvcJfWZ5ozr7w.png" /></figure><p>I’ll now list the three steps of the machine learning method with their corresponding Marr’s level.</p><p><strong>1 Define your loss function:</strong> how will you measure how good a particular model is? This question relates to the computational level of the pyramid.</p><p><strong>2 Define your model class:</strong> how will you represent your program? This question relates to the middle of the pyramid: the algorithmic level. In other words, what is the structure that is going to carry on our optimization?</p><p><strong>3 Pick an optimizer: </strong>how will you search through the model class to find the model that minimizes the loss function? This question relates to the implementation level of the pyramid.</p><p>The reason that we draw these distinctions is that when we have these different levels of analysis it can help us compartmentalize our thinking and help us to build abstractions so that we can solve the problems in isolation.</p><p>We’ll start from the middle of the pyramid, thinking about our representation of the problem.</p><h4>1 How do we represent p(y|x)?</h4><p>For example, say that we have this input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/67/1*4FgvoAfZ1AEz0DWPFx5OQw.png" /></figure><p>And our goal is to map it to the probability that it is an integer between 0 and 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*PIZIPdlj5Ky_ADcVurmD5Q.png" /></figure><p><strong>A valid probability distribution consists of positive numbers that sum up to 1.</strong></p><p>Let’s look at a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*RpHLxBRCZGw8Laj3dcu5oQ.png" /></figure><p>In the above image, we say that <em>the probability that y is a dog (conditioned on x) is constructed as “x” transpose “θ dog”; the probability that y is a cat (conditioned on x) is constructed as “x” transpose “θ cat”; the parameters are defined by the concatenation of “θ dog” and “θ cat”.</em></p><p>However, this program does not output a valid probability distribution: in general p(y = dog) + p(y = cat) will not sum to 1 unless the θs are chosen very very carefully. Therefore, we’re violating our constraint.</p><p>Let’s address this problem: instead of having “x” transpose “θ dog” be equal to p(dog), we’re going to define it as equal to some function f dog(x); we thus have some intermediate function inside of our program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*gCnjiHtm4fcmSJwFKaZjvg.png" /><figcaption>Take outputs from f dog and f cat, run them through a softmax</figcaption></figure><p>The softmax is going to take in f dog and f cat and it’s going to force those numbers to all be positive and sum up to 1. In theory, it could be any bijective (one-to-one and onto) function, because you want a function that uses the inputs you give.</p><p>A function f from the domain to the range is bijective when (1) No element of the range is the image of more than one element in the domain (2) All elements in the range are used.</p><p>But apart from this condition, why is it that we can use lots of different functions that make those numbers positive and sum to 1?</p><p><strong>The choice of your function in machine learning is not meant to produce the right answer; you produce the right answer by choosing the right parameters. </strong>The function just needs to be general enough so that there exists a choice of θ that represents the right answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*4MvduiPNgQHeXtlBk-Hx3Q.png" /><figcaption>It takes all of its inputs. it exponentiates them and then it divides by their sum; in this example, we see the dog output.</figcaption></figure><p>In general, you might have n labels (not just a dog) and p (y|x) might be a vector with n elements, one element for every possible label:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Jdz5g8YC1_4RU22_PmVl8A.png" /></figure><p>You have some function f θ(x), which is a vector-valued function with n outputs that might not be positive and might not sum to one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*E3VgC6eUsOYrEUmNJ7nDmQ.png" /></figure><p>So the softmax takes care of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*TSuxZuU3SCZBM5BDwdsBJg.png" /></figure><p>Its sole job is to make the numbers positive and to make them sum to 1.</p><h4>2 How do we select our parameters θ?</h4><p>So far, we have our picture of a computer program that maps our inputs to our outputs; we’ve decided that our outputs should be probabilities and we’re going to use the softmax to produce those probabilities.</p><p>To start thinking about defining our loss function, let’s start with a with a more basic question: how is our dataset generated? If our dataset consists of pictures and their corresponding labels, the actual process that gave rise to those pictures was probably pretty complex, involving photons and people making decisions about what to photograph and so on.</p><p>When it comes to trying to model it, we can come up with a very crude model: we’re going to represent that as a random process; there exists some p(x) distribution over photographs and humans randomly sampling from p(x) when they take photographs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*3stbtoEzZSHVHyHy_L9fOg.png" /></figure><p>And the label “dog” is sampled from some distribution over labels, which is not completely random and depends on the photograph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*flnhzTxZh_PSG4Gc9PZ1dg.png" /></figure><p>By the chain rule of probability, we can compose these two and generate samples (x, y) from their joint distribution p(x,y):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*Qx-NUAic8umtoCkV4MI97Q.png" /></figure><p>Our dataset is sampled from this distribution and consists of many tuples (x, y), which are generated according to the distribution p (x, y).</p><p>To make this a little more formal, what is the probability of seeing a particular training set? We need to make an assumption about how different data points relate to one another. <strong>The assumption we’re going to make is that we are dealing with independent and identically distributed data.</strong></p><ul><li>Independent means that every (x, y) tuple is independent of every other (x, y) tuple, meaning that if you observe a cat for x1, this doesn’t change how likely you are to see a cat or a dog for x2</li><li>Identically distributed means that every (xi, yi) comes from the same distribution.</li></ul><p>If we have this assumption, we know we can write the probability p(D) of seeing a particular training set as a product over all i of p(xi, yi).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*Msg6M1JFoe7ymSxIFt8tcA.png" /></figure><p>Why? Because “independent” means that the joint p(D) is formed as a product of the marginals p(xi) and p(yi).</p><p>In other words, if you flip a coin twice, the probability of seeing heads on the second flip doesn’t depend on the probability of seeing heads on the first flip. So if you want to know the probability of getting heads twice in a row you just multiply the probability of heads on the first attempt by the probability of heads on the second attempt. And because it’s identically distributed that’s the same as just taking the probability of heads and squaring it.</p><p>We have a probability associated with our dataset. Since we’re learning p(y|x), we can decompose the above formula using the chain rule of probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*7_kp2Q_nP_aG3zdIiLP87g.png" /></figure><p>Now we have a probability associated with our dataset expressed as a product over all of our data points of p(xi) by p(yi|xi). What we are learning is pθ of (y|x). It is important to notice that this is the learned function, which depends on our parameters: this is a model of the true p(y|x). Of course, it’s not the real process by which labels get associated with images, it’s a model of that process. And we’re going to try to get that model to be as accurate as possible.</p><p><strong>A good model should make the data look probable: one θ is better than another θ if the corresponding p θ(y|x) makes the entire data set look more probable and increases p(D)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*dcYw_SuWo_3TQ4gnfFPBbQ.png" /></figure><p>However, the issue here is that we express this probability p(D) as a product of a bunch of other probabilities that are between 0 and 1: if you multiply millions of numbers that are between 0 and 1, you’re going to get something very very close to zero. Essentially, this objective is numerically challenging.</p><p>What we can do instead is we can take the logarithm of p(D). When you take the logarithm of a product, you get a sum of logarithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*ESjvTeovPXId-SWVsWXTAw.png" /></figure><p>But since p(xi) doesn’t depend on θ, we can just treat is a constant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*0MC--4Qx7RFo5YDP_4PzoA.png" /></figure><p><strong>We can equivalently say that our objective is a sum over all of our data points of the logarithm of p θ(yi|xi) plus some other stuff that does not depend on θ.</strong></p><p>We can formulate the problem of learning θ as our attempt to find the θ that maximizes the log p(D):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*hlTcsUEx5XcyFKOVJfqfPw.png" /><figcaption>This is called maximum likelihood estimation (MLE), because this log probability is the likelihood and we are choosing θ to maximize the likelihood</figcaption></figure><p>Often times, we will see this written as a minimization (this is just a convention):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*0epNMapoWMF7l9BENm7c8A.png" /><figcaption>This is also called the cross-entropy</figcaption></figure><p>We still want to maximize the log p(D), which is the same as saying that we want to minimize the negative log probability. So, this is our loss function, which quantifies how bad θ is.</p><p>There are other ways to quantify how bad θ is. For example, you could have a zero-one loss: it just says that you get a a loss of one if you got the wrong answer and you get a loss of zero if you got a right answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*Yo7vjjIyZxLLJnDzn9qU1Q.png" /></figure><p>If you’re doing a continuous regression problem, you might have a mean squared error loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*E3whlQ2tzgujHGZVDUPd2g.png" /></figure><p>If you’re predicting a continuous value number, you might want to be as close to that number as possible.</p><h4>3 How do we pick our optimizer?</h4><p>Now we have to figure out how to find the setting of θ that minimizes our loss function. One of the things that it helps to think about when imagining optimization algorithms is what’s called the loss landscape. You can think of the loss landscape as a plot of the loss function. L(θ) denotes the loss function.</p><p>Let’s say that θ is 2D: you could imagine a plot where the horizontal axes are θ1 and θ2. The vertical axis represents the function L(θ). Just from glancing at it you know where the best θ is: it’s right there at the bottom of that bowl.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*v-IC3sUjQO4Tf8WQaEqKVg.png" /></figure><p>We want to find the direction in which the loss function decreases and move our θ in that direction. A very general sketch of an algorithm would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*GJ9pp3EtdMRQl3C5SByYAw.png" /></figure><p>Find the direction v such that L(θ) decreases and then pick the new θ to be the old θ plus some rate α times v. α is some small constant that is also called the learning rate. Then, we repeat this process enough times and we’ll hopefully settle down at the minimum.</p><p>Interestingly, the direction of steepest descent is not actually always the best choice, but what all these methods will have in common is that they will all move in the direction where L(θ) decreases at least locally.</p><p>Mathematically speaking, we represent a direction as a vector with n entries that points in the direction where L(θ) will decrease. It is easier to visualize in 1D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*2DxIwHCCq5a6qkp7U_gnEQ.png" /></figure><p>If I’m located at a certain point, the slope of the function at that point tells me in which direction it decreases. If the slope is negative, the function decreases to the right; if the slope is positive, the function decreases to the left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*0dSGFmrO42xfjdiWlGb25A.png" /></figure><p>Just from looking at the slope, we can therefore tell which way to go to decrease the function and the same intuition applies in higher dimensions. In general, for each dimension we should go in the direction opposite to the slope along that dimension.</p><p>What is a slope? A slope is just a derivative. All we do is we just set the direction for every dimension to be the negative of the partial derivative of our function L with respect to that dimension of θ.</p><p>In 2D, V1 is then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*Hk-5IVTNhZB55eUNWT6FuQ.png" /></figure><p>V2 is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*UvqID4A9819wIzBcV0Z_lQ.png" /></figure><p>These are not the only directions in which θ decreases: in fact, there’s an entire half space of vectors that encodes directions in which θ decreases. So, these partial derivatives give you the direction of steepest decrease, but if you go a little to the left or to the right, θ will still decrease. Of course, if you go in the opposite direction, θ will increase. As long as you have a positive dot product with v, you will go in a direction where L(θ) decreases. This is to say that it’s not a unique degree structure: it’s the steepest one, which doesn’t necessarily mean it’s the best one.</p><p>A very useful concept for doing this is something called the gradient, whose symbol is ∇. The ∇ is a vector; every dimension of that vector is the partial derivative of our function with respect to the corresponding dimension of θ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*8e5g7hNVCCIOcSrWWafNkQ.png" /><figcaption>The gradient is formed by taking partial derivatives and stacking them up in a vector</figcaption></figure><p>Here’s a sketch of the gradient descent algorithm:</p><ol><li>Compute the gradient step</li><li>Set θ to be:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*TirYe75wrUm3skCdrMfZ3A.png" /></figure><p>We have therefore selected our optimizer.</p><h4><a href="https://www.youtube.com/watch?v=PBYWWM9We-0&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=8">Empirical risk minimization</a></h4><p>Some people, when doing supervised learning, say they are minimizing empirical risk.</p><p>Let’s think back to the zero-one loss, which assigns 0 to loss for a correct classification and 1 for an incorrect classification</p><p>You can think of risk as the probability that you will get it wrong. Think back to our generative process: someone takes a picture. This is a randomly sampled picture from the distribution of pictures. It has a label sampled from the true distribution of labels. Given that picture, what’s the probability we’ll get it right or wrong?</p><p>The probability you get it wrong is just the expected value of the zero-one loss. Generalizing to other losses, the risk is the expected value of that loss.</p><p>If we’re using the negative log likelihood, we could say the risk is the expected value under the true distribution over x and the true distribution over y of the loss that we’ll get for that x and y and our learned θ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*9oKE2vg20RQtQ5btpRhdEA.png" /></figure><p>The risk is what we want to minimize. However, we can’t calculate true risk, because we can’t get infinite samples. Instead, we’re given a dataset D. So what we can calculate is the empirical risk, which is a sample-based estimate of the true risk. You get this sample-based estimate by averaging your loss over all of your samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*IlES_ppde_bb98_t1on37w.png" /><figcaption>The empirical risk approximates the true risk</figcaption></figure><p>Is the empirical risk a good approximation of the true risk? There are two situations where we might have trouble.</p><ol><li><strong>Overfitting </strong>happens when the empirical risk is low, but the true risk is high. This means that your average loss on your training set is low, but the true expected value of your loss is not low.</li></ol><p>Say that I’m trying to fit this line and the dots correspond to my training data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*clKoF0NZZcvLDHRBBHPjOw.png" /><figcaption>Overfitting</figcaption></figure><p>A high degree polynomial would perfectly fit the dots and result in very low empirical risk, as it passes right through the points. However, its true risk is going to be quite high. This can happen (1) if the dataset is too small or (2) if the model is too powerful and has too many parameters</p><p>2. Underfitting happens when the empirical risk does match the true risk, but they are both high.</p><p>For example, the true function here is some kind of curve, but we chose to fit a line to it and the line is not a powerful enough fit to that curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*AEVIGgCRSAiWvqcv2IJ2tw.png" /><figcaption>Underfitting</figcaption></figure><p>This can happen (1) if the model has too few parameters or (2) if your optimizer is not configured well.</p><p>Let’s try to mathematically understand what overfitting and underfitting are. In order to do so, we’ll focus on regression — this means that you are predicting a continuous variable or a continuous distribution based on your input.</p><p>Regression is basically curve fitting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*xis8XN1bUbsABMHrz1tmKQ.png" /></figure><p>You have some continuous or discrete inputs, you have a continuous output and you want to predict that output. For example, you’re predicting how big the dog is, how much it weighs, how expensive the house is, and so on.</p><p>If we want to adopt a probabilistic approach, in order to do regression we need a probability distribution over a continuous value to output y. There are many probability distributions that we could use to represent real numbers, but a very simple choice is the normal or gaussian distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*RBtXIjb1Dss_gStcPdg9MQ.png" /></figure><p><strong>The normal distribution is defined by two parameters: a mean and a variance.</strong> But of course, we want to solve a prediction problem — we want to predict a distribution over y given x. In our case, we are going to have a conditional gaussian distribution; in other words, the mean and perhaps the variance of this gaussian distribution are themselves functions of x. The log probability of a normal distribution can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*2IuqYxrARU3FuoprC2ZMkw.png" /></figure><p>It looks like a big equation, but it really consists of three simple things:</p><ul><li><strong>The first term</strong> is just the difference between f θ(x) and y, but under a particular norm defined by sigma. <em>It’s asking how close the mean f θ(x) to the true label y.</em></li><li><strong>The second term</strong> (negative 1/2 log of the determinant of sigma) tries to get the variance to be lower. What it’s saying is: <em>if you can fit the the true y’s accurately, try to use a lower variance.</em></li><li><strong>The third term</strong> is a <em>constant </em>that does not depend on x or y</li></ul><p>If we don’t bother learning sigma and fix it to be the identity matrix, then the normal distribution reduces to the square of the difference between f θ(x) and y, plus some constant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*y6gLCgFulPhXGbp9xdSWkA.png" /></figure><p>Often times, when we talk about regression, the particular distribution that we choose is a normal distribution, but we choose sigma to be the identity and then the log of this normal distribution just corresponds to the square of the difference between f θ(x) and y.</p><p>After this simplification, it is the same as the mean squared error (MSE) loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*KSiq1IMb2zsLyEHATI81pA.png" /></figure><p>The MSE loss is also the log probability for a normal distribution with the covariance sigma set to identity. If you have a linear model, then minimizing the MSE loss just corresponds to conventional linear regression. The analysis in the present article will therefore be for MSE, but keep in mind that it could be extended to other losses.</p><p>Now, let’s try to understand overfitting and underfitting more formally. The question here is: <strong>how does the error change for different training sets?</strong></p><p>This question is justified by the fact that intuitively we’d like to do our analysis in such a way that we understand the overfitting or underfitting tendencies of our algorithm somewhat independently of which particular dataset it’s trained on — because with a given dataset we could get lucky or unlucky. We want to know, on average, for datasets sampled from a particular data distribution, will our algorithm produce the right answer or not?</p><p>Here’s why this question could be important. Let’s say that this black curve is our true function and these blue dots represent a particular training set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*LcB3-mmJeOfJt8Jlx1E8Yg.png" /></figure><p>When I fit my model to that training set, I get the orange curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*euCx6BOXfBJk4AVnmrWRlQ.png" /></figure><p>Here, the empirical risk low is because the orange curve goes straight through the blue circles. However, the true risk is high, because the orange curve is very different from the black curve. This is overfitting.</p><p>Now imagine that I have a different set of blue dots. I have the same true function, the learning problem didn’t change, the distribution over x and y didn’t change either. The only difference is that I have a different dataset sampled from the same distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*spGabp3bqpo2NbvgNBYyzA.png" /></figure><p>If you look at both the second and third datasets, these are some polynomial regressions you might get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*PHdekaeQI_Zwj69D8E0jiQ.png" /></figure><p>They’re all overfitting, they all have low empirical risk and high true risk, but critically all the orange curves are different from one another. This is a very important observation. <strong>When we are overfitting, we see that different training sets — even though they come from the same distribution — will lead to very different solutions</strong>. This is kind of inevitable, because in order to overfit we have to get low empirical risk (the orange curve has to go through the blue dots) and high true risk (it can’t match the black curve); so as we move the blue dots around, the orange curve has to be in different places. In summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*3avL-RcViClUWwrkwhzstg.png" /></figure><p>On the other hand, if you’re getting underfitting, your empirical risk is high and your true risk is high. You’re getting a fit that is not going to vary nearly as much between different training sets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*d1hmPC2n41Kovj8U4DWmYw.png" /></figure><p>In fact, if you aggregate all of these three datasets together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*h9rgmWxK0S15QQUgBQ6OIA.png" /></figure><p>The linear fit to this aggregated dataset will probably look pretty similar to the fits that it had to the individual datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*ru5-__R2pVEyXnv3QBDnVg.png" /></figure><p>If we’re getting underfitting, that means that our model is not powerful enough; it doesn’t have enough free parameters to fit our function accurately and it’s not utilizing all the information that’s present in the training set. So, as the training set changes, it’s not going to change very much because it’s not pulling out all the information</p><p>To recap, in overfitting:</p><p>(1) The training data is fitted very well (2) The true function is fitted poorly (3) The learned functions will look different each time</p><p>In underfitting:</p><p>(1) The training data is fitted poorly (2) The true function is fitted poorly (3) The learned function looks similar, even if we pull together all the datasets</p><p>Now let’s make this more mathematically precise. We’re going to write down the expected value of the error given a distribution over datasets. So, we’re not taking an expected value with respect to x or y, we’re going to be taking an expected value with respect to the dataset D. If we can write a probability of D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*vxK_G0hMSwik3GrUAHUSGg.png" /></figure><p>Then we can take an expected value of a function of D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*NaNkWnof9kjUWgaP1OCmqw.png" /></figure><p>What is the expected value of the error between fθ(x) and y?</p><p>fθ(x) here is trained on D, but D is a random variable. This is not an expression that measures the average error for a particular fθ(x), it’s actually measuring the expected error of your training algorithm. For every value of D, you get a different fθ(x): this is really a function of D. Now, D goes in your learning algorithm, produces a θ and then we’re going to look at the error of that.</p><p><strong>In other words, in expectation, if I give you infinitely many datasets and you train on each of those datasets separately, what will your error be on average? </strong>Of course, this is just a theoretical exercise: in practice, when we do machine learning, we only get one training set.</p><p>The above equation can also be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*XjGJcCM_CFxQ0aL7Y9gW3g.png" /></figure><p>F(x) is the true function; fD(x) is the function I get from training on D.</p><p>As you might know, the expected value of some function is just a sum over all the values of your random variable, of the probability of that value times the value of that function. In this case, the expected value is a sum over all possible datasets of the probability of that dataset times the squared difference between fD(x) and f(x).</p><p>We can then take this expected value of the error and we can break it up into two terms, assigning blame to those terms. We can blame one of them for overfitting and we can blame the other one for underfitting.</p><p>For a little bit of notational convenience, I’m going to use f bar (x) to denote the expected value of fD(x). Importantly, f bar (x) is the average over all possible functions you would get for all possible datasets weighted by the probability of those datasets</p><p>That’s not to say that fD(x) is what you would get if you had infinite data, because every individual fD(x) is still fitted to a particular finite size training set, but you’re averaging their predictions together.</p><p>Now, we’re going to take this equation for the expected error and, inside the square, we’re going to subtract f bar and add f bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*akAt1nTvA6PS0dwRNajgZg.png" /></figure><p>Then, I’ll put parentheses around the first two terms and parentheses around the third and fourth term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*5aQcTMiFjLI-Qigzk3mQCg.png" /></figure><p>Now I’m going to evaluate the square of this quantity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJDk8wMPxyhatv3uN0vnvw.jpeg" /></figure><p>The third term ends up cancelling out, because this term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*WYSOYXmcOjIWvTVpDIBXng.png" /></figure><p>Does not depend on D. Therefore, by linearity of expectation, we can take it out. Moreover, this term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*-75jXjeHa4zRBuqcJPxdXw.png" /></figure><p>Also ends up equalling 0, because f bar (x) denotes the expected value of fD(x); therefore, the expected value of fD(x) minus f bar (x) equals 0.</p><p>Now, we are left with the first two terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*h93Xb1lUXeZFRwcoy9jjRg.png" /></figure><p>The first term is the variance. Notice that this first term doesn’t actually have f(x) in it, so this is regardless of what the true function is; this is quantifying how much our prediction changes with the dataset. In other words, how much does fD (x) vary for different training sets?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*9ZD1-HKhzLBqeZ_lLhrsRA.png" /></figure><p>In the second term, we can remove the expectation altogether, as f bar (x) minus f(x) don’t depend on D. It’s just the squared difference between the average over all of your predictions (f bar (x)) and the true function f (f(x)). We call this the bias, technically the square of the bias. The bias essentially quantifies how far off is the average prediction you get from the true function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*Myl_Qu_vQCbdlETYS_XusA.png" /></figure><p>In this case, the bias is pretty high. This error doesn’t go away no matter how much data we have, as it is quantifying how under-parametrized we are.</p><p>The full error is just the variance plus the squared bias. These two terms thus account for overfitting and underfitting.</p><p>So, if the variance is too high, then you have too little data or too complex of a function class: <strong>overfitting</strong>. On the other hand, if the bias is too high, then you have an insufficiently complex function class: <strong>underfitting</strong>.</p><p>Once we recognize that our error consists of variance and bias, then we know that getting an algorithm that works well requires regulating the trade-off between bias and variance. It’s very important to understand which term is big and which term is small, because many of the troubleshooting techniques we have for reducing variance will actually increase bias and vice versa</p><h4>Regularization</h4><p>Let’s talk about how we can trade off bias and variance: a key idea of neural nets, is that they use models that are “too complex” — complex enough to fit all the noise in the data. One then needs to “regularize” them to make the models fit complex enough, but not too complex. The more complex the model, the better it fits the training data, but if it is too complex, it generalizes less well; it memorizes the training data but is less accurate on future test data.</p><ol><li>Getting more data addresses variance. The more data you have, the less you will overfit and the less variance you will suffer from. Getting more data doesn’t generally improve bias:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*92UrRknap5qoZFwkZNND5Q.png" /></figure><p>2. You can change your model class. For example, you can take your 12th degree polynomial and change it to be a linear function; this will probably reduce variance and increase bias. But this is a very discrete choice. <strong>Ideally, we’d like something that more smoothly restricts the model class. </strong>We’d like to construct a continuous knob for complexity. This is where regularization comes in.</p><p>Informally, regularization is something we add to the loss function, typically to reduce variance, although not always. <em>One of the easiest ways to understand regularization is through the Bayesian interpretation, which regards regularization as a prior belief about our parameters.</em></p><p>The high level intuition for the Bayesian perspective is that, when we have high variance, it’s because the data doesn’t give us enough information to identify the parameters. If we only have five data points and we have a 12th degree polynomial, the function is underdetermined: there are many different 12th degree polynomials that fit those five data points really well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*HJQDnkeg9TxLWAjDIQoCpQ.png" /></figure><p>We therefore need to somehow provide a little bit more knowledge to the algorithm; as there’s not enough information in the data, we can provide some through the loss function. We need to answer the question: <strong>given the dataset D, what is the most likely parameter vector θ?</strong></p><p>In other words, this question relates to your knowledge about the domain. In this case, you might have reasons to believe that, for your problem, the third function is more likely to be a good choice. <strong>The Bayesian perspective then tries to frame the entire learning problem of how to get θ from D probabilistically.</strong></p><p>D is just a set of (xi,yi) tuples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*OgdfF5gCe-W6PnKr84YoOQ.png" /></figure><p>If you want the distribution over θ given D, you can just apply the definition of conditional probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*ceyPB10rtkvo1hnMYZ9Vpg.png" /><figcaption>Up to a constant, this is equivalent to p(θ,D).</figcaption></figure><p>By the chain rule of probability, we can factorize this as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*e0l5rf5kbPaSsW-duYCrzQ.png" /></figure><p>This should ring a bell. The probability of D given some θ, using the IID assumption, can be factorized as a product over all of your data points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*rtniigraLXVXDuTVVMQuDw.png" /></figure><p>What about p(θ)? This is our prior. This expresses how likely θ is a priori, before even seeing your training set.</p><p>For example, without even seeing your dataset D, if you believe that for your particular problem smoother functions are more likely, you might say the second function is a better candidate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*yrhRRcQm153luPgUits6Fg.png" /></figure><p>On the other hand, if you believe that spiky functions are more likely, the first function is a better candidate.</p><p>Let’s say we go with the second function. Based on this prior knowledge, how do we build a prior in such a way that the smooth function is made more likely? Before answering this question, notice we now have a different loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*DB0JG_YnkKcgqwxzgAUjoA.png" /></figure><p>The first part is exactly the negative log likelihood we are used to. Now, we simply subtract the prior from the negative log likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*fIjhkA7i1WZc9pm1poO0SA.png" /></figure><p>Again, we have to choose the prior — and this is a design choice that does not come from the data. It is our prior belief.</p><p>In other words, as polynomials with small coefficients don’t result in large spikes, what kind of distribution assigns higher probabilities to small numbers?</p><p>There’s a wide range of distributions we can choose from, but one very very simple choice is to use a normal distribution — which assigns most of the probability mass on small numbers, close to zero. How close? This is determined by the variance. The lower we choose variance to be, the less likely functions with spikes become.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*wKTQu_gc0zh6G5fXjevftQ.jpeg" /></figure><p>Here is the expression for the log probability of a normal distribution with a mean of zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*Ap1ICu2c1yGFr7I55B69Yg.png" /></figure><p>The second and the third terms don’t influence θ and we can thus disregard them and express them as a constant value. We can rewrite this prior like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*S37HnoTuIZaJ6mChL2cI8g.png" /></figure><p>Lambda is 1/2 times sigma squared, but we don’t care about its precise value as we’ll just keep it as a hyperparameter — we’ll have to select it in order for the algorithm to work well. Our new loss function is thus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*td-nIAGNAKVZs7X8o9lcfg.png" /></figure><p>This is the same objective we had before; all we’ve done is we added a quadratic penalty term to the Cross Entropy Loss Function L.</p><p>One common alternative choice is L1 (or “LASSO”) regularization, which uses a penalty which is the sum of the absolute value of all the weights in the DLN, resulting in the following loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*pyRoqYxCKLQFo-STVABhdw.png" /></figure><p>This also favours small numbers, but it has constant slope (unlike the squared function, which has increasing slope): it encourages as many entries as possible in the vector θ to be zero — in other words, it encourages sparse solutions.</p><p>Another regularizer that is used with deep neural nets is called dropout. In dropout, we literally drop out (zero out) some neurons during training. Throughout training, on each iteration, standard dropout zeros out some fraction (usually 1/2) of the nodes in each layer before calculating the subsequent layer. Randomly selecting different subsets to dropout introduces noise into the process and reduces overfitting. Dropout reduces the capacity of the model during training and hence as a general practice wider networks are used when using dropout. If you are using a dropout with a random probability of 0.5 then you might want to double the number of hidden neurons in that layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*vaAxtBvHIZb58mC2UXYveQ.png" /></figure><p><strong>Why many layers?</strong></p><p>The XOR problem is the problem of using a neural network to predict the outputs of XOR logic gates given two binary inputs. An XOR function should return a true value if the two inputs are not equal and a false value if they are equal. XOR is a classification problem and one for which the expected outputs are known in advance. A perceptron, which is a feed-forward network, is only capable of separating data points with a single line. This is unfortunate because the XOR inputs are not linearly separable. The solution to this problem is to expand beyond the single-layer architecture by adding an additional layer of units without any direct access to the outside world, known as a hidden layer. This kind of architecture is another feed-forward network known as a multilayer perceptron (MLP). In general, deep neural nets are often surprisingly powerful in learning complex functions without sacrificing generalization. And a core intuition behind deep learning is that deep nets derive their power through learning internal representations.</p><p>Deep learning is all about creating intermediate layers wherein each node in an intermediate layer represents the presence or absence of a different configuration of inputs. This way, if the input is a cat image, no individual pixel has to correlate with whether there’s a cat in the photo. Instead, the middle layer will attempt to identify different configurations of pixels that may or may not correlate with a cat (such as an ear, or cat eyes, or cat hair). The presence of many cat-like configurations will then give the final layer the information (correlation) it needs to correctly predict the presence or absence of a cat. You are going to train a neural network to learn patterns by observing all the individual datapoints and <em>searching for correlation</em>.</p><h4>How do we select hyperparameters?</h4><p>The idea is that we take the dataset and separate it into a training set and a validation set. Typically, the training set might be 80/90% of the dataset and is used to select (1) parameters θ (via optimization) and (2) those hyperparameters that affect optimization, like the learning rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*UuFjsVeIeNx1oZwkB5WK_w.png" /></figure><p>This is the training loss and it depends on D train:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*ZAYGh7i_RwIdp1mogpJpmg.png" /></figure><p>On the other hand, the validation set is not used for training; we will use it to make any other choices that are that are needed to design your method. Specifically, it is used to select (1) The model class (2) The hyperparameters of the regularizer (3) Which features to use. The validation loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*8qyK9RxUYbbvnb-tVhKj1Q.png" /></figure><p>This loss will allow us to diagnose overfitting and underfitting. Why? Because the training loss is your empirical risk, while the validation loss uses data that was not used for training and is thus an unbiased estimator of the true risk. By comparing these two losses you can determine if you’re overfitting or underfitting.</p><p>The machine learning workflow that you would typically use is:</p><p>1 Train your parameters θ on the training set.</p><p>If the training loss is not low enough, you are underfitting. To reduce underfitting, you can (1) decrease regularization (2) improve your optimizer.</p><p>If the training loss is low:</p><p>2 Look at the validation loss. If the validation loss is higher than the training set, you are probably overfitting. To reduce overfitting, you can (1) increase the amount of regularization (2) go out and get more data</p><p>Once you’ve done that, you can repeat the process.</p><p>In practice, we do something that is a bit more interleaved. We look at training loss and validation loss plotted on the same axis.</p><p>For example, this is stereotypical overfitting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*ncKVpMRjntQDx_1nun9J9Q.png" /></figure><p>Initially, both losses are going down, but later on the validation loss starts going up as the training loss drops further. Your learned function is fitting better and better those training points at the expense of actually deviating from the true function.</p><p>This is stereotypical underfitting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*h7RMM9BR1bS3vjmmwbDg3Q.png" /></figure><p>The validation loss and the training loss decrease at a similar rate, but they don’t decrease as much as we would like. That gap at the end is bias.</p><p>When looking at the overfitting case, one idea arises: would it make sense to hit the sweet spot before the validation error goes up and stop our optimization process? In fact, <em>this is called early stopping</em>. When the validation has been going up consistently for the past n iterations, you just rewind n steps and take whatever you had back then.</p><p>But does this mitigate all overfitting? No, because even if you can stop the optimizer at the right sweet spot, the validation error might never get as low as it could have if you had used appropriate regularization. So, early stopping is one way to combat overfitting, but it doesn’t solve all your problems.</p><p>Now, let’s say you followed this recipe: you don’t have underfitting, you don’t have overfitting, your losses are all good. How do you evaluate the final performance of your model?</p><p>We can’t really rely on the validation loss being unbiased anymore, because we used it to select (1) The model class (2) The hyperparameters of the regularizer (3) Which features to use. We can’t really rely on the training loss either, because we used it to select (1) parameters θ (via optimization) and (2) those hyperparameters that affect optimization, like the learning rate.</p><p>We could reserve another slice of the dataset for the final exam. We’ll call it the test set and we’ll use it only to report the final performance. Instead of partitioning our dataset into two parts, we’ll therefore partition it into three parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*968He5T1tQzn-tMK6sAmyg.png" /></figure><p>Hyperparameter tuning is often difficult and time consuming. There are a few techniques that we can use to guide us during the search.</p><ul><li>Grid Search: try all possible combinations of hyperparameters</li><li>Random Search: randomly try different combinations of hyperparameters</li><li>Coordinate-wise gradient descent: start at one set of hyperparameters and try changing one at a time, accept any changes that reduce your validation error</li><li>Bayesian Optimization / Auto ML: start from a set of hyperparameters that have worked well on a similar problem, and then do some sort of local exploration (e.g., gradient descent) from there.</li></ul><p>There are lots of choices, like what range to explore over, which parameter to optimize first, etc. Some hyperparameters don’t matter much (people use a dropout of either 0.5 or 0, but not much else). Others can matter a lot more (e.g., size and depth of the neural net). The key is to see what worked on similar problems.</p><h4><a href="https://www.youtube.com/watch?v=RdoZWcXmXhk&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=11">Optimization in deep learning</a></h4><p>We’re going to talk about optimization algorithms. Let’s start with a recap of gradient descent.</p><p>We can formulate the problem of learning θ as our attempt to find the θ that maximizes the log p(D):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*hlTcsUEx5XcyFKOVJfqfPw.png" /><figcaption>This is called maximum likelihood estimation (MLE), because this log probability is the likelihood and we are choosing θ to maximize the likelihood</figcaption></figure><p>Often times, we will see this written as a minimization (this is just a convention):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*0epNMapoWMF7l9BENm7c8A.png" /><figcaption>This is also called the cross-entropy</figcaption></figure><p>We still want to maximize the the log p(D), which is the same as saying that we want to minimize the negative log probability. So, this is our loss function, which quantifies how bad θ is. To find the setting of θ that minimizes our loss function, we have to find the direction v such that L(θ) decreases and then pick the new θ to be the old θ plus some rate α times v. Then, we repeat this process enough times. In general, we set the direction for every dimension to be the negative of the partial derivative of our function L with respect to that dimension of θ.</p><p>We’ll discuss at length situations in which gradient descent works, situations in which it works poorly and how we can improve it. One type of picture that we’ll see a lot is a contour plot. The lines correspond to level set contours; so, for all θ values along one of these contours, the loss takes on the same value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*KwuOYhmEUozisCzwgXUW_Q.png" /></figure><p>We’ll visualize the optimization path for gradient descent with lines. The endpoint of each orange segment represents a value of θ on one of the iterations of gradient descent; the segment between those endpoints represents the step (which is the gradient direction multiplied by the learning rate).</p><p>Convex functions tend to optimize pretty well. Here’s a function in one dimension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*RVurtnQCl6cG1e-kqmalVA.png" /></figure><p>A function is convex if a line segment between any two points on that function lies entirely above the graph. In contrast, this function is not convex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*iVqCvGUn4gelrknlRRWuFw.png" /></figure><p>If I draw a line between the two points, it will intersect the graph. This function also happens to have two optima. In general, a function can be non-convex even if it has only one optimum. For example, this function has only one optimum, but, as it also has a plateau, if I draw a line between these two points it will intersect the graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*SVenSjLl7yANoJlaoaN-jg.png" /></figure><p>So, a function being convex implies that it has only one optimum, but a function being non-convex does not imply that it has more than one optimum.</p><p>It’s possible to prove that gradient descent on convex functions will find the global optimum in a number of iterations that is not too large. This doesn’t mean that gradient descent works well for all convex functions, because it doesn’t always move in the direction of the optimum. It will always take the steepest descent direction, but the steepest descent direction is not the one that goes directly towards the minimum point. For example, if we look at the first step we take from the starting point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*-m8cTYn2Nj0EqbqAgSaASQ.png" /></figure><p>We see that it is moving away from the optimum.</p><p>Imagine this kind of function. Each ellipse represents points with an equal value of the loss. The optimum is in the middle. The direction of steepest descent is always perpendicular to the tangent to the level set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*iAtQrH7B_gdX03c_W3hfTA.png" /></figure><p>At that point if we compute the steepest descent direction, we’ll go the other way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*B-5PWaEG74JxkweksB7ajQ.png" /></figure><p>And then the other way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*u_Ls3km8a5Mjpvykk_AqKg.png" /></figure><p>Eventually this will reach the optimum, but it might take quite a long time.</p><p>What about the loss surface of a neural network?</p><p>A neural network is a more complex function with many parameters and many layers of representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*12rv74KIsgvBUwnyEEdP_w.png" /></figure><p>It’s pretty hard to visualize the loss surface of a neural network, because neural networks have a very large number of parameters. Some networks’ loss is decent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*YnOw8sz4AU2dRIopF11q6w.png" /></figure><p>However, the loss generally looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*j5O4QU6iH7VePyq-vBoACA.png" /></figure><p>In general, neural networks’ loss landscapes are definitely not convex.</p><h4>What are some geographical features in a loss landscape that we should worry about?</h4><p>There are three features that are important to know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*QSkQosvueB-H4N-2M_Hyzg.png" /></figure><p>Local optima are the most obvious issue when it comes to non-convex loss landscapes. The issue is that you might have more than one point where the derivative is zero. At any of these local optima, the derivative will be zero, which means that there’s no improvement.</p><p>Local optima are very scary in principle, because gradient descent could converge to a solution that is arbitrarily worse than the global optimum and you have no way of knowing. A bit surprisingly, neural networks with many parameters definitely have local optima in their loss landscapes, but these optima tend to be not much worse than global optima.</p><p>You can visualize this in the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*5pTaf5V8BxVPUC92Lclf8w.png" /></figure><p>On the horizontal axis, we have the numerical value of the loss for the solution discovered by gradient descent. This is a histogram, so the vertical axis represents how many rounds of gradient descent, each starting from a different random location, achieved that loss. It’s kind of plotting the frequency of runs that got that loss. The different colours represent networks of different sizes; larger numbers here correspond to bigger networks with more parameters.</p><p>Roughly speaking, for the smallest networks shown in yellow there’s a wide distribution of different loss values. It’s still not that wide, all the numbers are between 0.08 and 0.10, but there there’s some variability, which means that the optimization is falling into local optima with a range of different loss values. But as the networks get bigger and bigger, the frequency of networks that achieve different losses becomes much tighter; for the red, the largest networks, you can see that there’s still some variability in the loss, but the solutions are clustered much more densely in the range of 0.072 and 0.078, roughly.</p><p><strong>What this means is that bigger nets do have local optima, but those local optima are all fairly similar to each other and they’re all pretty good.</strong></p><p>Let’s move to the second issue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*X7dgA-DcF0l0zzmsffZbzw.png" /></figure><p>We could imagine a loss landscape where we don’t have a local optimum, but we have a large region where the gradient of the loss is very small. If it weren’t for these plateaus, we could just use small learning rates and would be able to make slow and steady progress towards the optimum. But when these plateaus are really flat, a small learning rate might mean that it essentially takes you forever to get through the plateau. So you need learning rates that are large enough not to get stuck in a plateau like this.</p><p>Third issue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*4ngCECUfoco0jG_x4YMU0Q.png" /></figure><p>Saddle points are something that doesn’t really exist for one-dimensional functions, but for functions in higher dimensions they are fairly common. Intuitively, you can think of a saddle point as a local minimum along some dimensions, but a local maximum along other dimensions. At a saddle point, the partial derivative with respect to each dimension of the function is zero, but the function is increasing in some of the dimensions and decreasing in other dimensions.</p><p>This is where our intuition about functions from thinking about low dimensions is very misleading.</p><p><strong>What’s a critical point?</strong></p><p>A critical point is any point where the gradient is zero, meaning that all partial derivatives of the loss with respect to every dimension of θ are 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/1*qZKl1Bk7PNIROKMTanL0fg.png" /></figure><p>There are different types of critical points; for a given critical point, is that a maximum, minimum or saddle point? The way that you know is by looking at the second derivatives.</p><p>In 1D, if you’re at a critical point and the second derivative is positive, that means the the graph is sloping upwards. That means you have a local minimum. On the other hand, if the second derivative is negative, then that means that you’re at a local maximum. But in higher dimensions, you could have some second derivatives be positive and some be negative</p><p>In general, we can construct a matrix, called the hessian matrix. The hessian matrix is basically the second derivative equivalent of the gradient.</p><p>The gradient is a vector where every entry is the partial derivative with respect to the corresponding dimension of theta; the hessian is a matrix where every entry is the second derivative with respect to two entries in theta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*lBidCPtc1uWNwNiRQHacYA.png" /><figcaption>Hessian matrix</figcaption></figure><p>The hessian matrix at a saddle point is going to have diagonal entries that are 1 for some dimensions and -1 for others.</p><p>The point is a maximum or minimum only if all of the diagonal entries have the same sign. Otherwise, it’s a saddle point. Imagine what happens in higher dimensions: how often is it going to be the case that all of the 100’s of diagonal entries have the same sign? In higher dimensions, it seems pretty unlikely that every single diagonal entry will be positive or every single diagonal entry will be negative. <strong>So, most critical points in higher dimensions are saddle points.</strong></p><p><strong>Improvement directions</strong></p><p>Are there methods that accelerate gradient descent without requiring second derivatives (which would imply a very long runtime)?</p><p>1 Momentum is exactly what it sounds like. If we remember this picture from before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*GN-4qG1DAA7lRCcWoju5Vw.png" /></figure><p>Gradient descent is going to oscillate back and forth, but if we look at a couple of successive gradient updates, we’ll notice that they tend to point in opposite directions. It’s thus very tempting to think that if we can just average them together, we’re going to get exactly the direction we want.</p><p>The intuition is that if successive gradient steps point in different directions, we should cancel off the directions that disagree and just keep the directions that agree; on the other hand, if successive gradient steps point in similar directions, we should go faster in that direction.</p><p>The update rule we’re going to use with momentum is very much like gradient descent. The difference is that we also take the previous direction and multiply it by a decay factor between 0 and 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*dDW3BG5J4sgtzE74YoHeAw.png" /></figure><p>If the previous direction and the new one point in opposite ways, they’ll cancel off. If they point in similar directions, they’ll actually add up together and go even faster in that direction. Momentum brings lots of benefits at virtually no cost.</p><p>The next issue I’m going to talk about is the scale of the gradient. The sign of the gradient is important, because it tells us whether the gradient points left or right; but the magnitude, which tells us how far it goes along each dimension, is a lot less informative.</p><p>Even worse, the overall magnitude of the gradient can change drastically over the course of optimization, which can make learning rates hard to tune. The explanation is that the more f θ(x) differs from y, the larger the gradient will be. So, if initially f θ(x) is very different from y, then your gradients will be huge and when your gradients are that huge you’ll almost certainly overshoot the optimum and come out the other side. But as your function f θ(x) gets closer and closer to y, the gradient will become tiny and at that point you might be taking really small steps and you might want a better learning rate.</p><p>One idea that could help us mitigate this is to normalize out the magnitude of the gradient along each dimension. If you can somehow figure out roughly how big the gradient tends to be on average along each dimension and divide by that, then you’ll remove these annoying scaling factors.</p><p>RMSProp is one algorithm that does this. The idea is to estimate the per dimension magnitude of the gradient, on average:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*hl353f59T-a1Sa5U8BrqWw.png" /></figure><p>Every step, we are going to take the old value of Sk and multiply it by some factor β (a factor between 0 and 1). Then we’ll take 1-β and multiply it by the square of every entry in the gradient. This is roughly the squared length of each dimension.</p><p>When we update θ, we take a step in the direction of the gradient, but we divide it by the square root of Sk, which is its average squared length. So, each dimension is divided by roughly its magnitude:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*FD2It6casePFIvR7JvjU8w.png" /></figure><p>3 AdaGrad is a more theoretically principled version of RMSProp. With AdaGrad, we also estimate per-dimension magnitudes, but we estimate them cumulatively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*FgyuuRfxXHeNjVNbP48Kpw.png" /></figure><p>As you can see, it is precisely the same as RMSProp, but without β and 1-β. This implies that Sk is going to keep getting bigger and bigger.</p><p>So, how do AdaGrad and RMSProp compare?</p><p>AdaGrad has some very appealing guarantees for convex problems. However, for non-convex problems, the fact that we keep dividing by bigger and bigger Sk’s means that the learning rate decreases over time — and this can be a problem. AdaGrad only works if you find the optimum quickly, before Sk gets so big that your updates become tiny.</p><p>On the other hand, RMSProp tends to work a bit better than AdaGrad for non-convex problems, because unlike AdaGrad, it forgets. Over time, the fact that you’re multiplying Sk-1 by β means that the algorithm will forget the gradients that it’s seen a long time ago.</p><p>Adam combines momentum and RMSProp. We use momentum to accelerate gradient descent and we divide by a running average of the squared lengths to normalize out the lengths.</p><p>First step, similar to momentum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*ADeJvNwuqvYRB5dwz57wuA.png" /></figure><p>In a similar way to momentum, we’re accumulating our gradients as we go. You can think of mk (where “m” stands for mean) as a running average of the gradients.</p><p>Second step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*y56G-hbuq8xkUS9q6pHMHg.png" /></figure><p>vk is the second moment estimate: a running average as well, but of the squared lengths of the gradient.</p><p>Third step, as we initialize m0 and v0 to be zero, we want to prevent the steps we’re taking to be small at the beginning and big over time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*AhoAxBYbe9dd4EOTRZvh0w.png" /></figure><p>Fourth step, our update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*dgtJd48OPiCxnlTmctGDnA.png" /></figure><p><strong>Stochastic optimization</strong></p><p>All the versions of gradient descent I’ve described so far are actually not suitable for use with deep learning. For example, negative log likelihood loss requires summing over all the data points in our training set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*EsmMj2-Fq_amzIzdZoxJHg.png" /></figure><p>However, in deep learning things tend to work best when the dataset is very large. Effectively optimizing a neural net might thus require millions of gradient steps and this would be pretty prohibitive.</p><p>One of the things we can recognize is that this sum is really a sample based estimate of an expected value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*Y28-dQ_Gnn7yWR3jA8xKMQ.png" /></figure><p>If you consider the expected value under the data distribution of the log probability of y given x, the sum that you’re actually computing for your loss is just a sample based estimate of that. And a sample based estimate of an expected value is unbiased for any number of samples. If you use fewer samples, you’re going to get a worse estimate, but it’s still an unbiased estimate.</p><p>One of the things we can do if we want gradient descent to be computationally faster is we can simply use fewer samples than the entire training set for each update. We could pick a subset of B samples and just average together those B samples — where B is much less than n:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*q23FeWM7Vod191I8_K1HhA.png" /></figure><p>Of course, if we just pick those samples once and we use them for the entire optimization process, that’s pretty wasteful because we’re not using most of our data. What we can do is we can pick a different subset of size B every single gradient step and this way our estimated gradient with a small number of samples will look like the true gradient — with some noise, because just by random chance every single gradient step will get a slightly different group of B samples.</p><p><strong>Stochastic gradient descent with mini-batches</strong></p><p>1 Sample a subset B of your entire training set D</p><p>2 Estimate an approximate gradient direction by averaging the gradient over all the points in your batch B. This is approximately going to be the gradient of your loss, but the reason it is not exactly the same is that you’re using many fewer points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*NW36Zg7W2f6uUMpSppzWeQ.png" /></figure><p>3 Use gradient descent with the approximate gradient. Of course, you can also use momentum, ADAM, etc.</p><p>Each iteration samples a different mini-batch. This is the ideal version of stochastic grading descent, but in practice you can actually do things a little more efficiently.</p><p>Sampling randomly every single step is pretty slow due to random memory access. If you have very complex data, it would be laid out sequentially in memory; so if you index into a random image every single time, then you’re doing a lot of random memory access which is going to trash your cache coherence. Instead, you can shuffle our dataset in advance, the same way you shuffle a deck of cards, and then index into that data set sequentially. Technically, this is not quite the same as regular gradient descent because you’re only shuffling once in the beginning, but the order with which you loop through the batches is random, so in practice this turns out to be pretty much just as good as the true stochastic grading descent and way cheaper computationally.</p><p><strong>Learning rates</strong></p><p>How can we adjust learning rates for these algorithms?</p><p>In this graph, the vertical axis is the training loss; the horizontal axis is the epoch — an epoch is just how many times you’ve gone through the whole dataset. With regular gradient descent, the number of epochs is equal to the number of optimization steps; with stochastic gradient descent, the number of epochs is the total size of your dataset divided by the size of your mini-batches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*UIsJOLJuMFV0ASCDdkQbEQ.png" /></figure><p>The red curve shows what you would expect to see for your training loss if you had a well-chosen learning rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*z7J0t7le_8sKr50XgG29WQ.png" /></figure><p>The green curve is descending a lot slower, so that means that our learning rate is probably lower than it should be. In deep learning, low learning rates can result in slow optimization and in convergence to worse final results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*idPRKUpBIIzCTjqDM9mKWg.png" /></figure><p>The yellow curve starts off really fast, but then it gets stuck, so that means that our learning rate is probably too high. When we’re going too fast, we’ll tend to go really quickly at first, but then you get stuck at a worse value.</p><p><strong>Learning rate decay</strong></p><p>One of the things you might be thinking at this point is: if high learning rates go quickly at first, but then get stuck, why don’t we start with a high learning rate and then switch to a lower learning rate?</p><p>Here’s a plot of a neural network, AlexNet, being trained on ImageNet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*-qRzSsu565YQNHQ_Pt5Klg.png" /></figure><p>It’s being trained with a learning rate decay schedule, where the learning rate is divided by 10 every once in a while. What you can see is that initially, with a learning rate of 0.01, accuracy improves rapidly, then it kind of plateaus. The learning rate gets decreased more and now your accuracy improves further and then it plateaus. Once again, the the learning rate is decreased and then accuracy improves further and plateaus. Eventually, you get close enough to the local optimum and then you stop improving. It is worth noticing that typically you don’t need learning rate decay with ADAM.</p><p><strong>Tuning stochastic gradient descent</strong></p><p>Hyperparameters to tune:</p><ul><li><strong>Batch size B</strong>. Usually, larger batches lead to less noisy gradients, which is safer but more expensive.</li><li><strong>The learning rate </strong>α<strong> </strong>is a somewhat tricky thing to choose. Generally, it’s better to use the biggest learning rate that works. You might want to decay it over time.</li><li>For momentum μ, good settings are 0.90 or 0.99, but you have to adjust it to fit your problem</li><li>ADAM parameters β1 and β2; usually, keep the defaults.</li></ul><p>How do you tune these hyperparameters? Technically, you want to tune these parameters on the training loss, because unlike regularization they’re not trying to give you better generalization to new points.</p><p>However, in practice, stochastic gradient descent hyperparameters are often also tuned on the validation set and it’s kind of an interesting choice. There’s a complex relationship between stochastic gradients and regularization; conventionally, we would separate out optimization from generalization. But recently there’s been quite a lot of research studying how great stochastic gradient descent itself can actually act as a sort of regularizer. The intuition is thus that if you start overfitting, you would expect the gradients to look very different for different batches, so you don’t want to average those out — you don’t want to get to the very bottom of your loss landscape. So, this is the crude intuition for why some people think that stochastic gradient has a desirable regularizing effect and therefore when you tune the hyperparameters of stochastic gradient descent you should actually be looking at the validation loss.</p><p><strong>Computation graphs for deep learning</strong></p><p>All machine learning algorithms are a program with some parameters. One of the ways that we can visualize that program is by drawing a graph that represents the flow of computation.</p><p>Here’s what a computation graph looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*DnO3hp2MwL8V1ZU1VGMCyA.png" /><figcaption>Computation graph for linear regression</figcaption></figure><p>This computation graph represents linear regression. We compute x1 times θ1 plus x2 times θ2; then we subtract y and square the difference and this gives us the mean squared error (MSE) loss. Generally, when we draw computation graphs for neural networks, we’re drawing the graph combined with a loss function.</p><p>Neural networks are generally much more complex and much larger computation graphs than the one that I have drawn above. Before we can draw computation graphs for neural networks, we need to talk about vectors and matrices; after we do that, we can design generic tools for computation graphs and use those tools to train many different kinds of neural networks with minimal additional engineering.</p><p>Let’s draw the same linear regression graph as before, but in a much simpler way, by using vectors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*ZbnE50qYaH2ruYmMjnFX_g.png" /><figcaption>Computation graph for linear regression</figcaption></figure><p>Now we have a node x that represents a vector of two entries x1 and x2; we also have a node θ that represents θ1 and θ2; after multiplying the two vectors, we subtract the label y from them and square the difference. This is exactly the same computation graph that I showed before, only written in a much more concise way by using vector notation.</p><p>On a similar note, we can look at this elaborate graph for logistic regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*88hajJUVWxLwVjVv3wmx0Q.jpeg" /><figcaption>Computation graph for logistic regression</figcaption></figure><p>And make this one simpler as well, by using matrices. We can write logistic regression in matrix notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*Fi_9znMB_12Su3H4dMzdKQ.png" /></figure><p>As some matrix θ times the vector x. And thus our computation graph becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*r5dJV6C4UL_DX7EIS_Kmpg.png" /></figure><p>We could draw logistic regression even more concisely. Notice that we have two types of variables in these calculations. We have data variables like x and y, which are the input and the target output; and we have parameters (θ), which usually affect one specific operation (although sometimes there is some parameter sharing). If we notice these properties we can summarize this combination graph a little more. As we know that θ is only going to affect what happens in one place, we can think of it as a parameter of that multiplication and fold it into the multiplication node. We could draw the same picture, but more concisely, by saying that x goes into a linear layer (linear because it’s a matrix-vector product), then it goes into the softmax and then the softmax goes into the loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*116FRdXP6iigJdppNhoZcg.png" /></figure><p>Now we have this heavily simplified computation graph diagram and we can compare it to other common ways to visualize neural networks.</p><p>A common way to draw a neural network diagram is to visualize variables in the network as boxes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*vCVC2l9sf044TCdbrf_Onw.png" /></figure><p>The first variable that everything starts with is the input x; then we have a linear layer, which by default has parameters; this linear layer transforms x into some intermediate representation that we will call z(1). z(1) is the result of applying the first linear layer — the superscript one denotes that it’s the first layer. Then we take this z(1) and we feed it into the softmax.</p><p>An even simplified drawing would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*G9HXkgA2tvvVaQIJ5Ip9hQ.png" /></figure><p>Here, we cut off the loss, because we know that a cross entropy loss always follows the softmax. We also remove the green trapezoids and instead just label the arrow. We also remove the parameters because a linear layers always has parameters. This is the kind of graph that you’ll see very often in research papers.</p><p><a href="https://www.youtube.com/watch?v=lKRatcD9hEg&amp;list=PL_iWQOsE6TfVmKkQHucjPAoRtIJYt8a5A&amp;index=14"><strong>Backpropagation step by step</strong></a></p><p>The expression for logistic regression is pretty simple and we could write the equation on a piece of paper. Then, we could just use the rules of calculus to derive the derivatives of that expression with respect to each of the parameters. We could do the same thing with neural networks, working out the derivatives with respect to every in every weight matrix and construct our gradient. But given that a neural network contains many functions, it could take a really long time to work out those derivatives. Plus, if you change your network, for example by adding another layer, you have to re-derive all of your derivatives and that’s going to take a really long time.</p><p>What we would really like is an algorithm that can compute derivatives through neural networks automatically, without us having to work out all the calculus by hand. Then, we could implement any neural network we want, run this algorithm and get a gradient. This algorithm is called backpropagation.</p><p>As an aside, we need to recap how the chain rule of calculus (not to be confused with the chain rule of probability) works. Neural networks consist of compositions of many functions. Taking derivatives through compositions of functions is what the chain rule of calculus helps us figure out</p><p>If you have the expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/1*4kmZHOxtkhQ-H__GHrxVhA.png" /></figure><p>That means you have an input x, you apply a function g to x, you get y and you apply another function f to y. Eventually, you get z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*XSxVit38W5xeXpLB1XUqIA.png" /></figure><p>Let’s say you would like to differentiate this whole expression with respect to x. The chain rule tells you that the derivative is given by the product of the derivative of g times the derivative of f:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*MzV1cDsPvhoErq1gCltmnQ.png" /></figure><p>The same exact expression applies to multivariate functions — we just have to be a little careful with the order, because the order in scalar multiplication is exchangeable, while the same is not true for matrix multiplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*WuWEaG_1KrZ-EvHxJ54vqw.png" /></figure><p>The same chain rule holds: dz/dy is a vector and dy/dx is a matrix.</p><p>Let’s look at this neural network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*Pyw51iEzX_LnKkvAOCehYg.png" /></figure><p>We could use the chain rule to write out, for example, the derivative of the loss with respect to W(2). That’s equal to the derivative of z(2) with respect to W(2) times the derivative of the loss with respect to z(2):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*31ED8sQJvgQvH3XIUZxXsA.png" /></figure><p>In the same way, we can write out the derivative with respect to W(1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*Gafgg75UkqWqhPIpoDFxhA.png" /></figure><p>Here’s how we could try to do things a little more efficiently. All these jacobians in the middle are going to be about nxn, but the very last jacobian is always going to be about nx1 — because the loss is always a scalar value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*3cNCWMvytRrSJdOFBjdIlw.png" /></figure><p>So, these products in the middle are pretty expensive, because they are going to be O(n³), while the last product is pretty cheap, because it’s always going to be roughly O(n²).</p><p>Here’s how we can use this intuition to actually build a much more efficient algorithm. The idea is that we’ll start on the right, so that we always keep our computations at O(n²). First, we compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*NuGYVQ9q2COk12OFUnTgEQ.png" /></figure><p>This is a matrix times a vector and it’s cheap to compute. We call it delta (δ). Now let’s update our derivatives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*QvA_fnRm7Iggt6ZYBxR_dA.png" /></figure><p>Once again, we start on the right. We compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*EFHFP3WiBNGJF_X4Wab7lQ.png" /></figure><p>This is a matrix times a vector and it’s cheap to compute. We call it gamma (γ). And finally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*iMdFsNCrqY7pv2ORRmpapQ.jpeg" /></figure><p>Again, this last product is cheap.</p><p>Based on this intuition, we can derive the classic backpropagation algorithm. Let’s say we have this network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*NQrF1dPS6aaz9m1SX0OHNA.png" /></figure><p>First, we’re going to do a forward pass and we’ll calculate every a(i) and z(i). Then, we’ll do the backward pass and this is what backpropagation refers to. We’ll first initialize our delta vector to be the derivative of the loss with respect to the last z. Then, we’ll go from the end of the network back to the front and for every function (both linear and non-linear layers) with input xf and parameters θf, we’re going to perform this operation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*QTmejlGwhwUuYa8sznMcxw.png" /></figure><p>And update delta this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*8BRA5YN2bBy468C350U0-g.jpeg" /></figure><p><strong>Internal representations</strong></p><p>Earlier, we saw that deep neural nets are often surprisingly powerful in learning complex functions and that they derive their power through learning internal representations.</p><ol><li>Learning through gradient descent seems very alike to the evolution of a dynamic system. They both are described by a set of differential equations. Dynamical systems often have a “time-constant” which describes the rate of change, similar to the learning rate, only instead of time, gradient descent evolves through epochs. Saxe et al. (2013) showed that to analyze and to understanding the nonlinear learning dynamics of a deep LNN, we can use Singular Value Decomposition (SVD) to decompose the matrix of weights into orthogonal vectors, where orthogonality of the vectors would ensure their individuality (independence). This means we can break a deep wide LNN into multiple deep narrow LNN, so their activity is untangled from each other. A quick intro to SVD: any real-valued matix A can be decomposed to 3 matrices:</li></ol><p>A=UΣV⊤</p><p>where U is an orthogonal matrix, Σ is a diagonal matrix, and V is again an orthogonal matrix. The diagonal elements of Σ are called singular values.</p><p>2. Representational Similarity Analysis (RSA) is an approach that could help us peek inside to see how the net has structured its internal representations. The main idea is that the activity of hidden units (neurons) in the network must be similar when the network is presented with similar input. If we perform RSA in every training iteration, we may be able to see whether the narrow nets are learning the representations.</p><p><strong>Practical implementation</strong></p><p>Before we can train it with backpropagation and gradient descent, we need to answer a few questions about our neural network:</p><ul><li>How many layers should the network have?</li><li>How big are these layers?</li><li>What type of activation function should we use?</li></ul><p>With regard to activation functions, one particularly popular choice is something called the rectified linear unit or ReLU. The ReLU takes the previous activation, let’s say z(1), and it sets a(1) to be the max between zero and the corresponding entry of z(1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*AGapYVCoMqyRrFbGyLNd4Q.png" /></figure><p>It has a positive branch that is fully linear and then it has a negative branch that is flat. One might assume that it’s insufficiently non-linear, but actually it ends up working really well. It has a number of very appealing properties:</p><ul><li>It’s computationally extremely cheap to implement, which means that for very large neural networks it can speed them up considerably</li><li>Its derivatives are really simple and that also makes them computationally efficient and easier to work with</li></ul><p>Another detail that we have to talk about for implementing neural networks is the bias term. This is a classic linear layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*qp5xQKZGgzplNFOiGMwg-A.png" /></figure><p>But this layer has a major limitation. Let’s imagine that a(i) is a vector of zeros. In this case, the linear layer can never produce any output that is not zero, which means that you will always have zeros everywhere. This kind of neural network can never represent certain functions — it’s not a universal function approximator.</p><p>A solution to this is to add a bias vector, which turns linear layers into this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*sBqhWLqEVXnr_ulDaZ5O0w.png" /></figure><p>This is also called an affine layer. It turns out that if you have a neural network that has these kinds of layers and a non-linearity, like a sigmoid, as long as these layers are big enough you can approximate any function to an arbitrary level of precision. You cannot do that if you don’t have biases. So now the parameters of your neural net will consist of the weight matrices W1 and W2 and the bias vectors b1 and b2.</p><p>What else do we need to actually implement backpropagation? We need to be able to compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*6d4QVAdTMZKGLjF5PDhW2Q.png" /><figcaption>Parameters θf for every function f</figcaption></figure><p>And:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*yhZBxP3Bi0sXcpN1A95_GA.png" /><figcaption>Input xf for every function f</figcaption></figure><p><strong>PyTorch AutoGrad</strong></p><p>Deep learning frameworks such as PyTorch, JAX, and TensorFlow come with a very efficient and sophisticated set of algorithms, commonly known as Automatic Differentiation. AutoGrad is PyTorch’s automatic differentiation engine.</p><p>Everything starts with the forward propagation (pass). PyTorch tracks all the instructions, as we declare the variables and operations, and it builds the graph when we call the .backward() pass. PyTorch rebuilds the graph every time we iterate or change it (or simply put, PyTorch uses a dynamic graph).</p><p>For gradient descent, it is only required to have the gradients of cost function with respect to the variables we wish to learn. These variables are often called “learnable / trainable parameters” or simply “parameters” in PyTorch. In neural nets, weights and biases are often the learnable parameters.</p><p>In PyTorch, to indicate that a certain tensor contains learnable parameters, we can set the optional argument requires_grad to True. PyTorch will then track every operation using this tensor while configuring the computational graph. It is important to appreciate the fact that PyTorch can follow our operations as we arbitrarily go through classes and functions.</p><p>Here is where all the magic lies: in PyTorch, Tensor and Function are interconnected and build up an acyclic graph, that encodes a complete history of computation. Each variable has a grad_fn attribute that references a function that has created the Tensor (except for Tensors created by the user - these have None as grad_fn). At this point, we kick off the backward pass to calculate the gradients by calling .backward() on the tensor we wish to initiate the backpropagation from. Often, .backward() is called on the loss, which is the last node on the graph.</p><p><strong>Important Notes</strong></p><ul><li>Learnable parameters (i.e. reguires_grad tensors) are &quot;contagious&quot;. Let&#39;s look at a simple example: Y = W @ X, where X is the feature tensors and W is the weight tensor (learnable parameters, reguires_grad), the newly generated output tensor Y will be also reguires_grad. So any operation that is applied to Y will be part of the computational graph. Therefore, if we need to plot or store a tensor that is reguires_grad, we must first .detach() it from the graph by calling the .detach() method on that tensor.</li><li>.backward() accumulates gradients in the leaf nodes (i.e., the input nodes to the node of interest). We can call .zero_grad() on the loss or optimizer to zero out all .grad attributes (see autograd.backward for more).</li><li>Recall that in python we can access variables and associated methods with .method_name. You can use the command dir(my_object) to observe all variables and associated methods to your object, e.g., dir(simple_graph.w).</li></ul><p><em>Feel free to drop me a message or:</em></p><ol><li>Connect and reach me on<strong> </strong><a href="https://www.linkedin.com/in/samuele-bolotta-841b16160/">LinkedIn </a>and <a href="https://twitter.com/SamBolotta">Twitter</a></li><li>Follow me on <a href="https://medium.com/@samuelebolotta">Medium</a></li></ol><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a20de41137cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>