<?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 Cheng Xi Tsou on Medium]]></title>
        <description><![CDATA[Stories by Cheng Xi Tsou on Medium]]></description>
        <link>https://medium.com/@chengxi600?source=rss-49de4e2f5a53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YrKyylMbSRsJf-DL.jpg</url>
            <title>Stories by Cheng Xi Tsou on Medium</title>
            <link>https://medium.com/@chengxi600?source=rss-49de4e2f5a53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:45:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chengxi600/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[Policy Optimizations: TRPO/PPO]]></title>
            <link>https://medium.com/geekculture/policy-optimizations-trpo-ppo-cf9479407df1?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf9479407df1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Fri, 17 Sep 2021 20:50:22 GMT</pubDate>
            <atom:updated>2021-09-18T20:29:24.736Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will be talking about policy optimization methods from the papers <a href="https://arxiv.org/pdf/1502.05477.pdf">Trust Region Policy Optimization (Schulman et al. 2015)</a> and <a href="https://arxiv.org/pdf/1707.06347.pdf">Proximal Policy Optimization Algorithms (Schulman et al. 2017)</a>. I will then briefly go over the Trust Region Policy Optimization method and implement two types of Proximal Policy Optimization methods: adaptive KL (Kullback-Leibler) penalties to the surrogate objective and clipped surrogate objective.</p><h3><strong>Introduction</strong></h3><p>In a traditional policy gradient method, we sample a trajectory of states, actions, and rewards, then update the policy using the sampled trajectories. While this method is great and solves basic control problems, the algorithm tends to be unstable and is inconsistent in solving an environment. A problem is that as we are updating the policy, the distribution of the inputs and outputs of the approximated policy distribution will change, resulting in instability.</p><p>Another problem is that when performing gradient ascent, we do not guarantee that the policy is being updated in the right direction. The advantage function is initialized randomly, so updating the policy with respect to the advantage can cause degradation instead of improvement. A solution to this would be to create some sort of safe distance between the old policy and the new policy such that updating the policy will guarantee monotonic improvement and not diverge.</p><h3>Trust Region Policy Optimization</h3><p>Let’s start by introducing the concept of trust regions from the TRPO paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*J9LTPt_41KzLcIXsq3idow.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>Here, we have <em>η, </em>the expected discounted returns following policy <em>π. </em>We can use this expected discounted reward in the following identity that expresses the expected discounted returns for a policy in terms of the advantage over another policy <a href="https://people.eecs.berkeley.edu/~pabbeel/cs287-fa09/readings/KakadeLangford-icml2002.pdf">(Kakade &amp; Langford 2002)</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*7fS4TsSjAX7AaXY62B1gqw.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>We use the standard definition of advantage function <em>A</em>, where <em>A(s, a)= Q(s, a)- V(s), </em>with <em>Q</em> being the value of taking action a in state<em> s</em> and <em>V</em> being the value of state s. The identity calculates the advantage of choosing policy π’ over π by calculating the advantage under π distribution while sampling from the π’ policy. Then, we rewrite this identity to be the sum over states and actions instead of timesteps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*EV5zi816UaRKVEIeTPP9HQ.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>In the last line, we define <em>ρ_π(s)</em> to be the discounted visitation frequencies for state s under policy <em>π </em>so we can get rid of the timesteps. From this equation, we can see that as long as the advantage is non-negative for all states <em>s</em>, then updating the policy from π → π’ will guarantee a non-negative improvement. The paper then introduces a local approximation of this identity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*eiyAu549TTjiym9VCAqAPQ.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>Instead of sampling state transitions from the new policy, we use the distribution from the old policy. This is because calculating the new policy’s discounted visitation frequencies is too complex as you would need to simulate the collected trajectories again on the new policy. With this approximation, we can just simply use the collected trajectories before updating the policy.</p><p>Since this is a local approximation, this does not mean that <em>L</em> can globally approximate <em>η</em>. The paper derives a lower bound, or trust region for which the approximation is accurate so that we know how big of a step we can take towards the new policy where the approximation is viable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*yBYH1Q76ZiVgmTB1P23oWw.png" /><figcaption>Taken from UWaterloo CS885 Lecture 15a</figcaption></figure><p>Kakade and Langford derived the lower bound as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*IrTiCG0L5Ftj3usegu-5rQ.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>The penalty uses the function D_KL, which is the Kullback-Leibler divergence between π and π’, used to measure the distance between two distributions for an arbitrary variable <em>x</em>. Here’s a visual of the local approximation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*AFknXIrrwiHMorkAQWVrmg.png" /><figcaption>Taken from UWaterloo CS885 Lecture 15a</figcaption></figure><p>Now with our surrogate function and trust-region lower bound, we can come up with an algorithm that guarantees non-decreasing expected return η:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*xBjmZjR2sTcVct5f2NN8Tg.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>We know that this algorithm guarantees improvement by looking at the surrogate objective with the derived lower bound. If we improve the surrogate function on the right-hand side, that will mean we improve the expected return η. Here, we maximize the surrogate objective at every iteration, so we know that the new policy’s surrogate objective will be at least just as good, so the expected discounted returns will have a non-negative improvement.</p><p>The TRPO paper then proposes a more practical way to implement the algorithm when we parameterize the policy π. If we use the penalty constant C as proposed in algorithm 1, the update steps will be very small. Instead, we will maximize the surrogate objective without a penalty, which is the derived lower bound to compensate for the local approximation, and use a trust-region constraint on the KL divergence between the old and new policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*Zo-9EmRZQOwY8cXomK9Y4A.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>In practice, it is impractical to guarantee that the KL divergence follows the constraint at every possible state, so instead, we use an approximation where as long as the average KL divergence is within the constraints, it is fine. Next, let’s try to rewrite the surrogate objective function. Recall that this is the current optimization problem we are trying to solve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*oWNjwGQ92MEttkQ9CKF96w.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>First, we can get rid of the summation of states by using an expectation that samples from the state distribution and the state visitation frequencies by using an infinite geometric sequence (1/1-γ) instead. Then, we replace the advantage function with a Q function which doesn’t change the objective as the only difference is a constant. Finally, we can get rid of the summation of actions by sampling from the action distribution and using importance sampling. Now we have the following objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*ET1t1wxKOub8JpefYCNz2w.png" /><figcaption>Trust Region Policy Optimization (Schulman et al. 2015)</figcaption></figure><p>The TRPO paper uses this objective with a Q function instead and comes up with a practical algorithm that solves the constraint problem at each iteration. I won’t go into detail about the TRPO algorithm as it is too computationally expensive and complex compared to its successor, PPO.</p><h3>Proximal Policy Optimization</h3><p>Now with the background knowledge of TRPO, we can discuss the proposed changes in the PPO paper that simplifies the constraint optimization problem in TRPO which can be complex and computationally expensive to solve. Recall the objective that TRPO tries to maximize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*fgKQ7qpt75KdCpW4bkU0Mw.png" /><figcaption>Proximal Policy Optimization Algorithms (Schulman et al. 2017)</figcaption></figure><p>Here, we are just defining <em>rₜ(θ)</em> as the importance sampling ratio between the old and new policies. The PPO paper proposed a new kind of objective: clipped surrogate objective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*i5pKzQZgqdWxKkrUHgKrPg.png" /><figcaption>Proximal Policy Optimization Algorithms (Schulman et al. 2017)</figcaption></figure><p>Without a constraint, the surrogate objective can be blown out of proportion. However, instead of using a constraint on the surrogate objective, we instead constrain the ratio between the old and new policy in the range of [1 - ϵ, 1 + ϵ], with ϵ as a hyperparameter constant that dictates how far the ratio can deviate from 1. Then, we take the minimum between the clipped and unclipped objectives. Intuitively, we can think of the clipping like this:</p><p>If the advantage is positive, we would want the ratio to be &gt;1 since we want the new policy to happen more often. The clip will then constrain the ratio under 1 + ϵ so the new policy does not stray too far away from the old policy. If the advantage is negative, we would want the ratio to be &lt;1 since we want the new policy to happen less often. The clip will then make sure the ratio is over 1 - ϵ, so the new policy does not stray too far away from the old policy.</p><p>Another kind method that the paper proposes is by using an adaptive KL penalty. Recall the derived lower bound for the deviation of the local approximation from the true expected discounted returns. Like in TRPO, we will use a penalty on the surrogate objective. However, instead of using a calculated constant C which results in small updates, we use a hyperparameter constant β. Here is the surrogate objective with the penalty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*1ODfKgDT5WRit0QwJW0Vgg.png" /><figcaption>Proximal Policy Optimization Algorithms (Schulman et al. 2017)</figcaption></figure><p>Since it&#39;s hard to choose a β that encompasses all situations, we can use an adaptive penalty instead. After several epochs of policy updates, we change the β constant under the following conditions (Let d = KL divergence between old and new policy):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*weveqViPf_EBqrxgXbmKMw.png" /><figcaption>Proximal Policy Optimization Algorithms (Schulman et al. 2017)</figcaption></figure><p>We choose a target KL divergence of our new and old policy. If the KL divergence is under our target, we can lessen the penalty on the surrogate objective. If the KL divergence is over our target, we will increase the penalty on the surrogate objective.</p><p>With the clipped surrogate objective or one with an adaptive KL penalty, we can modify the objective a bit more in practice. If we were using a neural network structure that shared its parameters between actor and critic as we need a critic to estimate advantage, we can add two more terms to the objective function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*F8PYfD61laabCZYWn2NSPQ.png" /><figcaption>Proximal Policy Optimization Algorithms (Schulman et al. 2017)</figcaption></figure><p>Here, the surrogate objective uses the clipped objective, though it works with the adaptive KL penalty as well. We have weights c1 for the value function loss (typically mean-squared error loss), and c2 for the entropy bonus S. Putting everything together, we have the PPO algorithm using an Actor-Critic structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZ2urnTSBEpGjcxhyYalTw.png" /><figcaption>Proximal Policy Optimization Algorithms (Schulman et al. 2017)</figcaption></figure><h3>Implementation</h3><p>For my implementation, I used the Actor-Critic structure with shared parameters for my training loop, computed my advantage estimates with a value network, and implemented the two optimization methods, clipped and KL adaptive penalty. Then, I trained my PPO agent using both optimization methods on the CartPole-v1 and LunarLander-v2 environments. Here’s a quick recap of the two environments.</p><p>CartPole is a classic control problem where an agent tries to balance a pole on a cart. The environment has a continuous state space with 4 variables, cart velocity/acceleration, and angular velocity/acceleration, and a discrete action space with actions push left or right. The agent is rewarded for each step the pole is balanced.</p><p>LunarLander-v2 is a rocket trajectory optimization problem where an agent tries to land a rocket on a surface. The environment has a continuous state space with 8 variables, x position, y position, horizontal velocity, vertical velocity, lander orientation angle, angular velocity, left leg touching the ground (boolean), and right leg touching the ground (boolean), and a discrete action space with actions fire main engine, left engine, right engine, and no action. The agent is rewarded for landing correctly on the surface, and within the landing pad, and penalized for fuel usage.</p><p>For my Actor-Critic network, I used the same layers as the PPO paper, with two hidden layers of 64 units and tanh activation function. Here are the hyperparameters and experiment setup I used for training the agent:</p><ul><li>γ (discount factor): 0.99</li><li>ϵ (surrogate clip): 0.2</li><li>β (initial KL penalty): 1</li><li>δ (target KL divergence): 0.01</li><li>c1 (value loss weight): 0.5</li><li>c2 (entropy weight): 0.01</li><li>k_epoch (number of training epochs in an update): 40</li><li>α_θ (actor learning rate): 0.0003</li><li>αv (critic learning rate): 0.001</li><li>total training steps: 300,000</li><li>max episode steps: 400</li><li>batch size: 1600</li></ul><p>Here’s the training history of CartPole with clipped surrogate objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*RwO6tPz_p6MhCOfNSI0sLg.png" /></figure><p>The agent was able to solve the environment in 30,000 steps with an average reward of 242.26 over 50 test runs. The training history looks a bit unstable, but I suspect this is because I didn’t do any kind of hyperparameter search. Another reason could be because of the way I computed my advantage. The PPO paper uses generalized advantage estimation (Schulman et al. 2015) to calculate the advantage, but I just subtracted a learning value baseline from the cumulative discounted returns. After training the agent again but without early stopping, the agent is able to achieve the max average score of 400 with 100,000 training steps.</p><p>I used tried to train the agent with an adaptive KL penalty but the results were inconsistent and unstable, though it was still able to solve the CartPole environment.</p><p>Next, here’s the training history and video of LunarLander with clipped surrogate objective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*TA3gMA0rOY20SX39Ffxzdg.png" /></figure><p>The agent was trained for 300,000 steps with an average reward of 142.4 over 50 test runs. As with the CartPole environment, the training history is a bit unstable due to the aforementioned factors. Although a testing score of 142.4 is not considered solved, the LunarLander is able to smoothly land on the surface and does much better than a random policy. With a hyperparameter sweep, the PPO agent should be able to achieve a solved score of over 200. Here’s a video of the agent in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*vE6GuE5A-XUwYLCSD4-AMQ.gif" /><figcaption>LunarLander-v2 trained with PPO</figcaption></figure><p>Code: <a href="https://github.com/chengxi600/RLStuff/blob/master/Policy%20Optimization%20Algorithms/PPO_Discrete.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Policy%20Optimization%20Algorithms/PPO_Discrete.ipynb</a></p><p>References:</p><ul><li><a href="https://arxiv.org/pdf/1502.05477.pdf">Trust Region Policy Optimization (Schulman et al. 2015)</a></li><li><a href="https://arxiv.org/pdf/1707.06347.pdf">Proximal Policy Optimization Algorithms (Schulman et al. 2017)</a></li><li><a href="https://cs.uwaterloo.ca/~ppoupart/teaching/cs885-spring18/slides/cs885-lecture15b.pdf">UWaterloo CS885 Lecture 15b</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf9479407df1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/policy-optimizations-trpo-ppo-cf9479407df1">Policy Optimizations: TRPO/PPO</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Deterministic Policy Gradient (DPG)]]></title>
            <link>https://medium.com/geekculture/introduction-to-deterministic-policy-gradient-dpg-e7229d5248e2?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7229d5248e2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 10:05:07 GMT</pubDate>
            <atom:updated>2021-08-26T10:16:43.813Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will be exploring the concepts following the paper <a href="http://proceedings.mlr.press/v32/silver14.pdf">Deterministic Policy Gradient Algorithms</a> (Silver et al.), implementing the algorithm COPDAC (Compatible Off-Policy Deterministic Actor-Critic) proposed in the paper, and training the agent on the continuous-control environment MountainCar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yDszF3Oecx38DznVuIWQlA.gif" /><figcaption>Taken from OpenAI gym documentation</figcaption></figure><h3><strong>Introduction</strong></h3><p>In the paper <a href="http://proceedings.mlr.press/v32/silver14.pdf">Deterministic Policy Gradient Algorithms</a>, Silver proposes a new class of algorithms for dealing with continuous action space. The paper derives the deterministic policy gradient theorem from first principles. An advantage of the deterministic policy gradient is that compared to the stochastic policy gradient, the deterministic version is simpler and can be computed more efficiently. The paper then proposes on-policy and off-policy Actor-Critic algorithms that make use of the deterministic policy gradient. The paper builds off several concepts I’ve written about such as <a href="https://medium.com/nerd-for-tech/reinforcement-learning-introduction-to-policy-gradients-aa2ff134c1b">Policy Gradients</a>, <a href="https://medium.com/geekculture/actor-critic-implementing-actor-critic-methods-82efb998c273">Actor-Critic methods</a>, and <a href="https://chengxi600.medium.com/actor-critic-off-policy-actor-critic-algorithm-cca654845558">Off-Policy Actor-Critic</a>, so I will not go into detail about them as they come up.</p><h3>Deterministic Policy Gradient Theorem</h3><p>Similar to the stochastic policy gradient, our goal is to maximize a performance measure function <em>J(θ) = E[r_γ |π]</em>, which is the expected total discounted reward following policy π, where<em> θ</em> is the parameters of the function we are updating. Here is an expanded version of the performance measure function where we sum up all rewards over the state distribution <em>ρ</em> and actions in each state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*SFxJ1_-Jib1mmP4tpqWXxQ.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>For a deterministic policy, this is a bit different. Unlike a stochastic policy, we define our policy to be the function <em>μ_θ: S → A, </em>where μ takes in the state space <em>S</em> and outputs an action space <em>A </em>following parameters <em>θ. </em>Here, instead of getting the integral over actions, we only need to sum over the state space as action is deterministic. We can then write this as an expectation, where we sample a state from the state distribution <em>ρ.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*lDUqRlMwoIANICSWliYrhw.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>The majority of model-free learning algorithms are based on policy iteration, where the general framework consists of <em>policy evaluation</em> and <em>policy improvement.</em> Policy evaluation involves methods such as estimating an action-state function Q and policy improvement methods usually involve updating the policy with respect to this action-state function. An example of this is when we are building a policy for Q-learning. After learning a policy evaluation function Q, we build a policy using argmax to select the action with the highest Q value.</p><p>For the deterministic policy, we will be doing something similar. Since our action space is continuous, we will move our policy in the direction of the Q function’s gradient. Instead of maximizing Q by taking the argmax action, the policy will converge towards a maxima Q value. We can write this gradient as an expectation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*rybaibq_77yrGFJBsy6uNQ.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>Then, we can apply the chain rule once so we can see the gradient of <em>Q</em> is with respect to action <em>a</em>, and the gradient of <em>μ</em> is with respect to parameters <em>θ:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*nNxihIu80_yHzvYeR8ynBA.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>Here’s the expanded form of the deterministic policy gradient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*1Lej3d1W4udXhrHc7roeGg.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>The proof for this deterministic policy gradient is similar in structure to the proof for the policy gradient theorem detailed in <a href="https://proceedings.neurips.cc/paper/1999/file/464d828b85b0bed98e80ade0a5c43b0f-Paper.pdf">(Sutton et al. 1999)</a>. Looking at the deterministic policy gradient, you may notice that it is a bit similar to the stochastic policy gradient. The paper introduces a theorem that shows that the deterministic policy gradient is really just a special case of the stochastic policy gradient.</p><p>Recall the policy gradient theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*9pec6lsxfabrIgt-.png" /><figcaption>Taken from Sutton &amp; Barto, 2017</figcaption></figure><p>We can parameterize the policy function <em>π</em> with the deterministic policy <em>μ_θ </em>and variance σ, similar to that of a policy parameterization for continuous actions. The theorem states that as σ approaches 0, π = μ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*M-6_-11s7kLzl59ENReyFQ.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>The proof for this theorem can be found in <a href="http://proceedings.mlr.press/v32/silver14-supp.pdf">Appendix C</a> of the paper. This theorem is important as it shows that other techniques such as compatible function approximation, natural policy gradients, and experience replay can be applied to deterministic policy gradients.</p><h3>Deterministic Policy Gradient Algorithms</h3><p>With the deterministic policy gradient, we can derive different kinds of algorithms such as Actor-Critic methods for both on-policy and off-policy. The paper beings with a simple on-policy algorithm that uses SARSA to update the Critic. Similar to stochastic Actor-Critic methods, we have an Actor that updates the policy, which in this case is deterministic, and a Critic, which will approximate the true action-state function Q by learning a set of parameters. Here are the update equations for the algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*u90W9VDa6XMOY4nzlwB9Xg.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>Similar to the on-policy algorithm, we can also use the deterministic policy gradient for an off-policy algorithm. Instead of using trajectories sampled from the policy, we can use a stationary behavior policy to get our actions. We can derive the expectation of the performance measure gradient in a similar way to a stochastic off-policy Actor-Critic which I wrote about in my <a href="https://chengxi600.medium.com/actor-critic-off-policy-actor-critic-algorithm-cca654845558">previous post</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*ErbPHeFga3FwWwtMzj7lwQ.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>This is the same expectation as the on-policy gradient, except the states are sampled from a separate behavior policy β. Note that the policy gradient does not use an importance weight since we don’t take the integral over actions. We can also avoid the importance weight for the Critic by using Q-learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*I9KO7HAFOWLnNXm9bN402g.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>In the two algorithms that were proposed above, there is still a big problem. We substituted the action-state function in the deterministic policy gradient with an approximation, but this does not guarantee that the approximated gradient will follow the true gradient. The paper then proposes a class of compatible function approximators to make sure that the approximation will follow the true gradient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*F4SCNwTofi5Lkh5zNqI7Lw.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>Here is the proof for the theorem:</p><p>First, if <em>w</em> minimizes MSE, then the gradient of MSE with respect to <em>w</em> is 0. We know this because if <em>w</em> minimizes the error, then <em>w</em> must be at a minima, therefore, the gradient is 0. Then, we have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYcBwD7VQ8QfD8VRbB2-iQ.png" /></figure><p>For lines (1) to (3), we expand the gradient of <em>MSE</em>. Then, we show that <em>∇_w ϵ(s, w) = ∇_θ μ(s, θ)</em>. We expand the gradient of ϵ in (4) and (5), then use condition 1 of the theorem for (6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaXe6ken7btLal9KZ_r4cg.png" /></figure><p>Now, we can plug in the <em>∇μ</em> in (8) and expand the<em> ϵ</em> in (9). Then, we distribute the <em>∇μ</em> in (10) and show that the deterministic policy gradient theorem is compatible using the approximator <em>Q_w </em>following the two conditions. Note that the compatible function approximator works for off-policy too!</p><p>The paper then proposed a form for the approximator Q_w that will satisfy the two conditions of the theorem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*ivk_FSk_-R8Od8fHNVGF9A.png" /></figure><p>Here, we have the base form for the action-state function. The components of the function are simple: the advantage function <em>A</em> estimates the advantage of choosing action <em>a</em> over <em>μ(s</em>) and the value function <em>V</em> is the value of the state <em>s</em>. For the value function, we can just use a linear approximator with parameters <em>v</em> and state features ϕ(s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*_5MzyzQUXVq6-KrwEsoV3A.png" /></figure><p>For the advantage function, we can also use a linear approximator with parameters <em>w</em> and define the action-state features ϕ(s, a).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*eUg8PYizm9AB4XLiELgGWQ.png" /></figure><p>The action-state features here are proportional to the advantage of taking action <em>a</em> over <em>μ(s)</em>, and also satisfy condition 1 of the compatibility theorem. Here is the complete form for the approximator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*MJx0KbYyk4qANpXQloCEkw.png" /></figure><p>Note that given an <em>m</em> action space size and <em>n </em>policy parameters, <em>∇μ(s)</em> will be a Jacobian matrix, ϕ(s) will be an <em>n × 1</em> vector, and <em>w</em> will also be an <em>n × 1 </em>vector. Now, we must satisfy condition 2 of the theorem, <em>w </em>must minimize the mean-squared error between the gradient of Q_w and the true gradient. The problem here is similar to that of learning a value function. Since sampling unbiased values of the true gradient are too hard, we will just approximate the true gradient with approximation methods such as SARSA or Q-learning. The paper does acknowledge that although an approximation of the true gradient will not exactly minimize the mean-squared error, the approximation can still approximately satisfy the second condition.</p><p>With all this, the paper proposes a compatible off-policy deterministic Actor-Critic algorithm (COPDAC-Q) that uses a Q-learning critic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*aozj8UBtonnXKOvmRlX0FA.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>A problem you may notice with this is that off-policy Q-learning tends to diverge. An improvement we can do is by using gradient temporal-difference methods that can guarantee convergence in an off-policy setting, the same thing we did for <a href="https://medium.com/geekculture/actor-critic-off-policy-actor-critic-algorithm-cca654845558">Off-Policy Actor-Critic</a>. The paper then proposes another algorithm, COPDAC-GQ that uses a Gradient Q-learning critic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*by-GlvNAuMdHSbv0Qd_T_Q.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>Finally, the paper uses a <a href="https://proceedings.neurips.cc/paper/2001/file/4b86abe48d358ecf194c56c69108433e-Paper.pdf">natural policy gradient</a>, which chooses the steepest gradient ascent direction with respect to the Fisher information metric. We use a deterministic version of the Fisher information metric, which is a special limiting case of the stochastic version when the stochastic policy’s variance approaches 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*e7esILHMfNDAJeq7yVUyyw.png" /><figcaption>Taken from Determinist Policy Gradient Algorithms (Silver et al. 2014)</figcaption></figure><p>Luckily, with our compatible function approximator, we can easily see that the steepest ascent direction with respect to the Fisher information metric is simply <em>w.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*CxM21bDg-cptA0O6iH8EBQ.png" /></figure><h3>Implementing COPDAC-Q</h3><p>Now, let’s try to implement a DPG! I will be trying to implement a COPDAC-Q with a natural policy gradient. The implementation is done in Pytorch and we will be using linear approximations for the policy, Q function, and value function.</p><p>Firstly, a quick introduction to the MountainCar environment. The agent is a car starting from the bottom of a hill and wants to reach the green flag at the top of the hill. The state space is continuous with Car velocity and Car position, and the action space is also continuous, a power coefficient that is used to calculate the driving force. The reward is 100 for reaching the flag and unlike the paper that only has a reward of -1 at each step, and the agent is penalized for energy usage at each step. The environment is considered solved when the agent achieves a score of 90 over 100 episodes.</p><p>Here are some of the hyperparameters used:</p><ul><li>γ (discount factor) = 0.99</li><li>MAX_STEPS (per episode) = 5000</li><li>SOLVED_SCORE = 90</li><li>α_θ = 0.005</li><li>α_w = 0.03</li><li>α_v = 0.03</li><li>BATCH_SIZE = 8</li><li>Numpy random seed = 0</li><li>Pytorch random seed = 0</li></ul><p>Something interesting is that the random seed here actually does matter as I wasn’t able to get my implementation to work for a long time, but changing the random seed made it work.</p><p>For this implementation, we will be taking advantage of experience replay and doing batch updating every 10 steps. The behavior policy will just be random sampling from the action space. We will also normalize the states using the mean and st. deviation obtained from sampling 10,000 random states. Note that we choose a higher learning rate for the policy evaluation as we want the evaluation to converge faster than the policy so the policy is moved in the correct direction.</p><p>Let’s first train our agent for 100 episodes with a batch size of 1. Here’s the training history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*e1g_TCBQu7NPmLpNFGVNkg.png" /></figure><p>After 100 episodes, our agent was able to achieve an average score of 82.06 over 10 playthroughs with a variance of 0.009. As the nature of the algorithm is deterministic, the low variance makes sense since the only uncertainty is the random starting state for the agent. The grey line is the training score from the behavior policy which does randomly get lucky, and the blue line is our target policy score. A fascinating thing is that even though the policy does initially go in the wrong direction around episode 17/18, the policy is still able to recover extremely quickly. I hypothesize that this is around the time where the Q and value function starts to converge, so the policy can learn fast. Here’s what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*wQ57UQL9cJDxXLBRpwzhgA.gif" /></figure><p>Now let’s train our agent with a batch size of 8. Here’s the training history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*QdAFMTAY9BXNEH4pIVhIrA.png" /></figure><p>Our agent was able to achieve an average score of 90.10 with a variance of 0.0203. Looking at the score history, it may seem like a mistake. The target policy starts at a high score of nearly 100 after 1 episode. However, after looking at the trained parameters and making sure there were no NaN values, I tried to retrain the agent for 1 episode. Surprisingly, the agent had an average score of 98 ± 0.03 and can solve the MountainCar environment in just 1 episode! Here’s what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*bPYwPXTRw1suX-cnO5N3JA.gif" /></figure><p>Here’s the interesting thing. For the 1 episode agent, the cart takes a much longer time to reach the flag but has a higher score. If we were to evaluate this with the DPG paper’s metric, then this would have a lower score as it takes a longer time to reach the flag. However, the cart uses less energy here to build up momentum to reach the flag, resulting in a higher score with energy usage penalties. For the 100 episode agent, I would guess that the agent overtrains and diverges to a suboptimal solution as a result of using a Q-learning critic.</p><p>A thing to also note is that the results I was getting are not always consistent, as the agent would not be able to solve the environment for some trials. After modifying the reward to also reward the change in mechanical energy, ∇ME = ∇ (0.5mv²+mgh), the agent was able to consistently solve the environment.</p><h3>Final Thoughts</h3><p>I was pretty excited to tackle this implementation as I wanted to be able to replicate the results from the DPG paper, and it was also an important component of the DDPG algorithm. In the end, I was able to successfully solve the MountainCar environment with my implementation in Pytorch using only linear approximations. Something I did learn in this process is that the random seed does matter. My implementation was not working for a long time until I changed the seed. A change I would do in the future is to aggregate results from different seeds since doing everything on a single seed may give biased results. Intuitively, you would think that an algorithm shouldn’t be dependent on the random seed, but that is the nature of Reinforcement Learning. In the next post, I’ll be taking concepts from DPG and DQN and explore the algorithm DDPG that uses deep learning.</p><p>Code: <a href="https://github.com/chengxi600/RLStuff/blob/master/Deterministic%20Policy%20Gradients/COPDAC-Q.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Deterministic%20Policy%20Gradients/COPDAC-Q.ipynb</a></p><p>References:</p><ul><li><a href="http://proceedings.mlr.press/v32/silver14.pdf">Deterministic Policy Gradient Algorithms (Silver et al. 2014)</a></li><li><a href="http://proceedings.mlr.press/v32/silver14-supp.pdf">Deterministic Policy Gradient Algorithms: Supplementary Material (Silver et al. 2014)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7229d5248e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/introduction-to-deterministic-policy-gradient-dpg-e7229d5248e2">Introduction to Deterministic Policy Gradient (DPG)</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actor-Critic: Off-Policy Actor-Critic Algorithm]]></title>
            <link>https://medium.com/geekculture/actor-critic-off-policy-actor-critic-algorithm-cca654845558?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/cca654845558</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 19:00:49 GMT</pubDate>
            <atom:updated>2021-08-19T07:50:44.102Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will be exploring the ideas behind the paper <a href="https://arxiv.org/pdf/1205.4839.pdf">Off-Policy Actor-Critic</a> (Degris et al.) submitted to the ICML 2012. The paper presents an Actor-Critic method that is fully online and uses a behavior policy to learn the target policy. This off-policy learning method takes advantage of action selection in Actor-critic methods while having the benefits of being off-policy for better exploration and usage of experience replay. In the end, I will try to implement the algorithm described in the paper.</p><h3>Critic: Policy Evaluation</h3><p>Firstly, the paper describes the policy evaluation method for the Critic. Similar to a baseline Actor-Critic method, we can use a set of weights to learn a linear approximation of the value function. During implementation, we can just use a neural network to learn a non-linear approximation. The paper uses <a href="https://sites.ualberta.ca/~szepesva/papers/ICML10_controlGQ.pdf">Gradient-TD methods</a> to learn the weights for the value function in an off-policy setting and also guarantees convergence unlike methods with bootstrapping. These methods try to minimize the mean-squared error of a λ-weighted projected Bellman Equation. The final algorithm presented in the paper uses a variation called GTD(λ) which is introduced by <a href="http://www.incompleteideas.net/papers/maei-thesis-2011.pdf">Maei (2011)</a>. I won’t go into detail about the value approximation method, but it is essentially a variation of TD(λ) in an off-policy setting.</p><h3>Off-policy Policy Gradient Theorem</h3><p>Before we look at how the Actor learns the policy function, let’s see how the policy gradient theorem works in an off-policy setting. Here’s a quick review of the policy gradient theorem. First, we define the policy to be π<strong>ᵤ</strong>(a|s), where the output is the probability of an action <em>a</em> given state <em>s</em>. The policy has a weight vector <strong>u</strong>, or parameters <strong>u</strong> if you’re using a neural network to learn. The goal is to maximize <strong>u </strong>for the performance measure function J:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*dDn6Jg9YnsWnJmyp1JmxtA.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>Here, d<strong>ᵇ</strong>(s) is the distribution of states under <strong>b </strong>where P(sₜ = s | s₀, <strong>b</strong>) ∀t ∈ ℕ, and states are following a behavior distribution <strong>b</strong>. This is slightly different from the on-policy performance measure function as we are sampling from a separate behavior distribution. Recall how we updated the weights in REINFORCE: <strong>u</strong>ₜ₊₁ = <strong>u</strong>ₜ + α∇J(<strong>u</strong>ₜ). We can get the gradient ∇J(<strong>u</strong>) by calculating an approximation of ∇J(<strong>u</strong>). For a complete derivation of this approximation, refer to my post on <a href="https://chengxi600.medium.com/?p=aa2ff134c1b">policy gradients</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*R_pAwtwLQ53l7TXmsLy8hA.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>Here’s a quick rundown of the equation from right to left. <em>Q(s, a)</em> is a value function that evaluates an action <em>a</em> taken in state <em>s.</em> We multiply that by the gradient of the probability of action <em>a</em> given state <em>s </em>following policy π with respect to weights <strong>u</strong>. We then sum up the products for all action <em>a</em> in our action space, giving us an expectation of the gradient of the value for state <em>s</em>. Then, we multiply this by a weight given by the behavior distribution d<strong>ᵇ </strong>for state <em>s</em> and sum the weighted values for all states <em>s</em> in our state space. The final value would be the approximate gradient of the performance measure for our weights <strong>u</strong>.</p><p>The paper provides two theorems to justify this approximation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*1Tw3EOwBpi70bdF3yvPjQQ.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*TwzlrtKPsbKB_FEj9wz8vw.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>Theorem 1 states that an update of any policy parameter in the direction of the approximation gives us a better policy. In an on-policy setting, the policy gradient theorem states that our approximation <strong>g</strong>(<strong>u</strong>) is equal to the gradient of the performance measure function J. While we can’t do this in an off-policy setting, Theorem 2 establishes a relationship between the solutions found using the approximation and the performance measure function. For proof of these two theorems, check the Appendix of the <a href="https://arxiv.org/pdf/1205.4839.pdf">paper</a>.</p><h3>Actor: Online Updates with Eligibility Traces</h3><p>Now that we have established the approximation for ∇J, we can come up with the update equation for the Actor. Just like with REINFORCE’s update equation, we want to find the expectation of the approximation instead of actually summing up all states and actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8qWGr9B0WDAheiOxCWjjA.png" /></figure><p>We start off with the off-policy policy gradient approximation in (1). Then in (2), we can get rid of the summation over all states by writing this as an expectation by sampling a state from distribution <em>d</em><strong><em>ᵇ</em></strong>. In (3), we multiply the expectation by two constants that equals 1, then rearrange some terms. The constant ρ is the <a href="http://timvieira.github.io/blog/post/2014/12/21/importance-sampling/">importance weight</a>. Here, <em>b(a|s)</em> is the probability of action <em>a</em> given state <em>s</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srNO8CKFHmYvLmN1hFprWw.png" /></figure><p>By introducing b(a|s), we are able to get rid of the summation of all actions in a state <em>s</em> by sampling an action from the behavior distribution <strong>b</strong>. The paper simplifies the expectation with a new notation:</p><blockquote>we introduce the new notation Eb [·] to denote the expectation implicitly conditional on all the random variables (indexed by time step) being drawn from their limiting stationary distribution under the behavior policy.</blockquote><p>Now we have converted our approximation into an expectation that can be calculated for the update equation. The paper then subtracts a baseline from it then approximates the Q function by using off-policy λ-returns defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*G4XuNAwnm_F2JH1cDf1rhA.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>We can subtract a baseline from the Q function since the gradient of the baseline is 0. For a more detailed explanation, check my post <a href="https://medium.com/nerd-for-tech/policy-gradients-reinforce-with-baseline-6c871a3a068">REINFORCE with baseline</a>. Here we have the final expectation that approximates <strong>g</strong>(<strong>u</strong>) as the λ-returns are slightly different from the Q function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*8da9wD68nOCJx9uf0j-K3w.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>The expectation is then used in the forward-view update equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*hY_PH76dCG-DjfIbvOiXTg.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>With this equation, we would have to sample a whole trajectory to calculate the λ-return. Fortunately, we can convert this forward-view update into a backward-view update for the algorithm to work fully online. Similar to the backward-view TD(λ) algorithm, we can use eligibility traces to update the parameters <strong>u</strong> instead. For an explanation of these traces, you can check out my post on <a href="https://medium.com/geekculture/actor-critic-value-function-approximations-b8c118dbf723">value function approximations</a>. Here’s the expectation written with eligibility traces,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*g_cTzOZ-xj95_O9AqWgpcA.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>where δ is the TD error: δₜ = Rₜ₊₁ + γV(sₜ₊₁) - V(sₜ) and the eligibility trace is updated with the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*HlEJFrhd6YDBGIIFR4pc5A.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>Then, we can use this expectation for a backward-view update equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*0yH45f7UKRDAoGQfZDsPvg.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>Here’s the pseudocode of the Off-PAC algorithm from the paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*JKG7AYFi2UPOjzo2gR7eTg.png" /><figcaption>Taken from Off-Policy Actor-Critic (Degris et al. 2013)</figcaption></figure><p>The vectors <strong>e</strong>ᵥ, <strong>e</strong>ᵤ are traces used for the Critic and Actor respectively, and <strong>w</strong> is a trace used for the GTD(λ) algorithm to update the Critic. The vectors <strong>v </strong>and <strong>w </strong>are weight vectors for Critic and Actor. Note that we can simplify ψ(s, a) = ∇ ln π(a | s) in the implementation for the Actor update. The hyperparameters used in this algorithm are:</p><ul><li>αᵛ, αʷ : step sizes for Critic</li><li>αᵘ : step size for Actor</li><li>λ : weight decay for traces</li><li>b(⋅|s) : stationary behavior policy distribution</li></ul><h3>Implementation</h3><p>For the implementation of this algorithm, I decided to attempt to implement it exactly how it is in the paper. But first, I wanted to implement a vanilla Off-Policy policy gradient method without all the modifications with λ-returns and off-policy learning for the value function.</p><h3>Off-Policy policy gradient implementation</h3><p>Recall the expectation of the off-policy policy gradient theorem we derived:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*kCWw6SWKD6tmY_GERA34Ew.png" /></figure><p>For a vanilla Off-Policy policy gradient, we are just going to use the discounted cumulative reward Gₜ as the Q value. Here’s the pseudocode I typed up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRfaK52XmR5-3V3v3TGYuQ.png" /></figure><p>As you can see, it is basically the same as REINFORCE, except we are sampling the trajectory from a stationary behavior policy, and we multiply an importance weight ρ in the update step.</p><p>Here are the hyperparameters I used for this implementation:</p><ul><li>α (learning rate): 0.01</li><li>γ (discount factor): 0.99</li><li>MAX_STEPS: 5000</li><li>NUM_EPISODES: 1000</li><li>behavior policy: uniform distribution over action space</li></ul><p>For the experiments, I generated two trajectories in each episode: one from the behavior policy to train our target policy, and one from the target policy so we can evaluate our target policy at that episode. Although this may potentially double the training time, the runtime of each episode is still 2n = O(n).</p><p>Here’s the training history of our agent over 1000 episodes with the CartPole environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*Sx8d0cxmTzG_fNmj4fbdPw.png" /></figure><p>The grey line is the reward history for our stationary behavior policy and the blue line is the reward history for our target policy. As expected, the grey line does not improve since we are sampling from a stationary behavior policy. The blue line shows the improvement of our agent over the 1000 episodes.</p><p>Our agent was able to achieve an average score of 142.37 in 50 playthroughs over 3 trials. This is much better than our vanilla On-Policy policy gradient where we achieved a score of 79.6. The advantages of being off-policy are seen here. Since we sample our trajectory from a stationary behavior policy, our agent maintains the same level of exploration for the whole trial and can prevent itself from being stuck in suboptimal local maxima.</p><h3>Off-Policy Actor-Critic implementation</h3><p>Now, let’s try to implement the Off-PAC algorithm described in the paper. For my implementation, I decided to follow the paper’s implementation exactly and used learned linear approximators for the Actor and the Critic. Here’s a quick walkthrough through snippets of my code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3676fb434d5545a7c5ab5f9ead53c04b/href">https://medium.com/media/3676fb434d5545a7c5ab5f9ead53c04b/href</a></iframe><p>Here, we initialize the Actor and Critic weight vectors u and v, and trace vectors ev, eu, and w. The shape of these vectors is (input x output), where the input is the state space and the output is the action space for the Actor weight vector, and 1 for the Critic weight vector. Then we have some helper functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17e12300b5b4cf953a16e07ab3a7676a/href">https://medium.com/media/17e12300b5b4cf953a16e07ab3a7676a/href</a></iframe><p>Since the paper uses linear approximators for the Actor and Critic, instead of a forward pass through a neural network we simply multiple the weight vector by the feature vector to get an output. The rest is pretty straightforward. We calculate the constants we need and update all the vectors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89936216b5256cecff0da53736af104e/href">https://medium.com/media/89936216b5256cecff0da53736af104e/href</a></iframe><p>After trying to run the agent with the MountainCar environment, I did not get the results I was looking for. Here’s the reward history following the behavior policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*vStbU6W2JH9ZWetu6bdAzg.png" /></figure><p>As expected, the behavior policy is basically the same as a random policy, with some lucky runs above a score of -5000. However, the average score of the agent with 50 playthroughs is still -5000. Even with the same hyperparameters as described in the paper, the policy did not improve. Even with the CartPole environment, the results were around the same as a random policy. Upon investigating the learned weights, the problem seems to come from gradient explosion. However, after reducing the learning rates, the agent gets stuck in a suboptimal policy.</p><h3>Final Thoughts</h3><p>Although I’m a bit disappointed that I couldn’t replicate the results in the paper, it is still interesting to learn about how policy gradients and value function approximation works in an off-policy setting. For the implementation of the Off-PAC algorithm described in the paper, I decided to try and copy the algorithm exactly, and used matrices for my weights instead of using a neural network to parameterize the learned functions. I definitely got a bit better at using Pytorch tensors since I had to do all the calculations manually.</p><p>A problem I was stuck on for a while was needing to do in-place operations on the weight vector for the target policy. Firstly, I needed to enable the requires_grad flag for the weight vector as I needed to calculate the gradient of the target policy probability with respect to the weight vector. To be able to get the gradient of the weight vector, it needed to be a leaf tensor since Pytorch autograd traverses through the DAG from non-leaf tensors to leaf tensors to perform the chain rule. Note that in Pytorch, Autograd keeps track of a DAG where nodes are tensors and edges are operations, where the arrow points to the resulting tensor from the operation. A leaf tensor is a tensor that has no operations performed on it, so in-place operations counts too.</p><p>The solution was to use detach() on the weight vector so that the resulting tensor is detached from the DAG. Then, I would have to enable the requires_grad flag again as I’m technically not doing an in-place operation but creating a new leaf tensor.</p><p>Code:</p><ul><li>Off-Policy policy gradient: <a href="https://github.com/chengxi600/RLStuff/blob/master/Policy%20Gradients/Off-Policy_Policy_Gradient.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Policy%20Gradients/Off-Policy_Policy_Gradient.ipynb</a></li><li>Off-Policy Actor-Critic: <a href="https://github.com/chengxi600/RLStuff/blob/master/Actor-Critic/Off-Policy_Actor_Critic.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Actor-Critic/Off-Policy_Actor_Critic.ipynb</a></li></ul><p>References:</p><ul><li><a href="https://arxiv.org/pdf/1205.4839.pdf">Off-Policy Actor-Critic (Degris et al. 2013)</a></li><li><a href="https://lilianweng.github.io/lil-log/2018/04/08/policy-gradient-algorithms.html#off-policy-policy-gradient">Policy Gradient Algorithms (Lilian Weng’s blog)</a></li><li><a href="http://www.incompleteideas.net/papers/maei-thesis-2011.pdf">Gradient Temporal-Difference Learning Algorithms (Maei 2011)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cca654845558" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/actor-critic-off-policy-actor-critic-algorithm-cca654845558">Actor-Critic: Off-Policy Actor-Critic Algorithm</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Policy Parameterization for a Continuous Action Space]]></title>
            <link>https://medium.com/geekculture/policy-based-methods-for-a-continuous-action-space-7b5ecffac43a?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b5ecffac43a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 20:11:24 GMT</pubDate>
            <atom:updated>2021-08-10T06:15:45.070Z</atom:updated>
            <content:encoded><![CDATA[<p>In the past few Policy Gradient and Actor-Critic algorithms I’ve implemented, I’ve been using the classical control environment, CartPole, as my experiment benchmark. The CartPole environment has a simple discrete action space: pushing the cart left or right. In this post, I will be exploring another way to parameterize our policy function to deal with an environment with a continuous action space.</p><h3>Introduction</h3><p>One of the advantages of a policy-based method is the ability to deal with large or even continuous action spaces. When we are doing Q-Learning methods, the agent learns the Q value for each action in a state and builds an optimal policy by picking the action that gives the highest Q value. While this may work for some environments, this only works with a discrete action space as there is an infinite number of actions in a range of continuous values. In policy-based methods, the agent learns the policy directly and picks an action out of a probability distribution of the action space. For a continuous action space, we can learn the parameters of a probability distribution and pick a value from there instead. First, let’s review how the policy is parameterized for discrete actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*mJOsjM-rZMG5-5NewI64OQ.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>The function takes in a discrete action, such as “push left” or “push right”, a state <em>s</em>, and a set of parameters θ. On the right side of the equation, there is the <em>h(s, a, θ) </em>function, which is a preference function that gives higher values to an action that the policy prefers. We use an exponential softmax distribution here so the preference value is converted to a probability value between [0,1], and all actions in a state will sum up to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*x7RAgKKyl3kQMJ3YXCWviA.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>The preference function here is just a simple set of weights θ multiplied by feature vector <em>x(s, a).</em> During implementation,<em> </em>the set of weights can be learned through a neural network, so the preference function can be more complicated than just a simple linear function.</p><p>Now, let’s see how the policy is parameterized for continuous actions. The policy function is based on the probability density function for a Gaussian distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*K3PPtvUi-cU7p0tFVZbrsw.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>We can see that the parameters of this distribution are<em> μ</em>, the mean, and <em>σ</em>, the standard deviation. Note that <em>p(x)</em> does not give us the probability of <em>x</em> but the density of the probability of <em>x. </em>Unlike the softmax distribution for discrete actions, the Gaussian density distribution gives us a real value instead of a probability. To find the probability for a range of <em>x</em> values, you would need to find the definite integral between those bounds. Using this probability density function, we can define our policy function to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*trg51m3QmgIAS4nBXHHBZg.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>Here, we use our θ parameters to approximate the values of μ and σ to get the probability density distribution. The μ and σ can be approximated this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*8zyjrCuxgCJQv2APv3CrrA.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>We can approximate the mean by a linear function, so a simple matrices multiplication of the transposed weights and feature vector. For the standard deviation, the value should be positive, so we exponentiate the linear function. Just like the parameterization for discrete actions, we only need to use one network as both μ and σ are approximated by the same linear function.</p><p>So that&#39;s it! There isn’t much that is changed in the underlying logic of any algorithm that uses a continuous action space, but rather the way the policy function is parameterized.</p><h3>Implementation</h3><p>For the implementation, I will parameterize the policy function using a neural network. Then, I will test my implementation with the vanilla policy gradient method REINFORCE. Looking at the classical control environments in OpenAI’s gym, I chose to tackle the Continuous Mountain Car problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*JkfAXyy63Tuw8bOO.gif" /><figcaption>Taken from Paperspace Blog</figcaption></figure><p>The premise of the MountainCar environment is simple. At each step, the agent exerts power proportional to a value between [-1, 1], and the goal is to drive the cart to the flag. The agent is rewarded when the cart reaches the flag and penalized for the energy used. However, achieving the goal is a little more complicated. Since the power is constrained, the idea is for the cart to rock back and forth to generate enough momentum to climb uphill. The agent will also need to minimize the amount of energy used to get a higher score. The environment is considered solved when achieving a score of 90+.</p><p>Here are the hyperparameters I used for my implementation:</p><ul><li>γ (Discount factor): 0.99</li><li>α (Learning rate): 0.001</li><li>NUM_EPISODES (episodes to run): 1000</li><li>MAX_STEPS (max steps per episode): 500</li></ul><p>Here is the policy network:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a448b092b709aa3767d07af315b42cb7/href">https://medium.com/media/a448b092b709aa3767d07af315b42cb7/href</a></iframe><p>We have two outputs here, μ and σ. Here is a snippet of code I used to select an action:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59652e36f8562c8272e7bfc6c10b38d6/href">https://medium.com/media/59652e36f8562c8272e7bfc6c10b38d6/href</a></iframe><p>Note that I still calculate the log probability of distribution as the update equation for the policy still doesn’t change, we are only changing how we parameterize the policy function.</p><p>Here’s the training history of the agent over 250 episodes with REINFORCE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*fhXXEJEM8KDxrlgzdBohmw.png" /></figure><p>When I first saw the training history, I was surprised at the result. The agent’s score increased rapidly and progress flatlined early on at around 50 episodes. Upon rerunning the experiment 10 more times, the same history pattern appears, though sometimes it does manage to exceed a score of 0 for one episode. A conclusion you may come up with is that the agent uses too much energy to generate the momentum needed to climb the hill, resulting in the reward canceling out the energy usage. However, looking at the agent play with the learned policy, the cart appears to only slightly rock back and forth at the base of the hill. So what happened?</p><p>The problem here lies with the environment’s sparse rewards. The MountainCar environment penalizes the agent for energy usage at each step and only rewards the agent after reaching the flag. Therefore, the agent will not know of the reward until it reaches the flag by random chance. As the agent is being penalized at each step, its goal naturally would be to minimize energy usage resulting in a policy where the cart just sits still.</p><p>A potential solution to this problem could be to make custom rewards for the environment instead. However, after trying to use position, velocity, mechanical energy, and more, I was still receiving the same results. The reason for this is due to the nature of our algorithm.</p><p>Our policy-based method relies on improving the policy directly and samples actions from our learned policy. While an off-policy method can use exploration methods such as epsilon-greedy, the only exploration our agent has is when the sampled action deviates far from the mean or the standard deviation is large. As the agent tries to update the policy without reaching the goal, the policy will converge suboptimally.</p><p>Looks like it&#39;s back to the good ole CartPole environment. I will be using a <a href="https://gist.github.com/iandanforth/e3ffb67cf3623153e968f2afdfb01dc8">continuous CartPole</a> implementation by <a href="https://gist.github.com/iandanforth">iandanforth</a> with OpenAI’s solved condition of an average 195 score over the most recent 100 episodes. The actions will be clipped to be [-1, 1]. Here’s the training history with REINFORCE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*c1h68OmZ_p4zp20_Ll_ikw.png" /></figure><p>Our agent was able to achieve an average score of 300.72 over 50 playthroughs. The agent was also able to solve CartPole in an average of 384.8 episodes over 5 trials. Compared to a score of 79.6 for CartPole with a discrete action space using REINFORCE, this result was far better. The agent was able to solve the environment under 1000 episodes. This result is to be expected as using continuous actions would provide precise control over the cart compared to applying +1 or -1 force.</p><p>One thing to note is the instability and frequent catastrophic forgetting. Since we are doing REINFORCE without a baseline, high variance is to be expected. However, we can observe that the agent “forgets” quite frequently starting from around episode 150. I hypothesize that this is because since our agent is learning so quickly, there isn’t time to converge to a stable policy. Adding onto the fact that our actions can widely vary, several outlier actions can cause the policy to collapse.</p><p>Here’s a peek at the training history of the action distribution parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*crUwSmgNgF0O0fjiOfX4Kg.png" /></figure><p>The training history of the means is to be expected. As the agent is trying to balance the pole, the policy learns to alternate the mean between negative and positive actions. We can also observe that the majority of the negative means are under -1 while the positive means are between 1 and 2 except for outliers. Since we clipped our actions to be between [-1, 1], the positive actions would be all +1. Negative means occurs 20% more frequently than the positive means to compensate for the larger positive means. I hypothesize that the magnitude of the mean increases over time since the actions are clipped so the mean can keep climbing without punishment.</p><p>The history of the standard deviation was a bit unexpected and can explain the training score history. We can see that our policy is less confident in its actions by its high st. dev starting from step 20,000. This is around the same time when the agent starts to catastrophically forget and there is a high score variance. The st. dev falls back down again once the agent solves the environment and converges to a maxima.</p><p>Let’s look at the training history of the scores and action distribution parameters with unclipped actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*3mbQLoaDgO_g8hfY99GnyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*Kawhx_1IEPb8fQsbOnIRQA.png" /></figure><p>Unlike the clipped actions, the magnitude of the mean does not increase over time as with unclipped actions there would be punishment for exerting extra force. The standard deviation history also makes sense as the learned policy is more confident in its action when it converges towards the solution.</p><h3><strong>Final Thoughts</strong></h3><p>Overall, this was a fun and short experiment that did not take too long to do. I only wanted to try to implement a different kind of policy parameterization so I modified parts of the code from the REINFORCE algorithm. In future posts, I will be moving on to more complex algorithms that do deal with continuous action spaces such as DDPG, PPO, SAC so hopefully, those algorithms will be able to solve more complex environments.</p><p>Code: <a href="https://github.com/chengxi600/RLStuff/blob/master/Policy%20Gradients/REINFORCE-Continuous.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Policy%20Gradients/REINFORCE-Continuous.ipynb</a></p><p>References:</p><ul><li><a href="http://incompleteideas.net/book/bookdraft2017nov5.pdf">Reinforcement Learning: An Introduction (Sutton&amp;Barto 2017)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b5ecffac43a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/policy-based-methods-for-a-continuous-action-space-7b5ecffac43a">Policy Parameterization for a Continuous Action Space</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actor-Critic: Implementing Actor-Critic Methods]]></title>
            <link>https://medium.com/geekculture/actor-critic-implementing-actor-critic-methods-82efb998c273?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/82efb998c273</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 12:30:24 GMT</pubDate>
            <atom:updated>2021-08-18T19:11:05.535Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I’ll be implementing some Actor-Critic methods using the <a href="https://medium.com/nerd-for-tech/reinforcement-learning-introduction-to-policy-gradients-aa2ff134c1b">policy gradients methods</a> and <a href="https://medium.com/geekculture/actor-critic-value-function-approximations-b8c118dbf723">value function approximations</a> from my previous posts. I won’t focus too much on the theory and details but more so on combining previous ideas of Actor and Critic.</p><h3>Actor-Critic Algorithms</h3><p>First, let’s look at the One-step Actor-Critic algorithm given by Sutton&amp;Barto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3GuuYG9Lt27G9RBn8b3Yg.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>We’ve learned how to update the Critic (Value function) which “critiques” the current state and the Actor (Policy function) which is updated in the direction that the Critic tells us to. The One-step Actor-Critic algorithm here is fully online and the Critic uses the TD(0) algorithm to update the value function’s parameters w. Recall the TD(0) update equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*d9yrGRk3r_nAfq0j.png" /><figcaption>Taken from David Silver’s UCL Lecture 7</figcaption></figure><p>Here, we are using the temporal difference between a target value and approximated value to update the value function in the gradient direction. Since the TD(0) algorithm updates at each time step, the target value is estimated by bootstrapping.</p><p>Now let’s look at the Actor. The Actor updates the policy parameters θ using the evaluation from the Critic. Recall the policy update equation we derived from the policy gradient theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*hY3cW5UxbpEEAYa3.png" /><figcaption>Taken from David Silver’s UCL Lecture 7</figcaption></figure><p>This policy update equation is used in the REINFORCE algorithm, which updates after sampling the whole trajectory. Since Sutton&amp;Barto’s One-step Actor-Critic uses online updates, we update the policy parameters in the direction of the state-action value approximated by the value function instead of using cumulative rewards Gₜ. Now if we only used the value function to determine the direction of the update, this results in a fairly biased result. We can use the concept of subtracting a baseline to make it unbiased. You can read more about my implementation of REINFORCE with baseline <a href="https://medium.com/nerd-for-tech/policy-gradients-reinforce-with-baseline-6c871a3a068">here</a>.</p><p>In REINFORCE with baseline, we used the value function as the baseline, so naturally, we can here too. Instead of updating the policy in the direction of the approximated state-action value, we adjust it by the advantage of choosing a specific action in this state. We can calculate this advantage by looking at the difference between the state value and the state-action value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*QFsP_WJM7wXeLXw6qxR-Fw.png" /><figcaption>Taken from David Silver’s UCL Lecture 7</figcaption></figure><p>A quick review: Q(s, a) is the value of a state s after taking action a while V(s) is just the value of a state s.</p><p>The naive way to do this is by learning a state-action value function Q and state value function V with different parameters. Doing this would make our algorithm way more complicated as we’ll have to keep track of the Q, V, and Policy parameters. Sutton&amp;Barto use a simpler approach here. We can use (R + V(s’)) as the estimated state-action value to compute the advantage, which is the same as TD error!</p><p>If you look at different implementations of the Actor-Critic algorithm, you may notice some differences. For example, <a href="https://keras.io/examples/rl/actor_critic_cartpole/">Keras</a> and <a href="https://github.com/pytorch/examples/blob/master/reinforcement_learning/actor_critic.py">Pytorch</a> use a Monte Carlo method to update the Actor and Critic. While Sutton&amp;Barto do not consider the Monte Carlo approach a true Actor-Critic method as the Critic is only used as a baseline to reduce variance, those approaches are still effective.</p><p>A question you may have now is, can the Critic use different value approximation methods? The answer is yes. Recall the different <a href="https://medium.com/geekculture/actor-critic-value-function-approximations-b8c118dbf723">approximation methods</a> we have discussed:</p><p>Monte Carlo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*l0zbxiX4cPj_My2GPI2iEg.png" /><figcaption>Taken from David Silver’s UCL Lecture 7</figcaption></figure><p>TD(0), the one used by Sutton&amp;Barto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*ZyHjxefdBChXNrPyDOp2lw.png" /><figcaption>Taken from David Silver’s UCL Lecture 7</figcaption></figure><p>Forward-view TD(λ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*loT7M24lr7hK4DyrG_E2qw.png" /><figcaption>Taken from David Silver’s UCL Lecture 7</figcaption></figure><p>Backward-view TD(λ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*OL7iTntB_WXdWA3dpe-RxA.png" /><figcaption>Taken from David Silver’s UCL Lecture 7</figcaption></figure><p>We can even do the same for the advantage function for the Actor. Simply substitute ϕ(s) = ∇v(S, w) for the Critic with ϕ(s) = ∇ln π(A|S, θ) for the Actor.</p><p>Here’s the pseudocode for an online Actor-Critic using Backward-view TD(λ) for the Actor and the Critic by Sutton&amp;Barto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*BBbKhynXKckOpljjFzmOLg.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>We can also implement a Forward-view TD(λ) for Actor and Critic, but similar to a Monte Carlo method, we would have to sample the full trajectory and perform offline updates episodically.</p><h3>Implementations</h3><p>For the rest of the post, I’ll be showing my Pytorch implementations of the Actor-Critic method and talk about some challenges and things I did. I’ve implemented Actor-Critic using TD(0), Backward-view TD(λ), and Forward-view TD(λ). For the Monte Carlo implementation, refer to my post <a href="https://medium.com/nerd-for-tech/policy-gradients-reinforce-with-baseline-6c871a3a068">REINFORCE with Baseline</a>. Here are the neural networks I used to parameterize my Policy and Value function:</p><pre>class PolicyNetwork(nn.Module):<br>    <br>    #Takes in observations and outputs actions<br>    def __init__(self, observation_space, action_space):<br>        super(PolicyNetwork, self).__init__()<br>        self.input_layer = nn.Linear(observation_space, 128)<br>        self.output_layer = nn.Linear(128, action_space)<br>    <br>    #forward pass<br>    def forward(self, x):<br>        #input states<br>        x = self.input_layer(x)<br>        <br>        #relu activation<br>        x = F.relu(x)<br>        <br>        #actions<br>        actions = self.output_layer(x)<br>        <br>        #get softmax for a probability distribution<br>        action_probs = F.softmax(actions, dim=1)<br>        <br>        return action_probs</pre><p>Statevalue Network:</p><pre>class StateValueNetwork(nn.Module):<br>    <br>    #Takes in state<br>    def __init__(self, observation_space):<br>        super(StateValueNetwork, self).__init__()<br>        <br>        self.input_layer = nn.Linear(observation_space, 128)<br>        self.output_layer = nn.Linear(128, 1)<br>        <br>    def forward(self, x):<br>        #input layer<br>        x = self.input_layer(x)<br>        <br>        #activiation relu<br>        x = F.relu(x)<br>        <br>        #get state value<br>        state_value = self.output_layer(x)<br>        <br>        return state_value</pre><p>Here are the hyperparameters I used for my implementations:</p><ul><li>γ (discount factor): 0.99</li><li>NUM_EPISODES: 1000</li><li>MAX_STEPS: 10000</li><li>α (Actor LR): 0.01</li><li>β (Critic LR): 0.01</li><li>λ (Actor): 0.8</li><li>λ (Critic): 0.8</li></ul><p>For each of the implementations, I’ll be using OpenAI’s solved condition of an average score of 195 over the most recent 100 episodes.</p><h3><strong>TD(0) implementation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3GuuYG9Lt27G9RBn8b3Yg.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>For the TD(0) AC, I followed the pseudocode given by Sutton&amp;Barto above. In my implementation, I used MSE as the loss function for the Critic, which is the same thing as the pseudocode above which applies the chain rule once. I’m also using Stochastic Gradient Descent (SGD) as my optimizer as described in the pseudocode and also to get a fair comparison between the different implementations.</p><p>Let’s look at the training history of my result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*UDTEiMzbXhn3X6VeV3Is3w.png" /></figure><p>Our agent was able to achieve an average score of 61.828 in 50 playthroughs over 5 trials. In the training history, we can see that there is a steady upward trend in score despite the high variance. Compared to the human benchmark (me) score of 30.8 and random policy score of 21.48, a score of 61.8 is definitely much better.</p><p>An explanation for the high variance could be because of the returns. For REINFORCE with baseline, I was able to use whitening rewards to normalize the rewards to reduce variance. That was because the algorithm samples the whole trajectory before applying updates, so I was able to apply normalization. Another reason for the variance is the sudden drops in the score. This is because of a phenomenon called catastrophic forgetting in which the agent “forgets” past states and needs to relearn patterns again.</p><p>Here’s the training result when using the Adam optimizer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*D9zaQCfpGMTTNaGBborNBQ.png" /></figure><p>With the Adam optimizer, the agent was able to achieve an average score of 500 in 50 playthroughs. The agent also hit our solved condition in just 443 episodes of training.</p><h3><strong>Forward-view TD(λ) implementation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kdraNRNufKeW2FvEgFO7A.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>For the Forward-view TD(λ) AC, there wasn’t any pseudocode but the concept is similar to the REINFORCE with baseline described by Sutton&amp;Barto above. Instead of calculating Gₜ return from step t, we calculate Gₜ lambda-returns from step t, which averages N-step returns for all Ns with decaying weights assigned to each N-step return. I used Stochastic Gradient Descent (SGD) as my optimizer and used MSE as my loss function to learn the value function. I also used whitening rewards to combat gradient explosion and reduce variance.</p><p>Lets’ look at the training history of my result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*3-TUd4EMekMywWw8uDSBZQ.png" /></figure><p>Our agent was able to achieve an average score of 146.27 in 50 playthroughs over 3 trials. I had only run 3 trials since the algorithm had a longer run time, and it was enough to ensure that I didn’t have an outlier. Compared to TD(0), our agent was able to achieve a better score of 146.27 compared to 61.83. We can also see that there isn’t as much variance due to the more robust target values that combine different N-step target values from all Ns. There is also an instance of catastrophic forgetting that happens around episode ~160 after the agent achieves a high score of 500.</p><p>When I was calculating the N-step returns, my solution’s runtime was O(n³) which I probably could’ve reduced to O(n²), so it resulted in a much longer runtime of around 16 minutes compared to TD(0)’s 2 minutes. This is a downside to the Forward-view TD(λ) which needs a higher time complexity for calculating N-step returns for all Ns at each time step and also a higher space complexity for storing the trajectories. This is also a reason why most algorithms choose to use backward-view TD(λ) instead of forward-view as this is not an issue with eligibility traces.</p><p>Here’s the training result when using the Adam optimizer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*GDVPf2QQBvIFh_ViLbjUUg.png" /></figure><p>With the Adam optimizer, the agent was able to achieve an average score of 500 in 50 playthroughs. The agent also hit our solved condition in just 262 episodes of training.</p><h3><strong>Backward-view TD(λ) implementation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*BBbKhynXKckOpljjFzmOLg.png" /></figure><p>For the Backward-view TD(λ) AC, I followed the pseudocode given by Sutton&amp;Barto above. In my implementation, I didn’t use an optimizer and performed manual updates to the network parameters so that I could apply the eligibility traces. This is also a reason why I used SGD for the other implementations to get a more fair comparison of results.</p><p>Let’s look at the training history of my results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*-rNE5_PbFiSjHHteXXLqvA.png" /></figure><p>Our agent was able to achieve an average score of 334.116 in 50 playthroughs over 5 trials. The agent also hit the solved condition in an average of 266.2 episodes. Compared to TD(0), our agent was able to achieve a much better score. Theoretically, the Forward-view and Backward-view TD(λ) are equivalent but as always in reinforcement learning, there is the problem of replicating results due to high variance. The training time of Backward-view TD(λ) is around the same as TD(0), as both do online updating. Compared to Forward-view TD(λ) which has a high time and space complexity, Backward-view TD(λ) accumulates an eligibility trace at each step which allows each update to take account of all the past updates. The neat thing is the trace only has a space complexity of O(|θ| + |w|) = O(1), which is the Actor and Critic network parameter size. When calculating the target value returns, we only need to calculate the 1-step TD error, which is O(n) for one episode.</p><p>As we have to perform updates manually, the Adam optimizer would not work in this case.</p><h3>Summary</h3><p>Here’s a summary of results including Monte Carlo AC from <a href="https://chengxi600.medium.com/policy-gradients-reinforce-with-baseline-6c871a3a068">REINFORCE with Baseline</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlGNOM4Nle-q5GKsjeUfvA.png" /></figure><p>Note that as I only ran 1 trial for the Adam optimizers, the number of episodes it took to solve may vary. An interesting thing to note is that for the solved implementations, the ones using SGD optimizers achieve a score of ~300 while the ones using Adam optimizer achieves a score of ~500. This may be because the Adam optimizer introduces update momentum and acceleration which allows the agent to climb to a local maxima faster than when using SGD. Another thing to note is that the choice of the CartPole environment has a huge impact on the effectiveness of each algorithm. CartPole only gives a uniform reward of +1 for every timestep in a non-terminal state, so the TD(λ) algorithms aren’t particularly better.</p><h3>Final Thoughts</h3><p>The three implementations took much longer than expected, and it was largely due to me misunderstanding the pseudocode and the Pytorch library. While TD(0) and Forward-view TD(λ) were fairly straightforward for me, I was stuck on Backward-view TD(λ) for a while. I was using the prebuilt optimizers and was unsure where to apply my eligibility traces. After watching this <a href="https://www.youtube.com/watch?v=mdKjMPmcWjY">video</a> that gives a short overview of the different optimizing algorithms, I realized that I should just perform manual updates.</p><p>Another thing I learned to use was setting the required_grad attribute to True when forming a tensor that I needed to perform backpropagation on which would help track Tensor operations. When calling backward() multiple times on tensors that had overlapping leaf tensors, I would need to use backward(retain_graph=True) instead so that the computational graph isn’t freed from memory after calling backward().</p><p>Overall, this was a challenging task but rewarding one which I learned a lot and feel more confident in proceeding to harder algorithms. Since there weren’t a lot of resources on eligibility traces, I ended up being stuck for a while on them. In future posts, I want to address Actor-Critic algorithms for continuous action spaces, Natural Actor-Critic, Asynchronous Advantage Actor-Critic (A3C), Deterministic Policy Gradients, and Proximal Policy Optimizations.</p><p>Code:</p><ul><li>TD(0) Actor-Critic: <a href="https://github.com/chengxi600/RLStuff/blob/master/Actor-Critic/Actor-Critic_TD_0.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Actor-Critic/Actor-Critic_TD_0.ipynb</a></li><li>Forward-view TD(λ) Actor-Critic: <a href="https://github.com/chengxi600/RLStuff/blob/master/Actor-Critic/Actor-Critic_TD_Lambda_Forward.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Actor-Critic/Actor-Critic_TD_Lambda_Forward.ipynb</a></li><li>Backward-view TD(λ) Actor-Critic: <a href="https://github.com/chengxi600/RLStuff/blob/master/Actor-Critic/Actor-Critic_TD_Lambda_Backward.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Actor-Critic/Actor-Critic_TD_Lambda_Backward.ipynb</a></li></ul><p>References:</p><ul><li><a href="https://www.davidsilver.uk/wp-content/uploads/2020/03/pg.pdf">Policy Gradients (David Silver’s UCL Lecture 7)</a></li><li><a href="http://incompleteideas.net/book/bookdraft2017nov5.pdf">Reinforcement Learning: An Introduction (Sutton &amp; Barto 2017)</a></li><li><a href="https://www.youtube.com/watch?v=mdKjMPmcWjY">Optimizers EXPLAINED (CodeEmporium)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82efb998c273" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/actor-critic-implementing-actor-critic-methods-82efb998c273">Actor-Critic: Implementing Actor-Critic Methods</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actor-Critic: Value Function Approximations]]></title>
            <link>https://medium.com/geekculture/actor-critic-value-function-approximations-b8c118dbf723?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8c118dbf723</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Fri, 23 Jul 2021 09:18:55 GMT</pubDate>
            <atom:updated>2021-08-02T19:05:59.032Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/nerd-for-tech/policy-gradients-reinforce-with-baseline-6c871a3a068">previous post</a>, I discussed a way to reduce variance by using the generalized policy update equation, which is derived from the <a href="https://medium.com/nerd-for-tech/reinforcement-learning-introduction-to-policy-gradients-aa2ff134c1b">policy gradient theorem</a>, and added a learned value function as a baseline. In this post, I want to elaborate further on the value function, the Critic, and how we can use different kinds of value function approximations to update the value function’s parameters.</p><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*S9VL1DjcDV8rJIM9.png" /><figcaption>Taken from FreeCodeCamp</figcaption></figure><p>First of all, what is an Actor-Critic algorithm? According to the NIPS paper <a href="https://papers.nips.cc/paper/1999/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf">Actor-Critic Algorithms (Konda et. al 1999)</a>, the vast majority of reinforcement learning algorithms at the time fell under two categories: Actor-only methods or Critic-only methods.</p><p>An Actor-only method is one that works with a parameterized policy. The gradient of the performance is directly estimated by simulating the policy and updating the parameters in the direction of improvement. A downside to this is that there can be a large variance.</p><p>A Critic-only method is one that relies on approximating a value function and aims to approximate a solution to the Bellman Equation (see below), which then we can use the learned value function to build an optimal policy. We can think of these as off-policy methods as they indirectly learn an optimal policy by learning the optimal value function. A downside to this is that while we get a good approximation of the value function, this does not mean the policy will be optimal as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_kijSJt3O1V04G7u.png" /><figcaption>Bellman equation for estimating the value function in a non-deterministic environment</figcaption></figure><p>The paper then presents a new kind of method, Actor-Critic algorithms, which combines the strong points from both actor-only and critic-only methods. The critic will use the same approximation structure to learn a value function which is used to update the actor’s policy parameters.</p><p>Now, let’s first take a look at the REINFORCE with baseline algorithm as an example. Although Sutton&amp;Barto do not consider this Actor-Critic as the value function is used as a baseline, not a critic, other sources such as the lectures by David Silver and the <a href="https://arxiv.org/pdf/1602.01783.pdf">paper on A3C</a> do consider it a kind of Actor-Critic. Nonetheless, we’ll still use this as an example as we’ve already seen this algorithm before in my previous post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ych-uOCN0suHkBpYFGoEVA.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>In this pseudocode, we can see the update equation for learning the Actor parameters θ (Policy) and Critic parameters w (state value function). I’ve already derived the Actor update equation from the policy gradient theorem <a href="https://medium.com/nerd-for-tech/reinforcement-learning-introduction-to-policy-gradients-aa2ff134c1b">before</a>, so I will be focusing on the Critic in this post.</p><h3>The Critic</h3><p>The Critic, which is a value function serves as a baseline to update the Actor’s parameters. The way the updating works is by using a loss function to calculate the difference between a target value and an approximate value. The goal is to minimize that loss so that the approximate value will approximate the target, which is the optimal value.</p><p>In the example, the value function here is a state value function that calculates loss by using the difference between Gₜ and v(Sₜ, w) to update its parameters. We can generalize the loss equation δ to J(w) shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*dcPrKde9lZa91CceUYqpSw.png" /><figcaption>Taken from David Silver’s UCL lecture 6 (COMPM050)</figcaption></figure><p>Then, we can get rid of the expectation as we are sampling the gradient. Here, we apply the chain rule one time to get rid of the exponent. The multiplier is absorbed by the learning rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*wLrJy7BI_LC8Y9qQIga86A.png" /><figcaption>Taken from David Silver’s UCL lecture 6 (COMPM050)</figcaption></figure><p>Now we have an update equation that is similar to the one used by Sutton&amp;Barto’s REINFORCE with baseline! Note that when implementing the update for the Critic, we can use a network to backpropagate the MSE loss function directly so no need to manually perform the chain rule.</p><h3>Approximating the value function</h3><p>So how do we actually implement this? For the approximate value, it would just be the output of our value function using the current parameters. For the target value, it would be what our value function should output. In reinforcement learning, these would be the rewards. There are several ways to calculate the target value with rewards. Let’s look at the different algorithms we can use to update our value function.</p><p>A way we can do this is by a Monte Carlo method, which is what REINFORCE with baseline uses. We sample the whole trajectory, accumulate the losses at each step, then update the parameters. The target value would be Gₜ, which is the cumulative discounted rewards at timestep t. We can use the exact cumulative rewards which are all rewards from timestep t to the end since we sampled the whole trajectory beforehand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*IQyl0KHzBjo2Ou9zKgvNqg.png" /><figcaption>Taken from David Silver’s UCL lecture 6 (COMPM050)</figcaption></figure><p>Another way is by TD(0), a form of temporal difference, which is what DQN uses. You can see me implementing DQN on Atari games in <a href="https://medium.com/nerd-for-tech/reinforcement-learning-deep-q-learning-with-atari-games-63f5242440b1">another post</a>. When sampling the trajectory, we apply updates at each time step, also called online learning, where the parameters are updated while playing out the episode. Here, the target value would be Rₜ₊₁ + γ v(Sₜ₊₁, w), where we estimate the target value by using another estimate, v(Sₜ₊₁, w), a practice called bootstrapping. Unlike MC, we use an estimated target since we are only looking ahead one step so we don’t know the exact future rewards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*1yIsDrmcHYgOayI80PK3lA.png" /><figcaption>Taken from David Silver’s UCL lecture 6 (COMPM050)</figcaption></figure><h3>Forward-view TD(λ)</h3><p>The last method we can use is TD(λ), which is a medium between MC and TD(0). In MC, we can get the exact target value at timestep t since we can “look” from time step t to the end of the episode. In TD(0), we estimate the target value since we can only “look” from time step t to timestep t+1. In TD(λ), we can generalize this by looking N-steps ahead. The target value would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*bGgBPStxC39EjLU-d2MqKg.png" /><figcaption>Taken from David Silver’s UCL lecture 4 (COMPM050)</figcaption></figure><p>and the update equation would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*aeMnz3MaZcP9Kr8Pcwox_w.png" /><figcaption>Taken from David Silver’s UCL lecture 4 (COMPM050)</figcaption></figure><p>There are several ways we can utilize looking N-steps ahead. We can combine different Ns, such as taking the average of 1-step ahead and 2-step ahead. So the question is, how many steps ahead should we look? The answer is not limited to just one N, we can average N-step returns across all Ns to come up with a more robust target value. Instead of averaging the N-step returns normally, we assign a weight to each N-step and sum up all the weighted N-step returns. Now how do we assign the weights?</p><p>One way we can assign the weights is by assigning larger weights to smaller Ns where we look immediately ahead while lesser weights for bigger Ns that will look to the end of the episode. We choose the different weights by following a geometric decay for the weights instead of a linear decay as it is more efficient to compute a geometric sequence. The diagram below is a visual of what this looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*MMwEg7BLvek5BsYN.png" /><figcaption>Taken from David Silver’s UCL lecture 4 (COMPM050)</figcaption></figure><p>The weight is calculated by (1 - λ)λ^(n-1) where n is the number of steps we look ahead and λ is a constant from [0, 1]. Each weight is multiplied by a λ^(n-1) so that the weights will sum to 1. We can observe that changing λ determines how fast the weights decay and how many different Ns we have. The target value would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*zynNdpP962mXF6dQSZcnHg.png" /><figcaption>Taken from David Silver’s UCL lecture 4 (COMPM050)</figcaption></figure><p>This way of looking forward N-steps and taking the average N-step returns is called Forward-view TD(λ). We can update the value function parameters by sampling the whole trajectory then applying offline updates episodically, similar to the Monte Carlo method.</p><p>You may notice that the summation goes to infinity. This is assuming that we have a continuing task that can go beyond the terminal state. However, most of the time this is not true. We can use this equation instead to get the target weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*-J4Edoik7jsIMrM9EK1kvQ.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>Here, we use the same decay from timestep t to timestep T - 1. Then, we use a different term for the terminal state which accounts for the weights from T-1 to infinity. This would ensure that our weights will sum to 1. Here’s a diagram that illustrates the two parts of this equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7FeOt6SiN5J9Vlf_HM9iA.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>We can see that each weight corresponds to a section of the area under the curve and the final weight for the terminal state accounts for the rest of the curve. Here’s the update equation for a Forward-view TD(λ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*OP1mA9bJqqtRbbO_KnSTdQ.png" /><figcaption>Taken from David Silver’s UCL lecture 4 (COMPM050)</figcaption></figure><p>We can also see how MC and TD(0) come from the Forward-view TD(λ). When λ = 1, every N-step weight becomes 0 except for the last one where N-step is the episode length. When λ = 0, the first weight is 1 and all the other weights become 0 so we only look ahead one step.</p><h3>Backward-view TD(λ)</h3><p>Another way to assign weights is by using eligibility traces, called Backward-view TD(λ). The concept of eligibility traces is simple. I’ll give a scenario described in David Silver’s UCL Lecture 4. Suppose you are a mouse. A bell rings three times, a light bulb lights up, then you get shocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*exIwFYELc0q88UPYchoENQ.png" /><figcaption>Taken from David Silver’s UCL lecture 4 (COMPM050)</figcaption></figure><p>Now, is the reason that you got shocked because of the bell or the light? Most people would say it was because of the light because that was what happened right before you got shocked. Someone may think it was because of the bell since the bell rang three times compared to the light going off once. We can think of these two reasonings as the Frequency heuristic, where we assign the blame to the bell since it happened more often, and the Recency heuristic, where we assign the blame to the light since it happened more recently. Eligibility traces combines the two heuristics to assign a weight to each N-step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*QErCg85ZP6Dr4Omck-LTJw.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>We can define the eligibility trace as a vector z, and initialize the trace as 0. We update the eligibility trace by adding the most recent gradient and discount the current trace by the natural timestep discount factor γ and the constant λ. The λ ∈ [0, 1] constant here determines how much you value a frequency versus recency. A high λ would mean the eligibility trace doesn’t decay as fast, so we value frequency more since if the same state appears again, then the trace would be adjusted in the ∇v(Sₜ, w) direction again. A low λ would mean we value recency more as most of the eligibility trace would be determined by the more recent ∇(Sₜ, w). This eligibility trace z would serve as the weight for each N-step.</p><p>So how do we use this z to perform TD(λ)? Here is the pseudocode from Sutton&amp;Barto on how we can use this eligibility trace to update our value function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Coi8FkkFcVpO-NpjblBRow.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>Unlike the Forward-view TD(λ), we can use eligibility traces to perform online updates, where we update the value function at each time step. First, we initialize an eligibility trace z for the current episode. Then, we update the eligibility trace using the aforementioned update equation. Similarly to TD(0), we calculate a loss by using the target value of looking one step ahead. We then update the value function by updating the parameters w in proportion to the eligibility trace.</p><p>We can observe some parallels with Forward-view TD(λ). In Forward-view TD(λ), we average all N-steps by assigning a decaying weight to each N-step. We can only update at the end of the episode as we need to “look forward” from each timestep t to calculate the N-step target value. In Backward-view TD(λ), it seems like we are only looking one step ahead to get the target value. However, this is not true. The eligibility trace is the cumulative weight that has been updated at each timestep and contains information from each state encountered. When we update the value function in proportion to the trace, we are essentially looking N-step backward from time step t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*--yj86-CyEfumSJdTcF2ww.png" /><figcaption>Taken from Sutton&amp;Barto 2017</figcaption></figure><p>We can also see how MC and TD(0) come from Backward-view TD(λ). When λ = 1, the eligibility trace z is only discounted by the time step discount factor γ, so the trace looks backward from time step t to the beginning of the episode, the same as Monte Carlo. When λ = 0, the eligibility trace z is equal to the most recent gradient of the value function, so the trace only looks one step backward. If we sum up all the updates in an episode with λ = 0, the result would be equivalent to all the updates of a TD(0) method.</p><h3>Summary</h3><p>In this post, we’ve covered in detail the different ways we can update the value function, the Critic of an Actor-Critic algorithm. The way to update the value function is by updating the parameters to minimize the loss between the true target value and an approximate value. We’ve gone over three methods, Monte Carlo, TD(0), and TD(λ), of updating the value function in practice and how they choose their target values. Monte Carlo uses Gₜ as an exact target value by looking ahead to the end of an episode, TD(0) uses Rₜ + V(Sₜ₊₁, w) as an estimated target value by looking ahead one step, and TD(λ) constructs an estimated target value by looking N-steps ahead. We’ve also established two kinds of updating mechanisms, offline and online updates. MC and Forward-view TD(λ) are updated at the end of an episode while TD(0) and Backward-view TD(λ) are updated at every step of an episode.</p><p>Overall, this is a very valuable experience for me going more in-depth about approximating value functions. While I was learning about Q learning and implementing DQN, I didn’t really understand the concepts behind approximating value functions and only understood the Bellman equation that is used to update the Q function’s parameters. I then delved into Policy Gradients and learned about how to update the policy parameters for the Actor. Now, with a deeper understanding of how to update the value function parameters for the Critic, I will be exploring and implementing Actor-Critic algorithms in the coming posts.</p><p>References:</p><ul><li><a href="https://www.davidsilver.uk/wp-content/uploads/2020/03/MC-TD.pdf">Model-free Prediction (David Silver’s UCL Lecture 4)</a></li><li><a href="https://www.davidsilver.uk/wp-content/uploads/2020/03/FA.pdf">Value Function Approximations (David Silver’s UCL Lecture 6)</a></li><li><a href="http://incompleteideas.net/book/bookdraft2017nov5.pdf">Reinforcement Learning: An Introduction (Sutton &amp; Barto 2017)</a></li><li><a href="https://papers.nips.cc/paper/1999/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf">Actor-Critic Algorithms (Konda et. al 1999)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8c118dbf723" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/actor-critic-value-function-approximations-b8c118dbf723">Actor-Critic: Value Function Approximations</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Policy Gradients: REINFORCE with Baseline]]></title>
            <link>https://chengxi600.medium.com/policy-gradients-reinforce-with-baseline-6c871a3a068?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c871a3a068</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Sat, 17 Jul 2021 09:56:22 GMT</pubDate>
            <atom:updated>2021-07-19T16:12:13.393Z</atom:updated>
            <content:encoded><![CDATA[<p>After an <a href="https://medium.com/nerd-for-tech/reinforcement-learning-introduction-to-policy-gradients-aa2ff134c1b">introduction to the REINFORCE algorithm</a>, I wanted to explore a little bit further this simple algorithm derived from the policy gradient theorem. In this post, I will be implementing REINFORCE with baseline and some small modifications and testing it out on the CartPole environment. At the end of the post, I go over some bugs I encountered using the Pytorch library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*Zp4fZoqjfkk30BJ8.png" /><figcaption>Taken from Sutton &amp; Barto 2017</figcaption></figure><p>Recall the policy gradient theorem we derived. We have established that the expectation of a sample gradient is equivalent to the actual gradient, so we can rewrite an update equation that takes in a sample action and a sample state. This led us to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*itSGrL9ugXdtk03u.png" /></figure><p>In our implementation of REINFORCE, we used a neural network to help us update our parameters and performed “gradient descent” on the negative gradient, which is basically just a workaround for performing gradient ascent. However, after training for 1000 episodes, we only managed to get an average score of 79.6 over 50 episodes of the agent playing with the learned policy. After looking at the training history, we can notice that there is a high variance in training scores with sudden spikes of scores reaching over 400 and dropping down right after. The slow learning rate and high variance of the REINFORCE method lead us to an improved variation: REINFORCE with baseline.</p><p>Expanding upon the policy gradient theorem, we can further generalize the theorem by adding an arbitrary baseline function we subtract from the state-action value function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*ScgRIWD-edMfZUrl82i_mA.png" /><figcaption>Taken from Sutton &amp; Barto 2017</figcaption></figure><p>This is still the same thing as the previously derived theorem, where b(s) = 0. We can substitute that b(s) function with any arbitrary function or even a constant as long as it does not vary with a. This is because the subtracted quantity is equal to zero as shown below, so the theorem is still valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*OXkVM7UPYXMbjzByVU8oDw.png" /><figcaption>Taken from Sutton &amp; Barto 2017</figcaption></figure><p>Our update equation will also be changed with the baseline function and look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbM7zU5IJepYbYvQmSh9dw.png" /></figure><p>Now for the most important question: what should the baseline function be? A very simple baseline we can use is by applying a <a href="https://en.wikipedia.org/wiki/Whitening_transformation">whitening transformation</a> on the reward. If you’ve looked at other implementations of naive REINFORCE most of them use this technique to decrease variance and remove bias from rewards, but this is also a type of baseline function we can modify the update function with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*i0dYdez7xLrmlrNTMS1PwQ.png" /></figure><p>A more complex baseline we can use is a state-value function. Since the learning for this algorithm is episodic, we can use a state-value function that leans episodically as well. Gₜ - (Sₜ) would just be the difference between what the discounted reward should be at timestep t and what our state value function believes it to be. This would be an easy way for us to adjust the parameters of the state function as well. We can see the pseudo-code for REINFORCE with baseline taken from Sutton&amp;Barto’s textbook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5pyryKULSo-29Gt0ntLzg.png" /></figure><h3>Implementation and Results</h3><p>For my implementation, I used my previous code as a base and cleaned it up a bit. I used a Policy network to learn the parameters θ and a separate network to learn the parameters w. For updating the state value function parameters, I used mean squared error to calculate the difference between Gₜ and v(Sₜ) instead. Here’s a quick peek at my networks:</p><pre>class PolicyNetwork(nn.Module):<br>    <br>    #Takes in observations and outputs actions<br>    def __init__(self, observation_space, action_space):<br>        super(PolicyNetwork, self).__init__()<br>        self.input_layer = nn.Linear(observation_space, 128)<br>        self.output_layer = nn.Linear(128, action_space)<br>    <br>    #forward pass<br>    def forward(self, x):<br>        #input states<br>        x = self.input_layer(x)<br>        <br>        #relu activation<br>        x = F.relu(x)<br>        <br>        #actions<br>        actions = self.output_layer(x)<br>        <br>        #get softmax for a probability distribution<br>        action_probs = F.softmax(actions, dim=1)<br>        <br>        return action_probs</pre><p>State Value Network:</p><pre>class StateValueNetwork(nn.Module):<br>    <br>    #Takes in state<br>    def __init__(self, observation_space):<br>        super(StateValueNetwork, self).__init__()<br>        <br>        self.input_layer = nn.Linear(observation_space, 128)<br>        self.output_layer = nn.Linear(128, 1)<br>        <br>    def forward(self, x):<br>        #input layer<br>        x = self.input_layer(x)<br>        <br>        #activiation relu<br>        x = F.relu(x)<br>        <br>        #get state value<br>        state_value = self.output_layer(x)<br>        <br>        return state_value</pre><p>Here are the hyperparameters I used for this algorithm:</p><ul><li>γ (discount factor): 0.99</li><li>NUM_EPISODES: 1000</li><li>MAX_STEPS: 10000</li><li>α (Policy LR): 0.01</li><li>β (Value LR): 0.1</li></ul><p>Let’s first look at the results of using a simple baseline of whitening rewards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*cLx4NhXy2Lm8HeDyRTuYmg.png" /></figure><p>Our agent was able to achieve an average score of 234.4 over 50 episodes when playing by our learned policy. This is better than the score of 79.6 with the naive REINFORCE algorithm. However, only using whitening rewards still gives us a high variance in training scores. In fact, there was one trial where the model parameters were stuck at a suboptimal local maxima:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*RAAdNtOJVvA6XDeYWUpTTQ.png" /></figure><p>Let’s see our results of using a learned state-value function as our baseline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*y_XbsK6fpC4UfQZ-jUwVAg.png" /></figure><p>Our agent achieved an average score of 500 over 50 episodes, which is the max score using our learned policy! This is far better than an average score of 79.6 without the baseline. Here is a quick demo of our agent in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*UKxB0ydGa6idVMoC7-f9_w.gif" /></figure><p>Looking at the training history, it is clear that there is an upward trend in the score. Although there is still some instability, it is far less than the previous training history with constant up and down fluctuations. We can also observe a pattern in the training history. The agent achieves a score plateau of 500 around 100 episodes in before dropping down and “relearning” until episode 400 where it drops again. This pattern repeats itself throughout the 1000 episodes. This behavior can be explained by a similar phenomenon that occurs in Q-learning which we solved through experience replay, called <a href="https://en.wikipedia.org/wiki/Catastrophic_interference">catastrophic forgetting</a>. The network becomes adjusted to fit new inputs and “forgets” the old inputs which can lead to performance collapse. A way we can fit this could be to implement some conditions for the agent to stop training to prevent overfitting.</p><p>According to the <a href="https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py">CartPole documentation</a>, the environment is considered solved when the agent has an average score of 195 over the last 100 episodes. If we look at our training history, our network easily scored over 195 in under 100 episodes of training. Let’s increase the solved score to 450 instead, with some leeway for variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*y8pkNCLXC6YN_q-S53OkEA.png" /></figure><p>We were able to achieve an optimal policy in just 584 episodes, a ~50% increase in training speed! Testing this learned policy over 50 episodes gave us an average score of 500, the maximum score.</p><p>Looking at the training history without early stopping, we can observe a huge discrepancy in the pattern of learning. With this run, the agent achieves top scores with high variance before stabilizing around 500 episodes. In the previous training history, there were three instances of the agent learning the optimal policy at episodes 100, 350, 700, before collapsing. The poor reproducibility of results is due to the stochastic nature of REINFORCE and is still a huge problem in the field of Reinforcement Learning. I ran the experiment four more times and achieved an average stopping point of 400.6 episodes over 5 trials with all trials having an average score of 500 over 50 episodes when playing with the learned policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgbEoBa02fSffVppHuwirA.png" /></figure><h3>Final Thoughts</h3><p>Although I did not expect to spend a long time on this, I did run into a lot of bugs on Pytorch due to my lack of understanding of the library. When I was trying to backpropagate my policy network after updating the value network, I kept on running into an error: <em>“RuntimeError: Trying to backward through the graph a second time…”. </em>This was because I did not use a tensor to calculate my policy loss and tried to call loss.backward().</p><p>So what went wrong here? In Pytorch, a tensor is not only used to perform operations like a NumPy array but it also tracks the tensor inputs and functions used on the tensor, forming a directly acyclic graph where the roots are the final output of the tensor and the leaf nodes are the input tensors. When we call loss.backward(), Pytorch backpropagates by traversing from the loss (root node) to the leaf nodes, kind of like the chain rule. By not using a tensor to calculate policy loss, the network didn’t know how to backpropagate and assumed that I was trying to backpropagate through the DAG formed by the value network a second time.</p><p>Overall, I learned a lot from what I thought was going to be a short continuation of REINFORCE and hopefully can slowly build up to more state-of-the-art policy gradient methods that can deal with a continuous action space.</p><p>My code: <a href="https://github.com/chengxi600/RLStuff/blob/master/Policy%20Gradients/REINFORCE-Baseline.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Policy%20Gradients/REINFORCE-Baseline.ipynb</a></p><p>References:</p><ul><li><a href="http://incompleteideas.net/book/bookdraft2017nov5.pdf">Reinforcement Learning: An Introduction (Sutton &amp; Barto 2017)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c871a3a068" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning: Introduction to Policy Gradients]]></title>
            <link>https://chengxi600.medium.com/reinforcement-learning-introduction-to-policy-gradients-aa2ff134c1b?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa2ff134c1b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Wed, 14 Jul 2021 04:59:39 GMT</pubDate>
            <atom:updated>2021-07-19T16:11:58.278Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous posts, I have been working on a form of Reinforcement learning, Q learning, where the agent finds an optimal policy that maximizes the total reward over a trajectory of states. I later expanded on Q learning with deep neural networks and explored the implementation of DQN. In this post, I wanted to explore a different approach of reinforcement learning called policy gradients which aims to optimize the policy directly. Unlike Q learning, the agent does not select the best action based on state-action values but rather from a probability distribution of actions. I will be showing the proof of the policy gradient theorem and a naive algorithm, REINFORCE (Williams 1992), that uses this derivation. Surprisingly, Williams was a professor at Northeastern University, where I’m studying right now!</p><h3>Introduction</h3><p>First, let&#39;s define some terms. Unlike an epsilon greedy algorithm that chooses the max value action with some noise, we are selecting an action based on the current policy. π(a | s, θ) = Pr{Aₜ = a | Sₜ = s, θₜ = θ}, which is the probability of an action a at timestep t given the state s at timestep t and the policy’s parameters θ at timestep t.</p><p>Now, the agent will learn the policy based on the gradient of a performance measure function J(θ) with respect to θ. We will be using gradient ascent to adjust the policy parameters to find the optimal policy: θₜ₊₁ = θₜ + α∇J(θₜ).</p><p>When dealing with the policy function π, we can preserve the concept of exploration by ensuring that π(a | s, θ) ∈ (0, 1) so the policy will not become deterministic. For parameterized numerical preferences we come up with a value h(s, a, θ) for a state-action pair. We can use softmax to turn this into a probability distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*q0bMxaQ_tST4RdDgLhHfhQ.png" /></figure><p>There are some advantages in selecting actions according to a softmax over action preferences rather than an epsilon greedy strategy. First, action preferences allow the agent to approach a deterministic policy, whereas epsilon greedy will need to maintain some degree of noise to encourage exploration. Action preferences are also focused on building an optimal stochastic policy rather than converging on a value. This means that if the policy is deterministic, then the probability of the best action will be driven to approach 1. If the best policy is to be stochastic, then the action preferences will form a probability distribution. With an epsilon greedy strategy, there is no natural way to form a stochastic policy.</p><p>Another advantage is that the action probability is adjusted smoothly over a function of the policy parameter. With an epsilon greedy strategy, a small change in Q value can result in a different action if we are selecting an action based on max value. This can dramatically overestimate the importance of a selected action and converge into a suboptimal policy.</p><p>Now let’s see how the agent can learn the parameters of an optimal policy. Remember that we will be adjusting our parameters based on a performance measure function J(θ). This brings us to the policy gradient theorem, which lets us approximate the gradient of J(θ) with respect to θ without a derivation of the state distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*cBTi8zEzgg-hTQDMDPBbvA.png" /><figcaption>Taken from Sutton &amp; Barto, 2017</figcaption></figure><p>μ(s) here is an on-policy distribution of our stochastic policy π. q is an action-value function following policy π, and π(a|s, θ) is the action distribution given a state under parameters θ.</p><p>This solves the problem of needing to know the state distribution in an unknown environment. The following proof (<a href="http://incompleteideas.net/book/bookdraft2017nov5.pdf">Sutton &amp; Barto, 2017</a>; Sec. 13.2) will be a detailed walkthrough with help from <a href="https://lilianweng.github.io/lil-log/2018/04/08/policy-gradient-algorithms.html">Lillian Weng’s article</a>.</p><h3>Derivation of Policy Gradient Theorem</h3><p>Define J(θ) = V_πθ(s), where V is the value function for policy π with parameters θ. Then we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*Bv_VVE1r7E4HNqOnFbyF_g.png" /></figure><p>We can expand the value function to be similar to that of an expectation equation, where we find the summation of the probability of an action following policy π multiplied by the value of a state-action pair following policy π, for all actions in the action space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*SJ1fMxo6I3IfjUVQNDGXAQ.png" /></figure><p>Then in (3), we apply the product rule: d/dx [f(x)g(x)] = f’(x)g(x) + f(x)g’(x). In (4), we expand on the q function. As we stated before, the q function gives us a value given a state-action pair. If we assume the environment is non-deterministic, then the next state will also be non-deterministic. We multiply the probability of a new state s’ and reward r given a state-action pair and the reward + value function of next state s’. This gives us the expected value of the resulting new state s’. We then take the summation over all possible new states. Notice that the reward uses a fundamental concept in reinforcement learning, where we must take account of current rewards and the future utilities as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*zjU3Op8hexR0RADxsr3ZcA.png" /></figure><p>We can simplify p(s’, r | s, a) to p(s’ | s, a) as the summation of all rewards in p(s’, r | s, a) is the same as p(s’ | s, a). Then, we can move past p(s’, r| s, a) since r is not a function of θ (the gradient is with respect to θ). The reward goes away as it is a constant.</p><p>Recall the line (1) of our derivation, ∇J(θ) = ∇v(s). Notice the similar term v(s’) at the end of our expanded equation. We can observe that ∇v(s) is recursive. Let&#39;s try to expand a bit on the recursion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*2FL1x3xPpS8FXCiYSfynjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*VHr-N82hnQ_xs1rqumHh7A.png" /></figure><p>As you can see, in line (8), we replaced the term ∇v(s’) with what we derived so far, except for the transition s’ to s’’. We can define this transition to simplify the equation a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*lRP9nJGPQWUsAUQbji0Yew.png" /></figure><p>The function above is the probability of a transition from state s to state s’ in k steps following policy π. We can then revise steps (6) and (7) to use this but also remember to keep the summation over all possible next states s’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*6_F2LfIvYBNvtZMY_F0ILg.png" /></figure><p>We can simplify even further. If we distribute the multiplied terms, we can combine Pr(s → s’, k=1) with Pr(s’ → s’’, k=1) to get Pr(s → s’’, k=2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*-uRaL4lxCF-9-TY-93hVsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*TShIpODDu5PNhcERAVYlwA.png" /></figure><p>After repeatedly unrolling the recursive bit, we can write this as a summation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*QJPqXIBPiEQtVTfV5OxfHg.png" /></figure><p>Here we have the summation over all goal states x over all possible length k steps of the transition from starting state s to state x. Note that at k = 0, Pr(s → s, k=0, π) is trivially 1, so we have not left out the first ϕ(s) term.</p><p>Now we can move towards the conclusion of the proof.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*69sXgsFgXNQot-KUZbrsRA.png" /></figure><p>On line (12), we have the distribution of the transition from starting state s0 to end state s for any k length steps which we simplify to η(s). Then on line (14), we normalize η(s) to be a probability distribution ∈ (0, 1) for each end state s. We have then constructed μ(s), which is the probability distribution of actions following our stochastic policy. When we expand the ϕ(s) function, we have proven the relation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*cBTi8zEzgg-hTQDMDPBbvA.png" /><figcaption>Taken from Sutton &amp; Barto, 2017</figcaption></figure><h3>REINFORCE algorithm</h3><p>Now with the policy gradient theorem, we can come up with a naive algorithm that makes use of gradient ascent to update our policy parameters. The theorem gives a sum over all states and actions but when we update our parameters, we are only going to be using a sample gradient since there&#39;s just no way we can get the gradient for all possible actions and states. We can write this as an expectation as the expectation of a sample gradient is the same as the actual gradient. Thus we have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-uyOz7SKdqZVU9ns7Wj_g.png" /></figure><p>Notice that we have replaced s with Sₜ in (2). This is because we are formulating the equation to take in a sample gradient, where we are using a sample state Sₜ and a sample action Aₜ, instead of a summation over all states and actions. Now, let&#39;s replace the summation of all actions with a sample action Aₜ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jc0TGpqb-jSVu0s-JJPCJA.png" /></figure><p>In (3), we multiple the value by the term at the end so that the value of a sample action is weighted by the probability of selecting the action. Then in (4), we can get rid of the summation over all actions and replace a with a sample action Aₜ. In (5), we can replace the state-action value function with Gₜ, the cumulative discounted reward at timestep t. Then, we can simplify the equation using the fact d/dx[ln(x)] = 1/x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*XpqigJ970nKU2P6QsGa4RA.png" /></figure><p>We can then use this term inside the expectation to perform gradient ascent to update our policy parameter. We can use this update in the naive REINFORCE algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1I6E6g7H62ICQ-g22EmOA.png" /><figcaption>Taken from Sutton &amp; Barto, 2017</figcaption></figure><p>Notice that this algorithm is a type of Monte-Carlo method, as we are not updating the parameter after every timestep but rather episodically sampling a whole trajectory with a static parameter θ, then updating the parameter. In the pseudocode above taken from the textbook (Sutton &amp; Barto, 2017), the update line is slightly wrong as we should not be updating the same parameter that we are using to get the policy log probability. In our implementation, we can simply accumulate the gradient and update the parameter at the end of the episode all at once. Now let’s get to the implementation!</p><h3>Implementing REINFORCE</h3><p>For my implementation of REINFORCE, I decided to use Pytorch instead of Keras as I wanted to explore other machine learning libraries. For the policy parameter, I used a neural network as it can do the gradient ascent for me. Note that I will be adding a negative sign in front of the gradient to perform gradient ascent instead of gradient descent. Here’s my network:</p><pre>#Using a neural network to learn our policy parameters<br>class PolicyNetwork(nn.Module):<br>    <br>    #Takes in observations and outputs actions<br>    def __init__(self, observation_space, action_space):<br>        super(PolicyNetwork, self).__init__()<br>        self.input_layer = nn.Linear(observation_space, 128)<br>        self.output_layer = nn.Linear(128, action_space)<br>    <br>    #forward pass<br>    def forward(self, x):<br>        #input states<br>        x = self.input_layer(x)<br>        <br>        #relu activation<br>        x = F.relu(x)<br>        <br>        #actions<br>        actions = self.output_layer(x)<br>        <br>        #get softmax for a probability distribution<br>        action_probs = F.softmax(actions, dim=1)<br>        <br>        return action_probs</pre><p>After implementing the algorithm, I tested my results with the following parameters:</p><ul><li>γ (discount factor): 0.99</li><li>NUM_EPISODES: 1000</li><li>MAX_STEPS: 10000</li></ul><p>First, let&#39;s look at how our agent does with a random policy over 150 episodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*jfXeE9Vpae7btuFW.png" /></figure><p>Unsurprisingly, these were some subpar results, with an average score of 21.48. Now, let’s look at the training history of our algorithm over 1000 episodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*JPYvWUlQMQa1sUcvrBXdcg.png" /><figcaption>Cumulative reward each episode</figcaption></figure><p>Looking at our training history, we can see that our agent slowly learns over time. However, we notice that compared to other learning methods such as DQN in my <a href="https://medium.com/nerd-for-tech/first-look-at-reinforcement-learning-67688f36413d">previous post</a>, the learning is slow and has high variance. This is to be expected as the REINFORCE algorithm is less complex compared to one that uses a deep neural network. Nonetheless, we were able to achieve an average score of 79.6 over 50 episodes using the learned policy, which is better than the human benchmark (me) of 30.8.</p><p>Overall, this was a great introduction to the class of policy gradient methods, which I had a harder time understanding than Q-learning that I learned from my CS4100 lectures. I thought it was interesting trying to understand all the derivations and reasoning behind each equation following Sutton &amp; Barto’s textbook and it gave me a stronger understanding of the topic. Moving forward, I definitely want to learn more about policy gradient methods and also Pytorch which I played around a little bit while implementing REINFORCE.</p><p>My code: <a href="https://github.com/chengxi600/RLStuff/blob/master/Policy%20Gradients/REINFORCE.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Policy%20Gradients/REINFORCE.ipynb</a></p><p>References:</p><ul><li><a href="http://incompleteideas.net/book/bookdraft2017nov5.pdf">Reinforcement Learning: An Introduction (Sutton &amp; Barto 2017)</a></li><li><a href="https://lilianweng.github.io/lil-log/2018/04/08/policy-gradient-algorithms.html">Policy Gradient Algorithms (Lilian Weng)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa2ff134c1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning: Deep Q-Learning with Atari games]]></title>
            <link>https://chengxi600.medium.com/reinforcement-learning-deep-q-learning-with-atari-games-63f5242440b1?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/63f5242440b1</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Thu, 08 Jul 2021 05:35:27 GMT</pubDate>
            <atom:updated>2021-07-19T16:12:33.955Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous post <a href="https://medium.com/nerd-for-tech/first-look-at-reinforcement-learning-67688f36413d">A First Look at Reinforcement Learning</a>, I attempted to use Deep Q learning to solve the CartPole problem. In this post, I will be further exploring Deep Q learning but in the context of Atari games.</p><p>In 2013, the paper by the Deepmind team <a href="https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf">Playing Atari with Deep Reinforcement Learning</a> (Mnih et. al) explored the notion of using Deep Q learning on Atari games. The goal was to present a deep learning model that could deal with high dimensional inputs and achieve superhuman benchmarks across different Atari games with no adjustment in the underlying architecture of the model. After reading the paper, I wanted to try and implement such a model and hopefully be able to train an agent to play some classic Atari games such as Breakout or Pong. I will also be implementing ideas on the follow-up paper <a href="http://files.davidqiu.com//research/nature14236.pdf">Human-level control through deep reinforcement learning</a> published in the British journal Nature. In addition, I will also talk about a modification we can add called Double DQN.</p><p>Firstly, I needed to choose an environment for this problem. When I first started this project, I wanted to try and solve the game Tennis. However, after a couple of hours of training my model, the results were no better than random play. Looking at my training parameters, I had only trained my agent for about 50 episodes, where each episode took a maximum of 200 frames to finish. So in total, about 10,000 frames. Looking at the Deepmind paper, they had trained their agent over 10 million frames. While my 10,000 frames took about 1.5 hours to run, 10 million frames would’ve taken me 2 months! In the end, I decided to go with Pong, one of the easier games to learn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*7CZhntvUjDQ4iVGd.gif" /><figcaption>A bot (left) playing against an RL agent (right)</figcaption></figure><h3><strong>Environment Setup</strong></h3><p>For this experiment, I will be using OpenAI’s gym library with prebuilt environments. Note that currently, the only environment in OpenAI’s atari-py package is Tetris, so you will have to import ROMs from elsewhere. I will be including the file in my code at the end of the post. Here is the environment:</p><pre>#initial environment<br>env = gym.make(&#39;PongNoFrameskip-v4&#39;)</pre><pre>#Atari preprocessing wrapper<br>env = gym.wrappers.AtariPreprocessing(env, noop_max=30, frame_skip=4, screen_size=84, terminal_on_life_loss=False, grayscale_obs=True, grayscale_newaxis=False, scale_obs=False)</pre><pre>#Frame stacking<br>env = gym.wrappers.FrameStack(env, 4)</pre><p>In the first line, I initialize the environment ‘PongNoFrameskip-v4’. The format that gym takes is a concatenated string of [‘Game][‘NoFrameskip’, ‘Deterministic’, None][‘-v0’, ‘-v4’]. Here’s a quick explanation of each term:</p><ul><li>“NoFrameskip”: Each step of the environment is one frame</li><li>“Deterministic”: Each step executes the same action for k frames and returns the kth frame. k = 4.</li><li>None: Same as “Deterministic” but k is sampled from [2, 5].</li><li>“-v0”: Each step has a 0.25 probability of repeating the previous action</li><li>“v4”: Each step will follow your issued action</li></ul><p>In the second line, I apply some preprocessing that was detailed in the Nature paper. The Atari wrapper follows the guidelines in Machado et al. (2018), “Revisiting the Arcade Learning Environment: Evaluation Protocols and Open Problems for General Agents”. A quick explanation of each parameter:</p><ul><li>NoopReset: obtain initial state by taking a random number of no-ops (no action) on reset.</li><li>Frame skipping: 4 by default</li><li>Max-pooling: Takes the max pixel value of most recent observations to remove the flickering effect in some Atari games.</li><li>Termination signal when a life is lost: turned off by default. Not recommended by Machado et al. (2018).</li><li>Resize to a square image: 84x84 by default</li><li>Grayscale observation: Converts observation to grayscale</li><li>Scale observation: Scales observation to [0, 1]</li></ul><p>Note that we will not scale the observation and keep value type as uint8 for more efficient memory storage and will only scale before feeding it into the model.</p><p>The third line stacks every k frames into one observation. This will give the model an idea of how an action plays out rather than just having the input be a still frame. Note that this does not mean we are grouping every k frames together, the observations are stacked for each frame so they will be overlapped. Our observation dimension should be (4, 84, 84) where inputs are images of size 84x84 and stacked with the last 4 frames. An interesting thing to note about the preprocessed observations is that the Nature paper chose to keep the in-game score rather than crop it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*ALngFl2kDNAYIP5lmUzICA.png" /><figcaption>The score is outlined in a black box</figcaption></figure><h3><strong>Implementing Deep Q Learning</strong></h3><p>We will be using an epsilon-greedy algorithm for choosing the best action, where there is an epsilon chance of sampling a random action from the action space. Instead of using epsilon decay, we will be using linear annealing to decrease epsilon from 1 to 0.1 over 1 million frames by Deepmind’s specification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*oOnAlIDHVPRaEb5E1AA2xg.png" /></figure><p>Similar to the baseline Deep Q-learning algorithm I described in my previous post, we will be using a neural network to learn the Q values of a particular state instead of a lookup Q table. This is because with a more complex environment such as Atari games, the memory needed to store all possible states is too inefficient and it would require a far longer time for the Q values to converge. We will be using the following equation to get the target Q value and let the network update its weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W1XNDmp5q8itrR1J.png" /><figcaption>Target q value for a given state and action</figcaption></figure><p>As we are dealing with images as inputs, the network will be a convolutional neural network. As detailed in the Nature paper,</p><blockquote>The input to the neural network consists of an 84 × 84 × 4 image produced by the preprocessing map w. The first hidden layer convolves 32 filters of 8×8 with stride 4 with the input image and applies a rectifier nonlinearity. The second hidden layer convolves 64 filters of 4×4 with stride 2, again followed by a rectifier nonlinearity. This is followed by a third convolutional layer that convolves 64 filters of 3×3 with stride 1 followed by a rectifier. The final hidden layer is fully-connected and consists of 512 rectifier units. The output layer is a fully-connected linear layer with a single output for each valid action.</blockquote><p>My implementation in Keras is shown below:</p><pre>model = Sequential(<br>    [<br>        Lambda(lambda tensor: tf.transpose(tensor, [0, 2, 3, 1]), output_shape=(84, 84, 4), input_shape=(4, 84, 84)),<br>        Conv2D(32, kernel_size=(8, 8), strides=4, activation=&quot;relu&quot;, input_shape=(4, 84, 84)),<br>        Conv2D(64, kernel_size=(4, 4), strides=2, activation=&quot;relu&quot;),<br>        Flatten(),<br>        Dense(512, activation=&quot;relu&quot;),<br>        Dense(env.action_space.n, activation=&quot;linear&quot;),<br>    ]<br>)</pre><pre>rms = tf.keras.optimizers.RMSprop(learning_rate=0.00025, rho=0.95, epsilon=0.01)<br>model.compile(loss=&quot;mse&quot;, optimizer=rms)</pre><p>In my implementation, I included a Lambda layer that converts the inputs of the format NCWH (Batch, Channel, Width, Height) into NWHC. This is because as I’m training my model with CPU (couldn&#39;t configure GPU), the format NCWH is not supported. If you are training on GPU, then you can ignore the Lambda layer and use (4, 84, 84) as the input shape of the first Convolutional layer. The specifications of the optimizers are detailed in the Nature paper. For more information about RMSprop, I found this <a href="https://towardsdatascience.com/understanding-rmsprop-faster-neural-network-learning-62e116fcf29a">article</a> to be very helpful.</p><p>We will also be using experience replay and keep track of past transitions in a “memory” array. The parameters described in the paper store up to 1 million transitions in memory. The memory will be prefilled with 50000 transitions from random play. During minibatch updates, a batch will be uniformly sampled from the memory to be used for training. The paper also mentions a more sophisticated strategy that emphasizes transitions where the model learns the most, similar to <a href="https://link.springer.com/article/10.1007/BF00993104">prioritized sweeping</a>. Another modification is detailed in the paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*otZunpxjrrlowHEIVDrs8A.png" /></figure><p>The modification states to clone the network every C updates and uses the cloned network as a target network for the target Q value and trains the online network rather than using the same network for both tasks. This is to reduce instability in the network as every time we update the network, the target will change as well. Using a target network will ensure the target doesn’t change for C updates. As you can see below, the differentiated loss function uses model parameters θᵢ for the current Q value and cloned model parameters θᵢ⁻ for the target Q value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*Cf69tmyvWLh3g9-OoRD2XA.png" /><figcaption>Gradient when differentiating the loss function</figcaption></figure><p>A summary of the algorithm is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*ljyyQeR1cQ-sFJERtantHw.png" /></figure><h3>Double DQN</h3><p>Another modification we can make to this algorithm is called Double Deep Q Learning. In the paper <a href="https://arxiv.org/pdf/1509.06461.pdf">Deep Reinforcement Learning with Double Q-learning</a> (Hasselt et. al 2015), the problem of overestimating q values is addressed. Although having overoptimistic values isn’t necessarily a bad thing, it can negatively affect the resulting policy if action values are not uniformly skewed.</p><p>The change proposed in the paper is regarding the target value during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*iQayJ3PkXUS8onv8-SsJXg.png" /></figure><p>When we use a neural network to train our agent, we want to update our model based on the difference between what our model thinks its Q value is versus what our model thinks the Q value should be. The equation above shows that our target is the reward + discounted future utility, where we use a neural network to predict action values and select the highest one. The problem here is that we are using the max operator, where we are using the same values to select an action and also evaluate that action. This can lead to over-optimistic value estimates, so we want a way to decouple selection from evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*9odKBFz1Tt2XWRz2lgW0NA.png" /></figure><p>The equation above is how we adjust the DQN target equation. Instead of using the max operator to choose the best action and get the value of the action at the same time, we are using argmax to select an action using network Q with weights θₜ and then evaluating that action using network Q with another set of weights θ′ₜ. The paper combines the concept of Double Q learning with DQN to create a simple Double DQN modification, where we can use the target network as weights θ′ₜ and the online network as weights θₜ.</p><p>Let’s take a closer look at how the overestimation causes a suboptimal policy. Take this theorem proposed in the paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*OqE9GqCiQQabROeFwQ_HIQ.png" /><figcaption>The proof can be found in the paper (Check sources below for link)</figcaption></figure><p>When we have unbiased error such that the sum of differences of action values between true optimal network V and arbitrary network Qₜ with a mean squared error C &gt; 0, we can derive a tight lower bound: √(C/m-1), where m is the number of actions. With Double Q-learning, the lower bound on the error is 0.</p><pre>#action selection with online network<br>best_future_action = np.argmax(model.predict(np.expand_dims(new_state, axis=0)))</pre><pre>#action evaluation with target network<br>target = reward + discount_factor * target_model.predict(np.expand_dims(new_state, axis=0))[0][best_future_action]</pre><h3>My results</h3><p>After implementing the algorithm, I was ready to train my agent. However, I did severely underestimate the training time. In the Nature paper, they trained the agent for 50 million frames, an equivalent of 38 days of playing time. As for me, I chose to use an easier Atari game that would take a shorter time to converge, which is around 750,000 frames according to some examples I’ve seen. Even with the reduced training time, training on my local CPU would’ve taken days, and I had run into memory issues. I decided to train my model for 200,000 frames with other hyperparameters being scaled to the number of trained frames.</p><p>First, let&#39;s see how we did with a random policy. Over 150 playthroughs, the random policy had an average score of -20.273, where the score is calculated by Cpu score - Agent score, and the game ends at 21 points. As expected, the random policy is not very good compared to the human benchmark of -3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*OXGbiKw449ABBJS8gkL-pg.png" /></figure><p>After training my model, I did not get the results I expected. The score did not improve over time and the resulting policy was just as good as a random policy. Checking the training loss history, it did seem like the model was reducing loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*VGII_ZDOUPzQKX6gB252-A.png" /><figcaption>Training Pong over 150 episodes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*wps_eTl2xBHxPIXIAnixOQ.png" /><figcaption>Training Loss of Pong</figcaption></figure><p>So why was my model not training? A couple of hypotheses on why this was happening. First, I was scaling down all hyperparameters and moving from 10 million frames trained to 200,000 frames. Although everything is still to scale, there is a major problem. The number of frames it takes to solve the problem is still the same. As I’m decreasing epsilon over the first 20,000 frames, the learned policy is still just as good as random policy.</p><p>Secondly, this could be due to the sparse nature of rewards in Pong. In the CartPole environment, we rewarded the agent for each timestep that the pole was upright. This kind of feedback allowed for the agent to quickly distinguish between good and bad actions. We then modified the reward to be scaled with the pole angle for even more precise feedback. This is a different case for DQN however. DQN was first proposed as a general solution to solve all Atari game environments given an image input. As such, we aren’t able to assign more precise rewards, and the reward system used for Pong is either -1 or 1 for scoring a point. This means there are far fewer rewards the agent learns from in each play-through, and there are tons of frames in between each reward which makes it harder for the agent to grasp the future utility of an action.</p><p>After a sanity check using the CartPole environment with similar hyperparameters as the last post, we had the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*Pb6etgeVdbzT-AKi9AeWDg.png" /></figure><p>Phew. At least the algorithm does work and the agent will learn in an easier environment. Comparing this to a baseline DQN implementation detailed in the 2013 paper, we had gotten similar results, with an average score of 476 over 10 episodes.</p><p>Overall, this was a fun experience and I got to go more in-depth about the DQN algorithm, adding in Target Networks and a naive Double Q Learning implementation. There are still improvements that can be made such as prioritized sweeping and Dueling Networks, but that&#39;s to be explored in the future. Although DQN was the first model used for solving Atari games with image inputs, the fact remains that DQN does have a long training time and slow convergence rate. In the future, I will be exploring other kinds of algorithms such as Deep Deterministic Policy Gradient (DDPG) for continuous actions, Proximal Policy Optimization, A3C, and more!</p><p>My code: <a href="https://github.com/chengxi600/RLStuff/blob/master/Q%20Learning/Atari_DQN.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Q%20Learning/Atari_DQN.ipynb</a></p><p>Sources:</p><ul><li><a href="https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf">Playing Atari with Deep Reinforcement Learning</a> (Mnih et. al 2013)</li><li><a href="http://files.davidqiu.com//research/nature14236.pdf">Human-level control through deep reinforcement learning</a> (Mnih et. al 2015)</li><li><a href="https://arxiv.org/pdf/1509.06461.pdf">Deep Reinforcement Learning with Double Q-learning</a> (Hasselt et. al 2015)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63f5242440b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A First look at Reinforcement Learning]]></title>
            <link>https://chengxi600.medium.com/first-look-at-reinforcement-learning-67688f36413d?source=rss-49de4e2f5a53------2</link>
            <guid isPermaLink="false">https://medium.com/p/67688f36413d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Cheng Xi Tsou]]></dc:creator>
            <pubDate>Sun, 27 Jun 2021 13:37:48 GMT</pubDate>
            <atom:updated>2021-07-19T16:12:43.933Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the types of learning that we hear about in Machine Learning is Reinforcement Learning, where an agent learns a goal in an environment, known or unknown, through reward and punishment. Unlike learning methods such as Supervised and Unsupervised learning, Reinforcement learning does not require data at all. In my class CS4100, the course briefly touched on the practices of this learning method so I wanted to explore a bit further. A lot of the applications of Reinforcement learning are in games or complex and computationally expensive real-world problems, so it is hard to find something to “meaningfully” apply reinforcement learning to. Nonetheless, this is still a super interesting topic where an agent can build a policy that maximizes the reward function without knowing its environment. I wanted to explore a high-level view of reinforcement learning so I’ll be playing around with OpenAI’s gym library where it has prebuilt environments with defined observation and action spaces with assigned reward values to different states.</p><p>A simple task I tackled first was the FrozenLake game. The game is simple, the environment is a 4 by 4 tiled square where the player starts at the S square and navigates to the G square. Falling into a hole, or the H square means game over. The implementation of this game in the gym library has a simple reward function. 1 if the agent reaches the goal, 0 if they don’t. The action space is just the four cardinal directions and the observation space is the 16 possible squares that a player could be in. The game also has a catch: the floor is slippery and there’s a chance you could go in a random direction every move. However, for the sake of seeing whether the built policy works, I’ll be turning the slippery mode off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*YOvEDDaGFCaBCPpT.png" /><figcaption>Non-slippery frozen lake</figcaption></figure><p>So how does an agent build its policy? There are many different ways to implement Reinforcement learning such as value or policy iteration, solving MDP, TD-learning, but I will exploring Q-learning.</p><p>In Q-learning, an agent wants to maximize a ‘Q’ value, which is a value that is mapped to from a particular state and action. At the start, a Q table will be initialized where the cardinality of Q(s, a) is <em>action space</em> × <em>observation space</em>. An agent plays the game over many episodes and builds the q table along the way.</p><p>Firstly, an agent chooses a move. A strategy I’ll be using the epsilon-greedy algorithm, where for some chance epsilon, an agent will choose a random action. Otherwise, it will choose the action with the highest Q value. Epsilon is a balance between exploration vs exploitation, and usually, there&#39;s an epsilon decay factor where the chance for exploration goes down as the number of iterations increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DzP5kD__wc1hZs1F.png" /><figcaption>Epsilon greedy algorithm</figcaption></figure><p>After the agent chooses an action, we will use the equation below so the agent can “learn”. In the equation, max_a Q(S_t+1, a) is the q value of the best action for the next state after the agent executes its action. Q(S_t, A_t) is the q value of the current state. The q value for the next state is multiplied by gamma, a discount factor since it is one time-step away, a concept where future rewards are worth less than immediate reward. R_t+1 is the reward after you execute the action. Together, reward + the difference between discounted future utility and current utility is what the agent thinks the current q value should be. The target value is multiplied by alpha, the learning rate to nudge the current q value towards the “true” q value, which the agent will learn over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E0bJTTdeJ_5CKEH1.png" /><figcaption>Update equation</figcaption></figure><p>After letting the agent learn for 10,000 episodes, we built a policy that chooses the best action for each state. Note that since FrozenLake without slippery floors is deterministic, so this is possible to solve with dynamic programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*HIC4snJqIYsgOucU63A_bg.png" /><figcaption>Our policy after 10000 iterations. Each letter corresponds with an action: Down, Up, Left, Right.</figcaption></figure><p>Plotting the reward over episodes gives us a very weird-looking graph. Since the reward is binary, either you reach the goal or not. You can see that the puzzle is consistently solved in around 4000 episodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*b60nGyUbE5RukSQB-0w-oA.png" /></figure><p>While all this is simple and computationally cheap, the FrozenLake problem only requires a q-table of 4*16 = 64 size. What if we wanted to use Q-learning for a more complex environment? Let&#39;s take the CartPole problem as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*SWGYqDqsRSR8w6qS.gif" /><figcaption>OpenAI gym’s CartPole-v1</figcaption></figure><p>The CartPole problem is a game where a pole is balanced on a cart that can be pushed to the left or right. The possible actions for this problem are only applying a force of +1 or -1. However, the observation space is continuous. A given state in the observation space is made of the cart position, cart velocity, pole angle, and pole angular velocity. A q-table would not work in this case. This is where Deep Q-learning comes in.</p><p>In Deep Q-learning, instead of a lookup table Q(s, a), we can think of Q(s, a) as a function. If we review the Q update equation, it&#39;s similar to how a neural network learns. The “target” which is reward + discounted future utility is what the q value should be. Q(S_t, A_t) is what the model thinks the current q value is. The difference between them would be the loss, and we can slowly update the weights of the network with a learning rate. With a neural network, we can fit the network by supplying states and target q value, and the network will return the action space and q values for each action when we use it to predict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E0bJTTdeJ_5CKEH1.png" /><figcaption>Update equation</figcaption></figure><p>The reward system for the CartPole game is simple. For each time step that the pole was upright, you would get +1. After trying to implement Deep Q-learning for the CartPole game, I was getting an average of 10 points despite running the algorithm for 100 episodes. In fact, after a while, the epsilon decay causes epsilon to approach 0, so the Q function converged to a sub-optimal policy. The problem was as we were fitting the network with the latest state, the model will slowly “forget” about past obstacles it had and go back to square one. Although the model does learn how to get past a certain obstacle, later states will not encounter that obstacle, so the network’s weights will shift away from the solution to that obstacle.</p><p>A solution for this is experience replay. We keep “memories” of past states and actions and replay those memories to keep the model informed of its past. An implementation of experience replay would be to keep an array of (state, action, reward, new_state, isOver) tuples, where the network is fit with a random batch of states instead of just fitting the latest state. Using this method, the agent achieved an average score of 430.26 over 50 plays when testing out the policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*BNWxeZnnvsQk0yioPSQn6A.png" /><figcaption>Agent training over 150 episodes</figcaption></figure><p>Let&#39;s compare this to random play, with a score of 21.48 on average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*ryf8SngqXlFUzeSridGSIA.png" /><figcaption>Agent playing with random action strategy</figcaption></figure><p>Let’s compare this to human play. I average a score of 30.8 over 45 play-throughs, but unlike random play, the human play will “learn” over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*WfdWB2tFTkt-LQ83aCTIxw.png" /><figcaption>Human playing</figcaption></figure><p>If we look at the rate of learning for human play versus deep q-learning, we can observe that the rate of learning is faster for the machine! Obviously, the benchmark for human play is only one player which is me, so it isn’t an accurate measure of human performance. Let&#39;s see if we can improve our Reinforcement learning algorithm. A few things we could tune would be batch size to allow for longer “memory”, the reward system, the hyperparameters for our neural network, and probably more, but here we are going to change the reward system. Instead of a simple +1 for each time step, we will scale the reward to match the pole angle’s range. CartPole-v1 terminates after the pole angle goes beyond [-0.418, 0.418] radians, so we will let reward = 1-|a/0.418| with a being the pole’s angle in radians to give more weight to the pole angle being more upright. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*HSBIBtEl5nWOY6dfVEnrag.png" /><figcaption>Agent playing with new reward system</figcaption></figure><p>Looks like much better performance. Notice how after 10 episodes, the score never drops below 100, compared to the original strategy, where the score still occasionally plummets after 120 episodes. I hypothesize that this may be because the pole is incentivized to stay at 0 radians, so there is less room for the pole is fall, whereas the old reward system still gives the same reward if the pole is about to fall but within bounds. Testing this policy over 50 plays, we averaged a score of 489.88. This is a whole 50 points over our average with the old system.</p><p>Overall, this was a fun first look at reinforcement learning. In future posts, I might try to look at some of the more complex environments such as Atari games in OpenAI’s gym, or try to write an environment myself. When I was browsing the gym’s environments, there is a Box2D section where it&#39;s a bunch of scenarios simulated with the Box2D physics library. This was a surprise as I’ve worked with Box2D when I was creating my RPGConcept (see my posts from 2018)! Maybe I’ll make my environment in Java. Ultimately, I want to be able to do something in Minecraft using <a href="https://github.com/GAIGResearch/malmo">Malmo</a>, an AI experimentation platform built on top of Minecraft by Microsoft.</p><p>Code: <a href="https://github.com/chengxi600/RLStuff/blob/master/Q%20Learning/QLearning_DQN.ipynb">https://github.com/chengxi600/RLStuff/blob/master/Q%20Learning/QLearning_DQN.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67688f36413d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>