<?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 Pranav Mahajan on Medium]]></title>
        <description><![CDATA[Stories by Pranav Mahajan on Medium]]></description>
        <link>https://medium.com/@mahajan.pranav25?source=rss-f033c765d486------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xUACZKT3j9iLHi_O6gL0Yg.jpeg</url>
            <title>Stories by Pranav Mahajan on Medium</title>
            <link>https://medium.com/@mahajan.pranav25?source=rss-f033c765d486------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:08:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahajan.pranav25/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[Playing Blackjack using Model-free Reinforcement Learning in Google Colab!]]></title>
            <link>https://medium.com/data-science/playing-blackjack-using-model-free-reinforcement-learning-in-google-colab-aa2041a2c13d?source=rss-f033c765d486------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa2041a2c13d</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Pranav Mahajan]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 14:31:04 GMT</pubDate>
            <atom:updated>2021-06-14T14:54:35.264Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comparative study of algorithms like Monte-Carlo Control and Temporal-Difference Control used to solve games like Blackjack.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1ivoeEs0TsU-sfmNN2pPg.jpeg" /><figcaption>Pixabay</figcaption></figure><p>I felt compelled to write this article because I noticed not many articles explained Monte Carlo methods in detail whereas just jumped straight to Deep Q-learning applications.</p><p>In this article you’ll get to learn about</p><ol><li>The motivation behind model-free algorithms in RL (Reinforcement Learning)</li><li>Inner workings of those algorithms while applying them to solve Blackjack as an example in a Colab notebook in browser itself (no need to install anything)!</li></ol><p>Before we start I’d like to let you know that this article assumes a basic knowledge of very basic concepts of Reinforcement Learning, if you don’t it’s alright here’s a quick recap :</p><ul><li>In a usual RL setup, agent takes an action in an environment and gets in return observations and rewards from the environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*c3pEt4pFk0Mx684DDVsW-w.png" /><figcaption>Illustration (<a href="https://i.stack.imgur.com/eoeSq.png">https://i.stack.imgur.com/eoeSq.png</a>)</figcaption></figure><blockquote>Reinforcement is the strengthening of a pattern of behavior as a result of an animal receiving a stimulus in an appropriate temporal relationship with another stimulus or a response. — Pavlov’s Monograph (1927)</blockquote><ul><li>These tasks that agent performs to get better at can be either episodic or continuing, here Blackjack is an episodic game, i.e. it ends with you either winning or losing.</li><li>Agents look forward to maximizing their cumulative ‘expected’ rewards or also known as ‘expected return’. Here we give lesser importance to rewards we might get way into the future as compared to some reward we might get in the immediate step. <em>i.e. Gt = Rt+1+</em> γ<em>Rt+2+…</em></li><li>We assume our environment to have Markov Property i.e. Future state or rewards are independent of the past state given the present state i.e. P(St+1|St) = P(St+1|S1,S2,S3…St).</li></ul><p>Policy for an agent can be thought of as a strategy the agent uses, it usually maps from perceived states of environment to actions to be taken when in those states.</p><ul><li>We define state-value pairs V(s) corresponding to a policy π : as the expected return an agent will get if it were to start in that state and follow the policy π. Remember V(s) always corresponds to some policy π.</li><li>We also define action-value function Q(s,a) as the value of taking action ‘a’ in state ‘s’ under policy π.</li><li><em>V(s) = E [Gt | St = s] and Q(s,a) = E [Gt | St = s, At=a] which can also written in the way shown in the picture below. That form will more useful in computing V(s) and Q(s,a)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*UM16k3FYmc_kEE-ieNxjYA.jpeg" /><figcaption>Pss’ is a property of the environment, also referred to as P(s’, r|s, a) in the book by Sutton and Barto.</figcaption></figure><p>Various Model-based methods like Dynamic Programming use the Bellman Equation ( <em>a recursive relation between V(St) and V(St+1) </em>) to iteratively find optimal Value functions and Q functions.</p><p>And that’s the end of recap!</p><h4>What do we mean by Model-free methods? and why use them?</h4><p>To use model-based methods we need to have complete knowledge of the environment i.e. we need to know <em>Pss’ (please refer to above picture)</em>: the transition probability we’ll end up in state St+1=s’ if the agent is in state St=1 and takes action At=a. For example, if a bot chooses to move forward, it might move sideways in case of slippery floor underneath it. In games like Blackjack our action space is limited like we can either choose to “hit” or “stick” but we can end up in any of the many possible states of which you know none of the probabilities! In Blackjack state is determined by your sum, the dealers sum and whether you have a usable ace or not as follows:</p><pre>env = gym.make(&#39;Blackjack-v0&#39;)<br>print(env.observation_space)<br>print(env.action_space)</pre><p>States: <em>(32*10*2 array)</em></p><ul><li>Players current sum: [0,31] i.e. 32 states</li><li>Dealer’s face up card: [1,10] i.e. 10 states</li><li>Whether the player has a usable ace or not: [0] or [1] i.e. 2 states</li></ul><p>Actions:</p><ul><li>Either stick or hit: [0] or [1] i.e 0 for stick , 1 for hit</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>What to do when we don’t have model of the environment?</strong> You take samples by interacting with the again and again and estimate such information from them. Model-free are basically trial and error approaches which require no explicit knowledge of environment or transition probabilities between any two states.</p><p>Thus we see that model-free systems cannot even think bout how their environments will change in response to a certain action. This way they have reasonable advantage over more complex methods where the real bottleneck is the difficulty of constructing a sufficiently accurate environment model. (For example, we can’t possibly start listing out probabilities of next card the dealer will pull out in each state of Blackjack.)</p><p>(Side note) Perhaps the first to succinctly express the essence of trial-and-error learning as a principle of learning was Edward Thorndike in his “Law of Effect” in 1911 but the idea of trial-and-error learning goes as far as the 1850s.</p><p>With understood the motivation behind model-free methods, let’s see a few algorithms!</p><p>&gt;&gt; <a href="https://colab.research.google.com/drive/1zVdv5KRmWyoYZGt83QTGxPkY1Gm7WjDM">Now onward we’ll dive into code while explaining the algorithms, it’ll be helpful if you open the Colab notebook in another tab</a>!</p><p><a href="https://colab.research.google.com/drive/1zVdv5KRmWyoYZGt83QTGxPkY1Gm7WjDM">Google Colaboratory</a></p><h4>Monte-Carlo Prediction Algorithm:</h4><p>In order to construct better policies, we need to first be able to evaluate any policy. If an agent follows a policy for many episodes, using Monte-Carlo Prediction, we can construct the Q-table (i.e. “estimate” the action-value function ) from the results from these episodes.</p><p>So we can start with a stochastic policy like “stick” with 80% probability if sum is greater than 18 as we don’t want to exceed 21. Else if sum is less than 18, we’ll “hit” with 80% probability. Following code generates episodes using the following policy and then later we’ll evaluate this policy:</p><p>(Note here an ‘episode’ i.e. the quantity that is returned is a list of (state, action, reward) tuples corresponding to every action taken in the episode )</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a63a32f3b435ca148abd19301e43149a/href">https://medium.com/media/a63a32f3b435ca148abd19301e43149a/href</a></iframe><p>Now, we want to get the Q-function given a policy and it needs to learn the value functions directly from episodes of experience. Note that in Monte Carlo approaches we are getting the reward at the end of an episode where..</p><p>Episode = S1 A1 R1, S2 A2 R2, S3 A3 R3…… ST(Sequence of steps till the termination state)</p><p>We’ll learn value functions from sample returns with the MDP, recollect from the recap that:</p><p><em>Q(s,a) = E [Gt | St = s, At=a] and Gt = Rt+1+</em> γ<em>Rt+2+… for a policy π</em>.</p><p>What is the sample return? Say we played for 10 episodes using a policy and we got rewards 2,6,5,7 when we visited the same state ‘S’ for 4 out of 10 times then the sample return would be (2+6+5+7)/4 = 20/4 = 5 ~V(s). Thus sample return is the average of returns(rewards) from episodes. In what order did we end up visiting the state doesn’t really matter here, estimate for each value is calculated independently!</p><p>This way we can build either a V-table or a Q-table, in order to create a Q-table we’ll need to keep track of reward we got for each we visited a (state,action) pair and also keep a track of how many times we visited the state say an N-table.</p><p>Depending on which returns are chosen while estimating our Q-values</p><ul><li>First visit MC: <strong>In an episode</strong>, we average returns only for <strong>first </strong>time (s,a) is visited. It’s statistically an unbiased approach.</li><li>Every visit MC: <strong>In an episode</strong>, we average returns only for <strong>every </strong>time (s,a) is visited. It’s statistically an biased approach.</li></ul><p>For example: In an episode, S1 A1 R1, S2 A2 R2, S3 A3 R3, S1 A1 R4 →End. Then first visit MC will consider rewards till R3 in calculating the return while every visit MC will consider all rewards till the end of episode.</p><p>Here, in Blackjack it doesn’t affect much whether we use first visit or every visit MC. Here’s the algorithm for first-visit MC prediction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*-gWLzZ9hduVq-dfS9NsDLQ.png" /><figcaption>MC pred, pseudocode</figcaption></figure><p>But we’ll implement every-visit MC prediction as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d986aa2c54146f80e9d0025da39cdb44/href">https://medium.com/media/d986aa2c54146f80e9d0025da39cdb44/href</a></iframe><p>We first initialize a Q-table and N-table to keep a tack of our visits to every [state][action] pair.</p><p>Then in the generate episode function, we are using the 80–20 stochastic policy as we discussed above.</p><pre>sum(rewards[i:]*discounts[:-(1+i)]) #is used to calculate Gt</pre><p>This will estimate the Q-table for any policy used to generate the episodes! Once we have Q-values, getting V-values is fairly easy as V(s) = Q (s, π(s)). Let’s plot the state values V(s)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLX2mbjQZc8BPtXo3PX6lA.png" /><figcaption>Plotted V(s) for each of 32*10*2 states, each V(s) has value between [-1,1] as the reward we get is +1,0,-1 for win, draw and loss</figcaption></figure><p>So now we know how to estimate the action-value function for a policy, how do we improve on it? Using the …</p><h4>Monte-Carlo Control Algorithm</h4><p>So here’s the plan in a nutshell. We start with a stochastic policy and compute the Q-table using MC prediction. So we now have the knowledge of which actions in which states are better than other i.e. they have greater Q-values. So we can improve upon our existing policy by just greedily choosing the best action at each state as per our knowledge i.e. Q-table and then recompute the Q-table and chose next policy greedily and so on! Sounds good?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*OpkcogcrE9s_3Bybdy8CqA.png" /><figcaption>From slides based on RL book by Sutton and Barto</figcaption></figure><ul><li>But we have a problem, what if for a state ‘St’ there were 2 actions ‘stick’ and ‘hit’ what if agent chooses ‘hit’ early on in the many games the agent will play and wins whereas ‘stick’ should’ve been the better action, it never got to explore the action as the algorithm went on greedily choosing it multiple times. Thus to solve this exploration-exploitation dilemma, we’ll use ε-greedy policy i.e. we’ll explore, take a random action with probability ‘ε’ (epsilon) rather than greedily exploiting the learnt Q-values. Naturally we’d like to keep the ε values ~1 at the start and reduce it till close to 0 by the end of the learning (total no. of episodes).</li><li>Incremental mean: Remember how we took average of all the returns to estimate Q-values in MC Prediction? But now unlike MC Pred, in MC Control our policy is undergoing change every cycle! We can write the same equation in terms of previous Q-values in this way: Trust me it’s not out of the blue you can arrive at the same equation yourself if you see that N(St,At) * Q(St,At) is the Gt until this step and thus Gt-Q(St,At) is incremental change.</li></ul><blockquote>N(St,At) ← N(St,At) + 1</blockquote><blockquote>Q(St,At) ← Q(St,At) + (1/N(St,At))*(Gt-Q(St,At))</blockquote><ul><li>Constant alpha: Now as the N(St,At) increases i.e. we visit the same state-action pair many times in our interaction, the incremental change term decreases, which means our latter experiences will affect lesser and lesser that starting ones. To solve this we can replace (1/N) term by a constant α, which is hyper parameter, for us to choose.</li></ul><blockquote>Q(St,At) ← Q(St,At) +α *(Gt-Q(St,At))</blockquote><p>Having learnt these crucial practical changes to idea of just sampling return, here’s the algorithm for first-visit MC control!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*tK_Lj-jasj9UmT2gg0g5BQ.png" /><figcaption>MC control, pseudocode</figcaption></figure><p>We’ll implement every-visit MC control, because it’s just slightly easier to code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31fa71aa26db7127b255dbccc7ac8d0a/href">https://medium.com/media/31fa71aa26db7127b255dbccc7ac8d0a/href</a></iframe><p>We’re just using 3 functions to make the code look cleaner. To generate episode just like we did for MC prediction, we need a policy. But note that we are not feeding in a stochastic policy, but instead our policy is epsilon-greedy wrt our previous policy. get_probs function gives us the action probabilities for the same i.e. π(a|s)</p><p>And the update_Q function just updates Q-values using incremental mean and constant alpha. Finally we call all these functions in the MC control and ta-da!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd1fc5ab86f8d4239303423cf982b8c5/href">https://medium.com/media/dd1fc5ab86f8d4239303423cf982b8c5/href</a></iframe><p>Feel free to explore the notebook comments and explanations for further clarification!</p><p>Thus finally we have an algorithm that learns to play Blackjack, well a slightly simplified version of Blackjack at least. Let’s compare the policy learnt compared to the optimal policy mentioned in RL book by Sutton and Barto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uqROrqcsfT7PYTjw.png" /><figcaption>RL, Sutton Barto Fig 5.2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*i5A9jKoN7IkQLSB5Fg4Y2Q.png" /><figcaption>Our learnt policy (rotated by 90 deg)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*SpkggSYhfMb5wB-FxTTNOg.png" /><figcaption>Play using our learnt policy!</figcaption></figure><p>Wolla! There you go, we have an AI that wins most of the times when it plays Blackjack! But there’s more…</p><h4>Temporal Difference methods</h4><p>Now Blackjack isn’t the best environment to learn advantages of TD methods as Blackjack is an episodic game and Monte Carlo methods assume episodic environments. In MC control, at the end of each episode, we update the Q-table and update our policy. Thus we have no way of finding out which was the wrong move that led to the loss but it won’t matter in a short game like Blackjack. If it were a longer game like chess, it would make more sense to use <strong>TD control methods because they boot strap , meaning it will not wait until the end of the episode to update the expected future reward estimation(V) , it will only wait until the next time step to update the value estimates.</strong></p><p>(Side note) TD methods are distinctive in being driven by the difference between temporally successive estimates of the <strong>same quantity</strong>. More over the origins of temporal-difference learning are in part in animal psychology, in particular, in the notion of secondary reinforcers. Secondary reinforcer is a stimulus that has been paired with a primary reinforcer (simplistic reward from environment itself) and as a result the secondary reinforcer has come to take similar properties.</p><p>For example, in MC control:</p><p><em>V(s) = E [Gt | St = s] and Gt = Rt+1+</em> γ<em>Rt+2+…</em></p><p>But the in TD control:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*DDfY_NKBgBIhfAIpo4THuQ.jpeg" /></figure><p>Just like in Dynamic Programming, TD uses Bellman Equations to update at each step.</p><p>Following picture can help explain the difference between DP, MC and TD approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*oH57by466D2gPmNMXMK_UA.jpeg" /><figcaption>David Silver’s Slides</figcaption></figure><p>Thus we can think of the incremental mean in a different way as if Gt was the Target or our expectation of the return the agent would have got, but instead got the return Q(St,At) so it would make sense to push Q-values towards Gt by α *(Gt-Q(St,At)).</p><p>Similarly in case of TD methods, instantaneous TD target is Rt+1 +γQ(St+1,At+1) and thus the TD error will be (Rt+1 +γQ(St+1,At+1) -Q(St,At))</p><p>Depending on different TD targets and slightly different implementations the 3 TD control methods are:</p><ul><li>SARSA or SARSA(0)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*giibnVs1xUMI1er_5ag13A.png" /><figcaption>SARSA update equation</figcaption></figure><p>Which when implemented in python looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ab8712c25a6733daf7109ddf5d74fa/href">https://medium.com/media/85ab8712c25a6733daf7109ddf5d74fa/href</a></iframe><ul><li>SARSAMAX or Q-learning</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Zsvy6X0HgtciKFX7EPkAuA.png" /><figcaption>SARSAMAX update equation</figcaption></figure><p>Which when implemented in python looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b1e8dbb0cff400e776fc764a020bc80/href">https://medium.com/media/6b1e8dbb0cff400e776fc764a020bc80/href</a></iframe><ul><li>Expected SARSA</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*EW6NpktNQhOOZ079wj7IAA.png" /><figcaption>Expected SARSA update</figcaption></figure><p>Which when implemented in python looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b3d661f5aa45c3a0665b64603c8cd7f/href">https://medium.com/media/5b3d661f5aa45c3a0665b64603c8cd7f/href</a></iframe><p>NOTE that Q-table in TD control methods is updated every time-step every episode as compared to MC control where it was updated at the end of every episode.</p><p>I know I haven’t explained TD methods in as much depth as the MC methods instead analyzed in a comparative fashion, but for those who are interested all of the 3 methods are implemented in the notebook. You are welcome to explore the whole notebook for and play with functions for a better understanding!</p><p>That’s all folks! Hope you enjoyed!</p><p>References:</p><ol><li>Reinforcement Learning: An Introduction (Book by Andrew Barto and Richard S. Sutton)</li><li>David Silver’s slides (UCL course on RL)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa2041a2c13d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/playing-blackjack-using-model-free-reinforcement-learning-in-google-colab-aa2041a2c13d">Playing Blackjack using Model-free Reinforcement Learning in Google Colab!</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>