<?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 Unnat Singh on Medium]]></title>
        <description><![CDATA[Stories by Unnat Singh on Medium]]></description>
        <link>https://medium.com/@unnatsingh?source=rss-63a23557163b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*p0lRv5RqWjrJu8oa</url>
            <title>Stories by Unnat Singh on Medium</title>
            <link>https://medium.com/@unnatsingh?source=rss-63a23557163b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:18:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@unnatsingh/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[RL- Policy Gradient Method]]></title>
            <link>https://unnatsingh.medium.com/rl-policy-gradient-method-7ec6b64b7019?source=rss-63a23557163b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ec6b64b7019</guid>
            <category><![CDATA[reinforce]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Unnat Singh]]></dc:creator>
            <pubDate>Sat, 08 Jun 2019 03:09:21 GMT</pubDate>
            <atom:updated>2019-06-08T03:09:21.146Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are Policy Gradient Methods?</h3><p>Policy gradient methods are a subclass of policy-based methods.</p><ul><li>It estimates the weights of an optimal policy through gradient ascent by maximizing expected cumulative reward which an agent gets after taking optimal action in a given state.</li><li>Reinforcement learning is divided into two types of methods:</li></ul><ol><li>Policy-based method (Policy gradient, PPO and etc)</li><li>Value-based method (Q-learning, Sarsa and etc)</li></ol><p>In the value-based method, we calculate Q value corresponding to every state and action pairs. And the action which is chosen in the corresponding state is the action which has maximum Q-value in the given state. So in the value-based method, we first calculate Q-value and then according to this value we choose the action which maximizes the Q-value and at the same time we choose the action and also update the Q-table.</p><p>And equation for finding Q-value changes on the approach which we take, basically there are two approaches:</p><ol><li>Monte Carlo (high variance, no bias)</li><li>Temporal Difference (low variance, biased)</li></ol><p>I will cover this in more detail in another article, in this article I will give you the equations for both Monte Carlo and Temporal Difference methods for calculating Q values.</p><h4>Monte Carlo Method:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*D74heWaqy89VWMmYl9_k3Q.png" /><figcaption>Monte-Carlo method</figcaption></figure><h4>Temporal Difference Method:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*aM1w55RuWM5SEaKA3e4zPQ.png" /><figcaption>Temporal Difference method</figcaption></figure><p>This is what a Q-table looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*7z_Iew2uwi4YDMc5zwGsiA.png" /><figcaption>Q-table</figcaption></figure><p>In each state (represented in rows) the optimal action is the action(represented in columns) which has the highest value in that state. In state one, it is up arrow and state two its right arrow and in state three it’s again the up arrow.</p><h3>Value-Based Method</h3><ul><li>Interaction → Optimal Value Function q* → optimal policy π*</li><li>Value Function is represented in the form of a table, where rows correspond to states and column corresponding to an action.</li><li>And then we use the above table to build an optimal policy.</li><li>But what about the environment with much<strong> larger state space</strong>?</li><li>So we investigated how to represent the optimal action-value function with a neural network which formed the basis of the <strong>Deep Q Learning</strong> algorithm.</li><li>Input dimension: state dimension, Output dimension: action dimension.</li><li>But the important message here is that both cases, whether we use the table for small state spaces or a neural network for much larger state spaces, we had to first <strong>estimate </strong>optimal action-value before we could tackle the optimal policy.</li></ul><p><strong>Can we directly find the optimal policy without worrying about a value function at all?</strong></p><ul><li>Yes! → Policy-based methods.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*qim-9Sxvol4-mVNgws8_MA.gif" /><figcaption>OpenAI Gym Documentation: <a href="https://gym.openai.com/docs">https://gym.openai.com/docs</a></figcaption></figure><h4>Policy Function Approximation</h4><ul><li>How might we approach this idea of estimating an optimal policy?</li><li>Let’s take cart pole example</li><li>In this case, the agent has two actions and dimension of state space is four.</li><li>It can push the cart either left or right.</li><li>At each time step agents picks one of two actions.</li><li>And we can construct a neural network that approximates the policy, that accepts the state as input and returns the probability of selecting each action in that state.</li><li>So if there are two possible actions, the output layer will have two nodes.</li><li>The agent uses this policy to interact with the environment by just passing the most recent state to the network.</li><li>It outputs the action probability and then the agent samples from those probabilities to select an action in response.</li><li>Our objective then is to determine appropriate values for the network weights so that each state that we pass into the network it returns the <strong>action probabilities</strong> where the optimal action is most likely to be selected.</li><li>This will help agent with its goal to maximize expected return.</li><li>This is an iterative process where weights are initially set to random values.</li><li>Then, as the agent interacts with the environment and learns more about the strategies which are best for maximizing the reward.</li></ul><h4>More on the policy</h4><ul><li>The agent can use a simple neural network architecture to approximate a stochastic policy. The agent passes the current environment state as input to the network, which returns action probabilities. Then, the agent samples from those probabilities to select an action.</li><li>The same neural network architecture can be used to approximate a <strong>deterministic policy.</strong> Instead of sampling from the action probabilities, the agent need only choose the greedy action.</li><li><strong>Softmax</strong> as the output activation function.</li></ul><h4>Why Policy-Based Methods?</h4><ul><li>Simplicity</li><li>Stochastic Policies</li><li>Works in continuous Action Space</li><li>Deterministic: π: s → a</li><li>Stochastic: π(s,a) = P[a|s]</li><li>Formulating policy in this manner allows us to makes such generalization where possible and focus more on the complicated regions of state space.</li><li>One of the main advantages of policy-based methods over value-based methods is that they can learn true stochastic policies.</li></ul><h4>Alias State</h4><ul><li>Alias states are identical state, according to state features (which can be limited, and in reality are not identical) and have different optimal actions, but the agent cannot differentiate between the states.</li><li>The best action that can be taken in these states is equiprobable random action — which value-based methods are not able to do.</li><li>Because in the value-based method, the method or technique by which we take random action is <strong>epsilon-greedy method</strong> and after training a value based method, our epsilon is small, because of this we can’t take anymore random action with a smart agent!</li><li>So the only way to take equiprobable random actions is through policy-based methods.</li></ul><h4>Continuous action space</h4><ul><li>Policy-based methods are well suited for continuous action spaces.</li><li>When we use a value-based method even with the function approximator (neural network for continuous state and action), our output consists of a value for each action.</li><li>Now if acting space is continuous, then the max operation turns out to be an <strong>optimization problem</strong> itself.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*1Po-XJWiFbFEIVk8Y8KIuQ.png" /><figcaption>q-learning update step (value based method) this is TD update</figcaption></figure><ul><li>It’s like trying to find global maximum of a continuous function which is non-trivial.</li></ul><h3>The Big Picture</h3><p>Before digging into the details of policy gradient methods, we’ll discuss how policy-gradient work at a high level.</p><pre>LOOP:<br>Collect an episode.<br>Change the weights of the policy network:<br>      if WON, increase the probability of each (state,action) combination.<br>      if LOST, decrease the probability of each (state,action) combination.</pre><h4>Summary</h4><ol><li>For each episode, if the agent won the game, we’ll amend the policy network weights to make each (state, action) pair that appeared in the episode to make them more <strong>likely</strong> to <strong>repeat</strong> in a future episode.</li><li>For each episode, if the agent lost the game, we’ll change the policy network weights to make it less likely to repeat the corresponding (state, action) pairs in the future.</li></ol><h4>Connections to supervised learning</h4><p>Policy gradient methods are very similar to supervised learning.</p><p>The important difference between Policy Gradient and Supervised Learning</p><ul><li>One important difference is that when we do image classification (supervised learning). Typically we work with a dataset that <strong>doesn’t change over time</strong>(means for an image when we are training the<strong> label will be same</strong> every time whenever we are passing it through neural network unlike Policy Gradient in Reinforcement Learning).</li><li>However, in the reinforcement learning setting. The dataset varies by episode.</li><li>So we use policy to collect an episode, that gives us a dataset or a bunch of matched state action pairs and then we use that dataset once to do our batch of updates to neural network weights.</li><li>After these updates are done we discard the datasets and then collect a new set of data(another episode).</li><li>So dataset is changing continuously, it’s highly likely that we will experience a situation where the dataset has multiple conflicting opinions about what the best output should be for input, or in other words, what the best action is to take from a game state.</li><li><strong>It like the same image appears in supervised learning with different labels.</strong></li><li>So this does make our current situation more complex.</li></ul><h3>Problem Setup</h3><p>We’re now ready to get started with rigorously defining how policy gradient methods work.</p><h4>Trajectory</h4><ul><li>The first thing we need to define is the <strong>Trajectory</strong>.</li><li><strong>Trajectory</strong> = state-action sequence</li><li>𝑠0,𝑎0,𝑟1,𝑠1,𝑎1,𝑟2,𝑠2,𝑎2,𝑟3,𝑠3,…</li><li>But actually, a trajectory is a little bit more <strong>flexible</strong> because there is no restriction on its <strong>length</strong>.</li><li>So, it can correspond to a full episode or just a small part of an episode.</li><li>We denote <strong>trajectory</strong> length with <strong>H</strong>, where <strong>H</strong> stands for <strong>Horizon</strong> and denote trajectory with τ.</li><li>Then, the sum reward from the Trajectory is written as R(τ).</li><li>Our goal is to find weights θ of the neural network that maximize expected return.</li><li>One way of accomplishing this is by setting the weights of the neural network so that on average, the agent experience trajectories that yield a high return.</li><li>We denote the expected return by U and it’s a function of θ.</li><li>We want to find the value of θ that maximizes U.</li></ul><h4>Expected Return</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*QXELxXAn5ndaR9RyzdUcPQ.png" /><figcaption>expected return</figcaption></figure><p><strong>Important note</strong></p><p>U(θ) = Σ P(τ;θ)R(τ)</p><p>To see how it corresponds to the expected return, note that we’ve expressed the return R(τ) as a function of the trajectory τ. Then, we calculate the weighted average (where the weights are given by P(τ;θ)) of all possible values that the return R(τ) can take.</p><h4>Why Trajectories?</h4><p>We may be wondering: why are we using trajectories instead of episodes? The answer is that maximizing expected return over trajectories (instead of episodes) lets us search for optimal policies for both episodic and continuing task!</p><p>That said, for many episodic tasks, it often makes sense to just use the full episode.</p><h3>REINFORCE</h3><p>We’ve learned that our goal is to find values of the weights θ in the neural network that maximizes the expected return U.</p><p><strong><em>U(θ) = Σ P(τ;θ)R(τ)</em></strong></p><p>where τ is an arbitrary trajectory. One way to determine the value of θ that maximizes this function is through <strong>gradient ascent</strong>. This algorithm is closely related to <strong>gradient descent</strong>, where the difference is that:</p><ul><li>gradient descent is designed to find the <strong>minimum</strong> of a function, whereas gradient ascent will find the <strong>maximum</strong>, and</li><li>gradient descent steps in the direction of the <strong>negative gradient</strong>, whereas gradient ascent steps in the direction of the <strong>gradient</strong>.</li></ul><p><strong>Our update step for Gradient Ascent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*NjipZlyeeklKdQlmbt4GLQ.png" /><figcaption>gradient ascent</figcaption></figure><ul><li>As we’ve learned, we can express the expected return as a probability-weighted sum, where we take into account the probability of each possible trajectory and, the return permits trajectory.</li><li>GOAL: find θ maximizes the expected return.</li><li>One way to do that is by Gradient Ascent, where we iteratively take small steps in the direction of the gradient.</li><li><strong>Gradient Descent</strong> → minimizes the function:</li><li><strong><em>θ ← θ - αδU(θ)</em></strong></li><li><strong>Gradient Ascent</strong> → maximizes the function:</li><li><strong><em>θ ← θ +αδU(θ)</em></strong></li><li>To apply above-mentioned methods we need to calculate the gradient.</li><li><strong>Now, we won’t be able to calculate the exact value of the GRADIENT since that is computationally too expensive.</strong></li><li>It’s computationally expensive <strong>because</strong>, in order to calculate the gradient exactly, we’ll have to consider every possible trajectory.</li><li>To calculate the gradient <em>δU(θ)</em>, we have to consider every possible trajectory.</li><li>To <strong>estimate</strong> the gradient <em>δU(θ), </em>we have to consider a <strong>few trajectories</strong>.</li><li>Specifically, we’ll use the policy to collect trajectories.</li><li>Use the policy π(<em>θ</em>) to collect trajectories τ(1),τ(2), ….., τ(m).</li><li>Remember, any trajectory is just the sequence of states and action and we’ll use this notation refers to the ith trajectory.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*oZTMdxjsLMwsm707wFrqgQ.png" /><figcaption>trajectory</figcaption></figure><ul><li>Then we will use this trajectory to estimate the gradient <em>δU(θ).</em></li></ul><h3><strong>BIG SHOT EQUATION FOR CALCULATING THE GRADIENT!!</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*Nt7zlQLO9jFmXXz2qji9pA.png" /></figure><ul><li>One important thing to note here is an estimate for the gradient which we refer to as g_hat is equal to the consolidation of information from the M trajectories.</li><li>And I’m not deriving this equation in this article.</li></ul><h4>Recap the big picture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*DRHXYClPq3jAsf62jeA5DA.png" /></figure><h4>Diving deep into Gradient Equation</h4><p>Equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*Nt7zlQLO9jFmXXz2qji9pA.png" /></figure><h4>Initial Idea</h4><ul><li>Change the Policy weight to accommodate the following condition:</li><li>If <strong>WON, </strong>increase the probability of each (state, action) combination (sequence) in the trajectory which ended in winning.</li><li>If <strong>LOST</strong>, decrease the probability of each (state, action) combination in the trajectory which combination (sequence) ended in loss.</li></ul><h4>Initial Assumption (simplifying the problem)</h4><ol><li>Only one trajectory for calculating the gradient (for weights update)</li><li>In terms of our gradient equation m=1.</li><li>And trajectory τ corresponds to the full episode.</li></ol><p><strong>Now the equation for the simplified problem:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*8gwOeEwDOSxsXxjyICKm_w.png" /></figure><ul><li>We currently assuming that we have calculated the full episode which we referred as to τ.</li><li>R(τ) is just a cumulative reward from that trajectory.</li><li>Now let’s take an example environment, in which the agent has to cross a road now the environment gives a reward of +1 if the agent crosses the road and -1 otherwise.</li><li>And τ is just a sequence of states and actions.</li><li>And π<em>θ(at|st) term looks at the probability of that the agent selects action at in states st.</em></li><li>And π<em>θ refers to a policy which agent follows and policy depends on the weight θ.</em></li><li>Then this full calculation here takes the gradient of the log of that probability.</li><li>This will tell us how we should change the weights of the policy theta if we want to increase the log probability of selecting action at and state st.</li><li>Specifically, if we nudge the weight in the direction of gradient then we increase the log probability of selecting that action in that state space and if we step in the opposite direction will decrease the log probability of selecting that action in that space.</li></ul><h4>Basic Working</h4><ul><li>The basic idea here is that if <strong>WON</strong>, then cumulative reward +1 so gradient is positive it will nudge weight in the direction of gradient and hence will increase the probability of taking that action in that state and if <strong>LOST</strong>, cumulative reward -1 so gradient is negative it will nudge the weight in direction opposite to the gradient and hence minimize it, will decrease the probability of taking that action in that state.</li></ul><h4>Implementation of Policy Gradient with PyTorch</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20af875f376f4f14861fb89b099e89ca/href">https://medium.com/media/20af875f376f4f14861fb89b099e89ca/href</a></iframe><h4>What’s Next?</h4><p>In this article, we’ve learned about the REINFORCE algorithm, which was illustrated with a toy environment with a discrete action space. But it’s also important to mention that REINFORCE can also be used to solve the environment with continuous action spaces.</p><p>For an environment with a continuous action space, the corresponding policy network could have an output layer that parameterized a <strong>continuous probability distribution.</strong></p><p>For instance, assume the output layer returns the mean μ and variance σ2 of a normal distribution.</p><p>Then in order to select an action, the agent needs only to pass the most recent state <em>st </em>as input to the network, and then use the output mean μ and variance σ2 to sample from the distribution at — N(μ,σ2)</p><p>This should work in theory, but it’s unlikely to perform well in practice. To improve performance with continuous action space, we’ll have to make some small modification to the REINFORCE algorithm, and I’ll cover this in the upcoming article.</p><h3>Summary</h3><h4>What are Policy Gradient Methods?</h4><ul><li>Policy-based methods are a class of algorithm that search directly for the optimal policy, without simultaneously maintaining value function estimation.</li><li>Policy gradient methods are a subclass of policy-based methods that estimate the weight of an optimal policy through gradient ascent.</li><li>In this article, we represent the policy with a neural network, where our goal is to find weights θ of the network that maximize expected return.</li></ul><h4>Τhe Big Picture</h4><ul><li>The policy gradient method will iteratively amend the policy network weights to:</li><li>make (state, action) pairs that resulted in positive return more likely, and</li><li>make (state, action) pairs that resulted in negative return less likely.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*KULc2S-yPy6f2npSYbsraw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ec6b64b7019" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Q-Network with Pytorch]]></title>
            <link>https://unnatsingh.medium.com/deep-q-network-with-pytorch-d1ca6f40bfda?source=rss-63a23557163b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1ca6f40bfda</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Unnat Singh]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 13:34:45 GMT</pubDate>
            <atom:updated>2021-05-17T14:34:31.134Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F11wlGW9Ai5Hxy8%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Frl-11wlGW9Ai5Hxy8&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F11wlGW9Ai5Hxy8%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="316" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d6c78971c9ee77b805e09d4f2d9c07e/href">https://medium.com/media/2d6c78971c9ee77b805e09d4f2d9c07e/href</a></iframe><h4>DQN</h4><ul><li>A deep neural network that acts as a function approximator.</li><li><strong>Input</strong>: Current state vector of the agent.</li><li><strong>Output</strong>: On the output side, unlike a traditional reinforcement learning setup where only one Q value is produced at a time, The Q network is designed to produce a Q value for every possible state-actions in a single forward pass.</li><li>Training such a network requires a lot of data, but even then, it is not guaranteed to converge on the optimal value function. In fact, there are situations where the network weights can oscillate or diverge, due to the <strong>high correlation between action and states</strong>.</li><li>This can result in a very unstable and ineffective policy we can solve this by:</li><li><strong>Experience Replay</strong></li><li><strong>Fixed Q-Target</strong></li></ul><h4>Experience Replay</h4><ul><li>The idea of experience replay and its application to training the neural network isn’t new.</li><li>It was originally proposed to make more efficient use of observed experiences.</li><li>Consider the basic online Q-Learning algorithm where we interact with the environment and at each time step, we obtained a state action reward next state tuple,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*L82G665n221b9ARzKKI8AQ.png" /></figure><ul><li>we learn from it and discard it.</li><li>Moving on the next tuple in the following time step.</li><li>We could possibly learn more from these experienced tuples if we store them somewhere.</li><li>Moreover, some states are pretty rare to come by and some action can be pretty costly, so it would be nice to <strong>recall</strong> such experiences.</li><li>That is exactly what a replay buffer allows us to do.</li></ul><h4>Replay Buffer</h4><ul><li>We store each experience tuple in this buffer as we are interacting with the environment and then sample a small batch of tuples from it in order to learn.</li><li>As a result, we are able to learn from individual tuples multiple times, recall rare occurrences, and in general make better use of our experience.</li></ul><h4>Another Problem that replays buffer solves:</h4><ul><li>This what DQN takes advantage of:</li><li>If you think about the experiences being obtained, we realize that every action A_t affects the next state S_t+1 in some way, which means that a sequence of experienced tuples can be highly correlated.</li><li>A naive Q-Learning approach that learns from each of these experiences in sequential order runs the risk of getting swayed by the effect of this correlation.</li><li>With experience replay, can sample from this buffer at random.</li><li>It doesn’t have to be in the same sequence as we stored the tuples.</li><li>This helps break the correlation and ultimately prevents action values from oscillating or diverging catastrophically.</li></ul><p><strong>Example to show why we need to break the correlation between subsequent experience tuple</strong></p><p>Tennis Example:</p><ul><li>Practising forehand, learning to play tennis.</li><li>More confident with forehand shot than backhand.</li><li>I hit the ball straight, the ball comes straight back to my forehand.</li><li>Now, if I were an online Q-Learning agent learning to play, this is what I might pick up.</li><li>When the ball comes to my right, I should hit with my forehand less certainly at first but with increasing confidence as I repeatedly hit the ball.</li><li>I’m learning to play forehand pretty well <strong>but not exploring the rest of the state space.</strong></li><li>This could be addressed by Epsilon-Greedy policy action randomly with small chances.</li><li>So I try different combinations of states and actions and sometimes I make mistakes, but I eventually figure out the best overall policy.</li><li>Use a forehand shot when the ball comes to my right and a backhand when it comes to my left.</li><li>This works fine with simplified state space with just two discrete states.</li></ul><p><strong>Continuous state-space — &gt; Problem</strong></p><ul><li>But when we consider a continuous state space things can fall apart. Let’s see how</li><li>First, the ball can actually come anywhere between the extreme left and extreme right.</li><li>If I discretized this range into buckets I will have too many buckets (too many possibilities).</li><li>What if I end up learning a policy with holes in it. For example states or situation that we may not have visited during practice.</li><li>Instead, it makes more sense to use a function approximator like a linear combination of (RBF kernels or a Q-network) that can generalize my learning across space.</li><li>Now, every time the ball comes to my right and I successfully hit a forehand shot, my value function changes slightly.</li><li>What happens when I learn while (processing each experience tuple in order)</li><li>For instance, if my forehand shots are fairly straight, I likely get back the ball around the same spot.</li><li>This procedure a state very similar to the previous one, so I use my forehand again and if it is successful it reinforces my belief that the forehand is a good choice.</li><li>I can easily get trapped in this cycle.</li><li>Ultimately, if I don’t see too many examples of the ball coming to my left for a while, the probability of the forehand shot become greater than the backhand across the entire state space.</li><li>My policy would then be to choose forehand regardless of where I see the ball coming.</li></ul><h4>Fix it</h4><ul><li>The first thing I should do is stop learning while practising.</li><li>This time is the best spend in trying out different shots playing little randomly and thus exploring the state space.</li><li>It becomes important to remember my interactions, what shot was well in the given situations, etc.</li><li>When I take a break or when I am back home or resting, that’s a good time to recall this experience and learn from them.</li><li>The main advantages are that now I have a more comprehensive set of examples.</li><li>I can call random experience tuple from the buffer and learn different shot in a different region.</li><li>After this, with this learned experience, I will again play and collect more experience tuple and learn from them in batches.</li><li><strong>Experience replay</strong> can help us to learn a more robust policy, one that is not affected by the inherent correlation present in the sequence of observed experience tuples.</li></ul><h4>Summary</h4><p>When the agent interacts with the environment, the sequence of experienced tuples can be highly correlated. The naive Q-Learning algorithm that learns from each of these experience tuples in sequential order runs the risk of getting swayed by the effect of this correlation. By instead keeping track of the replay buffer and using experience replay to sample from the buffer at random, we can prevent action values from oscillating or diverging.</p><p>The replay buffer contains a collection of experience tuples [current state, action, reward, next state]. These tuples are gradually added to the buffer as we are interacting with the environment.</p><p>The act of sampling a small batch of tuples from the replay buffer in order to learn is known as experience replay. In addition to breaking harmful correlations, experience replay allows us to learn more from individual tuples multiple times, recall rare occurrences, and in general make better use of our experience.</p><h4>Fixed Q-Targets</h4><ul><li>Experience replay helps us address one type of correlation. That is between consecutive experience tuples.</li><li>There is another kind of correlation that Q-Learning is susceptible to:</li><li>The main idea of introducing fixed Q targets is that both labels and predicted values are functions of the same weights.</li><li>All the Q values are intrinsically tied together through the function parameters.</li><li>Doesn’t experience replay take care of this problem?</li><li>Well, it addresses a similar but slightly different issue.</li><li>There we broke correlation effects between consecutive tuples by sampling them randomly out of order.</li><li>Here, the correlation between the target and the parameters we are changing.</li></ul><h4>Q-Learning Update</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtGQt--kMq3K7dwzSp4kcg.png" /></figure><h4>Fixed Target</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*rPsXbotOWxbtikiwjYSTzA.png" /></figure><ul><li>The fixed parameters indicated by a w minus are basically a copy of w that we don’t change during the learning step.</li><li>In practice, we copy w into w minus, use to generate targets while changing w for a certain number of learning steps.</li><li>Then, we update w minus with the latest w, again, learn for a number of steps and so on.</li><li>This decouples the target from the parameters, makes the learning algorithm much more stable, and less likely to diverge or fall into oscillations.</li></ul><h4>Summary</h4><ul><li>In Q-Learning, <strong>we update a guess with a guess</strong>, and this can potentially lead to harmful correlations. To avoid this, we can update the parameters <strong>w</strong> in the network to get the current Q value for the current state and action and w- to get the target q value for the next state and action.</li></ul><h3>DQN — Implementation</h3><h4>Model Architecture</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5f6d2f39b7b4ad1424207caaf6c03ef/href">https://medium.com/media/e5f6d2f39b7b4ad1424207caaf6c03ef/href</a></iframe><h4>DQN Agent</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/568191a025db699a610194ae0eaae964/href">https://medium.com/media/568191a025db699a610194ae0eaae964/href</a></iframe><h4>Train the Agent with DQN</h4><p>Run the code below to train the agent from scratch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2348e2033f7c473ef85307601e4c471/href">https://medium.com/media/a2348e2033f7c473ef85307601e4c471/href</a></iframe><h4>Watch a Smart Agent!</h4><p>In the next code cell, we will load the trained weights from file to watch a smart agent!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f8480d1dcd069ad5d5139d274d7614/href">https://medium.com/media/c6f8480d1dcd069ad5d5139d274d7614/href</a></iframe><h4>Deep Q-Learning PipeLine</h4><ol><li><strong>Qnetwork </strong>→ Actor (Policy) model.</li></ol><ul><li>Basically maps state space to actions space, it&#39;s a neural network that works as Q-table, its input dimension is equal to dimensions of state space and output dimension is equal to action space dimensions.</li><li>We basically keep two neural networks because while training our labels and predicted values are both functions of neural network weights. To decouple the label from weights we keep two sets of neural networks weights(two networks with the same architecture) fixed Q-targets.</li></ul><p>2. <strong>dqn_agent </strong>→ it’s a class with many methods and it helps the agent (dqn_agent) to interact and learn from the environment.</p><p>3. <strong>Replay Buffer</strong> → Fixed-size buffer to store experience tuples.</p><h4>Different methods of dqn_Agent</h4><ol><li><strong>__init__ </strong>method: We initialize the state_size, action and random seed.</li></ol><ul><li>then we initialize two different q-network (qnetwork_local and qnetwork_target) one for mapping predictions and the other for mapping targets.</li><li>then we declare an optimizer and we only define this for parameters of qnetwork_local and later we will do a soft update and update the parameters for qnetwork_target using the parameters of qnetwork_local.</li><li>then we initialize the Replay buffer.</li><li>then we initialize t_step, which decides after how many steps our agent should learn from experience.</li></ul><p>2. <strong>step(self, state, action, reward, next_state, done)</strong></p><ul><li>this method decides whether we will train(learn) the network actor (local_qnetwork) and fill the replay buffer or we will only fill the replay buffer.</li><li>we will only learn from the experiences if the length of replay buffer is greater than batch_size and t_step is multiple of a number(of our choice, say after this many steps we want our agent to learn (for e.g. 40 iterations)).</li></ul><p>3. <strong>learn(self, experience, gamma)</strong></p><ul><li>this step is equivalent to the step in qlearning where we update the qtable (state-action value) for a state (S) after taking corresponding action (A)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*Tg9nQBMImAD0xMdyS5u0XA.png" /></figure><ul><li>But instead of using the above equation, in DQN we use the neural network to map state-space which is continuous so we have a non-linear function approximator for mapping the state space and then we do backpropagation on our neural network to get the new update for qvalues.</li><li>And our target is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*asYR5kZ31g9RJQ5pWU0iag.png" /></figure><ul><li>where Q[nextState, A, w_minus] is the output from qnetwork_target, the dimension of this [batchSize, dimensions of action space] so according to this we define the architecture of our neural network, we do the following in Pytorch to get the target/labels.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06624c281631bd481bf288066309ee8d/href">https://medium.com/media/06624c281631bd481bf288066309ee8d/href</a></iframe><ul><li>In above using the max method along the 1st dimension (among actions) our dimensions will be [batch_size] so to make it a dimension of (batch_size,1) for Pytorch operations we have to use unsqueeze(1) method.</li><li>The states which we get from replay buffer has dimensions (batch_size, state_dimension) and one important thing to note here is along batch_size we have the different state at random order because of Replay Buffer (we have broken the <strong>correlation of sequence</strong>)</li><li>And this implementation (1- done)*labelsnext makes sure that there is no next state after terminating state.</li><li>After passing this state from qnetwork_local our output’s dimension will be (batch_size, actionSpace dimensions) so in the experience tuple (state, action, reward, next_state, done) we have action corresponding to the current state, so here we only want qvalue to that corresponding action which was there in the experience tuple and we can get that with the following command:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaca38b32daa9423b36aac6dff17c18b/href">https://medium.com/media/eaca38b32daa9423b36aac6dff17c18b/href</a></iframe><ul><li>One important thing here to note is Q-table is a table that contains all possible states in the rows and all possible actions in the columns, in a particular row (state) whichever action has the highest value, that is the preferred action in that state that’s how Q-learning(Sarsamax) works, but for this to work state space and action space should be discrete but in our case, the state space is continuous and have discrete action space, so <strong>we use a neural network to approximate the Q-table</strong>.</li><li>So from the above code snippet, we can get our predicted value which has a dimension of [batch_size, 1].</li><li>Now we can compute the loss and then we can use backpropagation to update our weights and hence is equivalent to updating of <strong>state action value(Q-table)</strong>.</li><li>And then we do the <strong>soft update</strong> the gradient of <strong>qnetwork_target</strong>, remember we are only training one set of weights that is of qnetwork_local, so we need a way to update the weights of qnetwork_target and with those weights, we are hoping that our target too improve after each step as we are improving our predicted value, and the main idea we are using two networks is because we want to decouple both targets and predicted value from each other as both are functions of same weights, and with fixed q-target, we are making sure that our ta<strong>rget and predicted value are functions of a different set of weights. So our network doesn’t oscillate.</strong></li></ul><p>4. soft_update(local_model, target_model, tau)</p><ul><li>One important thing to note is that when we are passing <em>next-state</em> to the <em>qnetwork_target</em> we are not calculating the gradient for each pass because we have wrapped with <em>torch.no_grad() </em>and there is no need of calculating the gradient.</li><li>tau decides how much weightage will be given to the <strong>qnetwork_local</strong> and <strong>qnetwork_target</strong> weights respectively.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5ce93a728eec6d9d3468b182b7bdaa0/href">https://medium.com/media/d5ce93a728eec6d9d3468b182b7bdaa0/href</a></iframe><p>5. act(state, eps=0)</p><ul><li>Returns the action for the given state as per current policy.</li><li>First, we change our model in evaluation mode.</li><li>then we change the state tensor from<em> NumPy </em>to <em>torch.tensor</em> and then <em>.unsqueeze(1) </em>method is used to add a dimension along the batch_size, because in Pytorch we can only pass an input when it has a dimension that addresses the <em>batch_size</em>.</li><li>And then we pass the state and get the corresponding action and note that we have used qnetwork_local.</li><li>And then we have an implementation of <strong>greedy action selection </strong>because we want to explore more random actions. So that the agent gets more experience and <strong>eps </strong>hyperparameter control this process.</li><li>And as we know we decrease the <strong>eps</strong> gradually as our agent becomes smarter so we want to decrease the <strong>exploration </strong>and increase<strong> exploitations</strong>. Sounds fancy!</li></ul><h4>Deep Q-Learning Improvements</h4><p>Several improvements to the original Deep Q-Learning algorithm have been suggested.</p><ol><li><strong>Double DQN</strong></li></ol><ul><li>Deep Q-Learning tends to overestimate action values. Double Q-Learning has been shown to work well in practice to help with this.</li></ul><p>2. <strong>Prioritized Experience Replay</strong></p><ul><li>Deep Q-Learning samples experience transition <strong>uniformly</strong> from a replay buffer.</li><li>Prioritized experience replay is based on the idea that the agent can learn more effectively from some transition than others, and the more important transitions should be sampled with higher probability.</li></ul><p>3.<strong> Duelling DQN</strong></p><ul><li>Currently, in order to determine which states are (or are not) valuable, we have to estimate the corresponding action value for each action. However, by replacing the traditional Deep Q-Network (DQN) architecture with a duelling architecture, <strong>we can assess the value of each state, without having to learn the effect of each action.</strong></li></ul><h4><strong>Double DQN</strong></h4><ul><li>The basic idea here is while training the agent in the early stages when the agent is naive for target updating, we use the action that <strong>maximizes</strong> the <em>Q-value[next_state]. </em>But in the early stage, this is a noisy approximation so we tend to <strong>overestimate the Q-value</strong>.</li><li>To overcome the overestimation problem we can use both the networks the local and target as we have two sets of weights, so we can cross-validate it with both sets of weights and minimize the overestimation problem.</li><li>We select the best action using one set of parameters <strong>w</strong> (<em>qnetwork_local</em>), but evaluate it with the different set of parameters <strong>w-</strong> (<em>qnetwork_target</em>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*A9LFS3PTeUNYKPVM3t3XJQ.png" /></figure><ul><li>Its basically likes having two separate function approximator that must agree on the best action.</li><li>If <strong>w </strong>picks an action that is not best according to <strong>w-</strong>, then Q-value returned is not that high.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16693decc0762e852e050af2b25d1508/href">https://medium.com/media/16693decc0762e852e050af2b25d1508/href</a></iframe><h4>Trained agent Example</h4><p>In my Udacity Deep Reinforcement Learning nanodegree, I trained an agent to navigate in large grid world and collect bananas and it was trained using DQN algorithm.</p><p>For this project, you will train an agent to navigate (and collect bananas!) in a large, square world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*FdfnxhJS1V3Dd0HU.gif" /></figure><p>A reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana. Thus, the goal of your agent is to collect as many yellow bananas as possible while avoiding blue bananas.</p><p>The state space has 37 dimensions and contains the agent’s velocity, along with the ray-based perception of objects around the agent’s forward direction. Given this information, the agent has to learn how to best select actions. Four discrete actions are available, corresponding to:</p><ul><li>0 - move forward.</li><li>1 - move backwards.</li><li>2 - turn left.</li><li>3 - turn right.</li></ul><p>The task is episodic, and in order to solve the environment, your agent must get an average score of +13 over 100 consecutive episodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pf9sX66sSyO___oB84ccsw.png" /></figure><p>Thank you! Happy Learning to everyone!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1ca6f40bfda" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>