<?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 Sakarya on Medium]]></title>
        <description><![CDATA[Stories by Sakarya on Medium]]></description>
        <link>https://medium.com/@mersakarya?source=rss-ebcfa050d49f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Sakarya on Medium</title>
            <link>https://medium.com/@mersakarya?source=rss-ebcfa050d49f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:42:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mersakarya/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[Watch this AI Algorithm Beating Players in an Online Game (Video)]]></title>
            <link>https://medium.com/data-science/watch-this-ai-algorithm-beating-players-in-an-online-game-video-27fde513333e?source=rss-ebcfa050d49f------2</link>
            <guid isPermaLink="false">https://medium.com/p/27fde513333e</guid>
            <category><![CDATA[ai-plays-puzzle]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Sakarya]]></dc:creator>
            <pubDate>Thu, 14 May 2020 01:47:35 GMT</pubDate>
            <atom:updated>2020-05-15T16:32:03.992Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI Plays Puzzle</h4><h3>Watch this AI Algorithm Beating Players in an Online Game</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-ACix4Ix-eqbWsS1gw2UA.png" /><figcaption>This is what the agent “sees” while playing against other players online.</figcaption></figure><p>This is the final post of a three-piece article in which I walked through the training of this AI algorithm. Feel free to check out: <a href="https://medium.com/p/2eb789c2ff5e">Part 1</a>, <a href="https://medium.com/p/e7097478d402">Part 2</a>, <a href="https://medium.com/p/e4a2992112a1">Part 3</a>.</p><p>Over the course of training, agent learned how to play by playing against itself, challenging its own knowledge. Here are the results, agent playing against other players online:</p><ul><li><a href="https://youtu.be/FhhPJIZnJ1M">AI versus human 172–117 WON</a></li><li><a href="https://youtu.be/88im5nrpRcE">AI versus human 185–94 WON</a></li><li><a href="https://youtu.be/NxOomGWppvY">AI versus human 191–69 WON</a></li><li><a href="https://youtu.be/mwMR28FmEqA">AI versus human 138–179 LOST</a></li><li><a href="https://youtu.be/yH559pas0A0">AI versus human 189–164 WON</a></li><li><a href="https://youtu.be/nh2FqoDW_Bk">AI versus human 228–69 WON</a></li><li><a href="https://youtu.be/RacWwYijzzM">AI versus human 213–167 WON</a></li><li><a href="https://youtu.be/-nrYGkWoLMA">AI versus human 73–169 LOST</a></li><li><a href="https://youtu.be/cfqhyZNBw5c">AI versus human 271–58 WON</a></li><li><a href="https://youtu.be/P6bgT0WcZIk">AI versus human 150–195 LOST</a></li><li><a href="https://youtu.be/dmzyJBAkrqw">AI versus human 89–223 LOST</a></li><li><a href="https://youtu.be/BEsWW6XSh38">AI versus human 192–109 WON</a></li><li><a href="https://youtu.be/Qk8-rEPKwBQ">AI versus human 268–21 WON</a></li><li><a href="https://youtu.be/8h9f5-qn2eQ">AI versus human 110–207 LOST</a></li><li><a href="https://youtu.be/HoBBw0EQDgo">AI versus human 182–166 WON</a></li><li><a href="https://youtu.be/Cl7Uoi5yo1I">AI versus human 107–58 WON</a></li><li><a href="https://youtu.be/g2wej9Q_1kM">AI versus human 102–160 LOST</a></li></ul><h3>Why AI doesn’t win all the time?</h3><p>I would like to make a final point by explaining why the agent is losing to some players.</p><p>Referred as Agent, is an AI algorithm trained by deep reinforcement learning. Agent is able to beat some players, but not others. Fails to see whenever the enemy “pushes agent to the edge”, forcing it to inevitably make a bad move. Also, sometimes agent performs an absurd action, letting opponent get a lot of points.</p><p>Over the course of training, agent learned how to play by playing against itself, challenging its own knowledge. Notice that this would yield a different training data than the case in which agent played against humans for training. It’s always a possibility that there is a strategy that counters agent’s strategy. Theoretically, if agent is pushed to make decisions on states that it didn’t encounter during training, it’s likely to make poor decisions.</p><blockquote>“Our framing of the reinforcement learning problem forces us to settle for approximations. However, it also presents us with some unique opportunities for achieving useful approximations. For example, in approximating optimal behavior, there may be many states that the agent faces with such a low probability that selecting suboptimal actions for them has little impact on the amount of reward the agent receives. Tesauro’s backgammon player, for example, plays with exceptional skill even though it might make very bad decisions on board configurations that never occur in games against experts. In fact, it is possible that TD-Gammon makes bad decisions for a large fraction of the game’s state set. The online nature of reinforcement learning makes it possible to approximate optimal policies in ways that put more effort into learning to make good decisions for frequently encountered states, at the expense of less effort for infrequently encountered states. This is one key property that distinguishes reinforcement learning from other approaches to approximately solving MDPs.”</blockquote><blockquote>— Sutton &amp; Barto, Introduction to Reinforcement Learning, 2018</blockquote><p>In short, it’s possible to beat the AI algorithm. It’s also possible to train an algorithm that is much closer to unbeatable than the one we have.</p><h3>Ethics</h3><p>From the other players’ point of view, playing against an AI algorithm might be a daunting experience. As my defense, it’s possible to beat the AI, as couple other players and I did. Therefore, it’s not as daunting as playing against me, which they would be playing against if AI wasn’t there. Also, the game is played over a bet of in-game currency. Because of that, bets are kept small and every time agent won over another player, money won is refunded immediately.</p><h3>Want to find out more?</h3><p>This is the final post of a three-piece article in which I walked through the training of this AI algorithm. Feel free to check out: <a href="https://medium.com/p/2eb789c2ff5e">Part 1</a>, <a href="https://medium.com/p/e7097478d402">Part 2</a>, <a href="https://medium.com/p/e4a2992112a1">Part 3</a>.</p><h3>About Me</h3><p>I’m a Data Scientist, living in San Francisco. Passionate about working with user-generated data. Find me on Linkedin: <a href="http://linkedin.com/in/sakarya">Ömer Sakarya</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27fde513333e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/watch-this-ai-algorithm-beating-players-in-an-online-game-video-27fde513333e">Watch this AI Algorithm Beating Players in an Online Game (Video)</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>
        <item>
            <title><![CDATA[Playing Treasure Drop with Deep Reinforcement Learning — Part 3/3]]></title>
            <link>https://medium.com/data-science/playing-treasure-drop-with-deep-reinforcement-learning-part-3-3-e4a2992112a1?source=rss-ebcfa050d49f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a2992112a1</guid>
            <category><![CDATA[ai-plays-puzzle]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sakarya]]></dc:creator>
            <pubDate>Wed, 13 May 2020 05:56:59 GMT</pubDate>
            <atom:updated>2020-05-15T02:10:44.536Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>AI Plays Puzzle</h4><h3>Playing Treasure Drop with Deep Reinforcement Learning — Part 3/3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hjfHORenbDTLJIaOkhYXQ.png" /></figure><p><strong>In this article series, I went through explaining the Reinforcement Learning (RL) project I have worked on. At the very end, you will know how this works:</strong></p><p><a href="https://youtu.be/FhhPJIZnJ1M">WATCH This AI beat human player in a real time puzzle game</a></p><p>I discussed unique and notable aspects of the problem, what techniques I used and why. Hopefully, readers interested in Deep Reinforcement Learning find all of this insightful.</p><p>In <a href="https://medium.com/p/2eb789c2ff5e/">part 1</a> and <a href="https://medium.com/p/e7097478d402/">part 2</a>, the game of <em>Treasure Drop</em> is explained and Deep Q Network is implemented with some methods specialized for Deep Reinforcement Learning. This part is about monitoring models’ learning progress by plotting metrics, comparing agents by fighting them off, and framework for agent to play online.</p><h3>Summary</h3><p>Tracking learning progress and plotting is key to deep learning research. In order to track the learning progress, heuristic metrics are explained and plotted along with the MSE loss over iterations of episodes. Trained models are challenged against each other to understand which learning process yields better agents. Agents trained for different rounds of the game (1, 2, 3 and 4) are put together to perform online. Finally, some of the classes in GitHub repository is explained on high level. <strong>Taking the input from the screen, clicking on appopriate spots, agent was able to beat majority of the players.</strong></p><p><strong>GitHub repository for Part 3/3:</strong> <a href="https://github.com/arapfaik/td-deepreinforcementlearning-part3">td-deepreinforcementlearning-part3</a></p><h3>Plotting</h3><p>Although I am mentioning it last, <strong>plotting is far from being the least important.</strong> I have been plotting throughout project and it was profoundly helpful. It would be impossible to succeed at least to this level without plotting.</p><p>Plotting loss with respect to episodes is inarguably key step on any machine learning project. In reinforcement learning, it’s also essential to track agent’s learning progress. Sometimes there are obvious metrics you can track such as cumulative reward or accuracy, sometimes your have to make them up. Regardless, learning process might seem like a black box at times and metrics will be your beacon of light in that darkness.</p><p><strong>Metrics should convey information about model’s progress that loss plot lacks to provide.</strong> As you work on the problem, you probably have couple things in mind that would make sense plotting. I encourage you to plot them next to loss and pay attention to their trend over training episodes.</p><p>After the train loop, the model is automatically saved along with its plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmNjcSw5PTAlxbjignamOQ.png" /></figure><p>Here is one of the them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEi7C1ZyrpuIa0xf0bUXgw.png" /></figure><p>Those on the left column are just losses, zoomed in along x and y axes. Bottom left spot is reserved for learning rate schedule and is left blank if the learning rate is constant. To the right, there are custom defined heuristic scores. You can see what score are they on the y label of each plot. They are a heuristic measurement of model’s learning progress, which brings our discussion to them.</p><h3>Heuristic Scores</h3><p>Explanation on why those scores are related to model’s progress are explained in detail in <a href="https://medium.com/p/2eb789c2ff5e/">Part 1</a>. To briefly give the idea, a perfect model with %100 accurate q-value predictions would have these scores as 0. Lower the score, it’s likely that the model is better.</p><h4>Score1</h4><p>MSE loss between q-values for randomly-picked (from experience replay buffer), mirror-imaged game states. In the ideal model outputs are very accurate q-values. Therefore, corresponding actions of mirror images would be very close. Since the score is MSE, the ideal model would have it very close to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUYO0hAAM2J-zzJrUy-6_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWgElNWHHHLXaBUwi_PcGA.png" /></figure><h4>Score2</h4><p>MSE loss between neighboring equivalent actions. Actions are considered equivalent if there is a coin in the immediate lever below both locations. Either left or right action will lead to the exact same next state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*csQnFeSS_H6zea2xEjqD_w.gif" /><figcaption>Both left and right actions lead to the same effect for the game.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l90RjT8VFH8o6e3jtx01KQ.png" /><figcaption>Both actions 0 and 1 lead to the exact same next state.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRyyo1xrcl23Bj0jZMJftw.png" /><figcaption>Formule of score2.</figcaption></figure><h4>Score3</h4><p>Q-values will show differences across mirror-images states since our model will never be perfect. However, only the highest q-value determines the action, no matter what the individual values are. <strong>Because of that, even though the score1 and loss is pretty high, agent can end up playing very good.</strong></p><p>Score3 is mean of 0–1 losses. It’s value is bounded within 0 and 1. It is measured similar to score1. However, only the maximum q-value is considered. If both actions in mirror imaged states lead to same consequences, the contribution to mean is 0. If not, then contribution is 1. For instance, if score3 is 0.2, it means that, in 2 out of 10 mirror imaged states, agent is consistent in only 8. Please see the examples of each case below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvlFu-PYHzKUayl4Ii1Oug.png" /><figcaption>Although the q-values are way different in those two states, highest ones belong to the same action.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Khd4I6QG_tZegYf2r7oyUA.png" /><figcaption>Here, two mirror images states with inconsistent optimal actions.</figcaption></figure><h3>Heuristic Scores in the Plot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Uw31_FFALIr_Bo-Lr2SAw.png" /></figure><p>Here is another plot from a training run with a cyclical learning rate. Notice how the score3 keeps going down even though the loss is not improving (visually) after some point. It turned out to be insightful for me analyzing this set of plots after running grid searches over hyper parameters.</p><p>Scores do help but, in a folder full of models, it’s hard to know which model is the best. That brings us to the discussion of the Duel and DuelFolder class.</p><h3>Duel and DuelFolder Class</h3><p>Duel class takes two trained agents, fights them off couple games and plots the result like the following plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEQQ65vkg366Pjt5-UBODg.png" /><figcaption>Results are from 1000 episodes. Looks like 51–11 wins most of the time.</figcaption></figure><p>DuelFolder does the same thing in a bulk fashion, taking a whole folder of models as input. Pairwise fighting-off agents, outputs win counts each of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lIAipLV8S6grt1hutN3VA.png" /><figcaption>It appears that model ending with 51–30 is the best.</figcaption></figure><p>This is just another form of gauging how the learning process went. There is no perfect model we can compare trained models against. However, we can compare one another by fighting them off. Dueling trained models allows us to compare models trained under different conditions.</p><p>For the most part, models with good looking loss and heuristic metric plots performed the best against others. Final models are selected based on this comparison.</p><p>In an environment where there is no automated way to gauge how well an agent will perform against humans, it is interesting to measure the relative performance of models within each other.</p><h3>AgentFull Class</h3><p>At the very beginning, for simplicity of training, we have ignored the fact that the original game has four rounds. Each round has different set of scores at the bottom of the game. This changes the rewards in transactions. Therefore, an agent trained for a round is not valid for another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*DOfSCyeywwYK_r4PL14C7w.png" /><figcaption>Bucket scores for rounds 1, 2, 3 and 4 respectively.</figcaption></figure><p>This makes it necessary to train a separate agents for each round. AgentFull then takes these four individually trained models. Whenever asked for the optimal action given state, it just forwards the inference process to the appropriate agent.</p><h3>GameController Class</h3><p>This class is the framework in which the AgentFull class operates online. It takes a screenshot, detects the objects using OpenCV Library. When it’s agent’s turn, reads the state from the game and clicks on the appropriate spot with mouse.</p><h3>Model in Action! ⚔️</h3><p><a href="https://github.com/arapfaik/td-deepreinforcementlearning-part3">Link to GitHub Repository</a></p><p>Here is how to run the “Running GameController” notebook. You open both the notebook and the game, visible on the same screen. Once you run the cell with .start_playing() method, the game will be detected and program will start grabbing a screenshot every .5 seconds, playing against the other player. Please note that doing this might get you banned from the game.</p><h3>That’s all!</h3><p><a href="https://medium.com/p/27fde513333e">Watch how agent performs against real players online.</a></p><p>Hope you enjoyed! 😊</p><h3>About Me</h3><p>I’m a Data Scientist, living in San Francisco. Passionate about finding answers from data. Find me on Linkedin: <a href="http://linkedin.com/in/sakarya">Ömer Sakarya</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a2992112a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/playing-treasure-drop-with-deep-reinforcement-learning-part-3-3-e4a2992112a1">Playing Treasure Drop with Deep Reinforcement Learning — Part 3/3</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>
        <item>
            <title><![CDATA[Playing Treasure Drop with Deep Reinforcement Learning — Part 2/3]]></title>
            <link>https://medium.com/data-science/playing-treasure-drop-with-deep-reinforcement-learning-part-2-3-e7097478d402?source=rss-ebcfa050d49f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7097478d402</guid>
            <category><![CDATA[ai-plays-puzzle]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sakarya]]></dc:creator>
            <pubDate>Wed, 13 May 2020 05:51:40 GMT</pubDate>
            <atom:updated>2020-05-15T02:10:48.115Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI Plays Puzzle</h4><h3>Playing Treasure Drop with Deep Reinforcement Learning — Part 2/3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CINe-_itkSwA7A3fA-xBYA.png" /><figcaption>This is what the agent “sees” while playing against other players online.</figcaption></figure><p><strong>In this article series, I went through explaining the Reinforcement Learning (RL) project I have worked on. At the very end, you will know how this works:</strong></p><p><a href="https://youtu.be/FhhPJIZnJ1M">WATCH This AI beat human player in a real time puzzle game</a></p><p>I discussed unique and notable aspects of the problem, what techniques I used and why. Hopefully, readers interested in Deep Reinforcement Learning find all of this insightful.</p><p>In <a href="https://medium.com/p/2eb789c2ff5e/edit">Part 1</a>, the game of <em>Treasure Drop</em> is explained and tabular q-learning method is used for a smaller version of the game. After getting the validation and early success needed with tabular approach, Deep Q Networks are implemented here.</p><h3>Summary</h3><p>After getting the validation and early success needed with tabular approach, Deep Q Networks are implemented for the same problem as Part 1 using Keras library. However, learning process got unstable due to the nature of the project. Several methods are implemented to mitigate the problem. Those are namely, Prioritized Experience Replay, Target Q-Network, Cyclical Learning rate with Learning Rate Finder.</p><p><strong>GitHub repository for Part 2/3:</strong> <a href="https://github.com/arapfaik/td-deepreinforcementlearning-part2">td-deepreinforcementlearning-part2</a></p><h3>Limitations of Tabular q-learning</h3><p>In <a href="https://medium.com/p/2eb789c2ff5e/edit">Part 1</a>, q-tables are implemented for board sizes of 3x2, maybe 4x2 the biggest. On 4x2, it took a very long time for q-table to have converged values. This is because in 4x2, state space has 4⁹ = 2¹⁸ states. That equals to roughly 260k states. That is too much for a tabular implementation. The original game table is 4x5 with 2⁶⁰ different possible states. That renders tabular q-learning infeasible for our problem.</p><p>In many cases of practical interest, including this one, there are far more states than could possibly be entries in a table. In these cases the functions must be approximated, using some sort of more compact parameterized function representation.¹</p><p>The solution to this is to approximate the q-value function. Guess what is a good function approximator? Yes, you got that one right! 👏👏 <strong>Deep Neural Networks</strong>! This article is about approximating the q-value function using deep neural networks. They are commonly in the reinforcement learning context and are called Deep Q-learning Networks (DQN).</p><h3>Transition from Q-Table to DQN</h3><p>It is pretty straightforward. The only difference in the code will be on the line where we update the q-table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62d3308a504be87fdbedbc0c1878051/href">https://medium.com/media/e62d3308a504be87fdbedbc0c1878051/href</a></iframe><p>Instead, we will feed the td_target along with the state to the neural network. Theoretically speaking, next time the network sees the state, it will output the correct q-value. This is the case for smaller board sizes however, will not be that easy for bigger board sizes and the original size of the game. Here is the update that will replace the tabular q-learning update above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5239d55a8d80ab125b3854aae0155d3/href">https://medium.com/media/b5239d55a8d80ab125b3854aae0155d3/href</a></iframe><h3>Neural Network</h3><h4>Architecture</h4><p>Decided to settle with the shape 60 x 300 x 300 x 300 x 300 x 300 x 8, although input and output layers differ by the board size. For instance, for a 4x3 game, they would be 30 and 4 respectively. All layers are fully connected.</p><blockquote>The ideal network architecture for a task must be found via experimentation guided by the validation set error. ²</blockquote><blockquote>– Goodfellow, Bengio &amp; Courville. <a href="https://www.amazon.com/Deep-Learning-NONE-Ian-Goodfellow-ebook/dp/B01MRVFGX4/ref=sr_1_3?dchild=1&amp;keywords=deep+learning&amp;qid=1587862365&amp;sr=8-3"><em>Deep Learning</em></a><em> </em>(2016)</blockquote><p>During online play, the state is collected from the screen by GameController class. The round is also inferred from screen. Then, state is fed in as the input to the model with corresponding round. Outputs are q-values, each corresponding to an action on the board. The action with highest q-value is picked by the agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8DU2EYbFYPJUfh0BkolMA.png" /><figcaption>Diagram of how information flows between model and game.</figcaption></figure><h4>Optimizer and Loss</h4><p>Stochastic Gradient Descent (SGD) with momentum = 0.9 is used for all the models. Gradients are clipped with coefficient of 0.5. Not clipping gradients sometimes caused exploding results, weights of neural network ended up being NaN.</p><p>Loss function is MSE between the predicted q-value of the action and the value calculated by the Bellman’s Equation.</p><h3>Stability of Learning Process</h3><p>At this point, the DQN worked, however only for very small board sizes. It would sometimes converge, sometimes not. Deep reinforcement learning is known for being stable since this is currently a hot research area. The most popular term about instability being “the deadly triad”. If certain three qualities exist in a learning algorithm, it’s said that there is a high chance learning algorithm diverging.</p><p>When using deep non-linear function spaces with reinforcement learning, there is little guidance on whether divergence is common, and if the deadly triad is to blame.³</p><h3>The Deadly Triad</h3><p>In the DQN method, we are doing three things that deserves some attention. These are:</p><ol><li>Function Approximation: Rather than crafting the actual function mathematically, or storing the output values for each input, we are approximating the q-value function by a Deep Neural Network:</li><li>Bootstrapping: We are updating q-value estimates based in part on other estimates. We learn a guess from another guess — we <em>bootstrap.</em></li><li>Off-Policy Learning: We are not following the policy all the time when learning takes place. This is because we are taking random actions with the probability of ε (epsilon).</li></ol><p>The combination of those three can create harmful learning dynamics that can lead to divergence of the function parameters. Due to this possibility of divergence, the combination of the three has been called “the deadly triad”.³</p><p>When training for the 3x2 game, I noticed that the model sometimes converged, sometimes did not. Learning process seemed to be unstable for some reason. I blamed deadly triad, although it was unclear whether that was the problem. Nevertheless, the learning process has all three qualities of it. Rest of this article is about what is implemented in order to render the learning process stable.</p><h3>Experience Replay</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56d659cc8488e5654df209144880e4a1/href">https://medium.com/media/56d659cc8488e5654df209144880e4a1/href</a></iframe><p>In Data Science, underlying distribution of data determines what the model learns. Experience Replay is a very, very, very popular technique to be implemented whenever RL and DQN come together. Updating the model with the current transaction is cool, but it’s wasteful of the data. Model sees the data only one.</p><p>Contrast to that, Experience Replay uses <strong>a random sample of prior transactions</strong> to update Q-values. By keeping a memory of previously occurred transactions, samples randomly among them at every step. This introduces two new hyperparameters: the size of the memory (max_memory) and the # of samples to be drawn each time (batch_size).</p><p>Mnih et al. (2015) set size of their memory buffer to 10⁶ for DQN tasks on various Atari games.⁴ It made sense to ditto that as a starting point. Later in the project I have adjusted it to a lower number after realizing it hurts the performance. As for the batch_size, 10 seemed to work the best for this game.</p><h3>Prioritized Experience Replay</h3><p>Experience replay liberates online learning agents from processing transitions in the exact order they are experienced. Prioritized replay further liberates agents from considering transitions with the same frequency that they are experienced.⁵</p><p>Intuitively, some transactions matter more than others. It is possible to sample transactions in a more informed fashion. Now the question is, which transaction have more importance than others?</p><p>Agent must be more sensitive to those transactions with big scores. This has a two-fold advantage. First, agent can sense the high reward and take appropriate action. Second, agent can see whether enemy can score a high reward after a certain move, and can prevent letting the enemy take that rewards by restricting its own actions.</p><p>At this point, we just need a metric to assign probabilities accordingly.</p><p>Predicting a high scalar value has more MSE loss than predicting a low scalar value. This translates into, higher the reward around a transaction, higher the MSE loss would be.</p><p>Therefore, we can safely consider loss as a metric for prioritization. Higher the loss, more important a transaction is. Each time a transaction drawn from the experience buffer, a prediction runs on it. The loss resulting from the prediction is updated and transaction placed back into buffer with new priority metric.</p><p>Models trained with Prioritized Experience Replay seemed to beat models that were trained without it, given the same amount of training iterations.</p><h3>Target Q-Network</h3><p>This adresses the bootstrapping quality of our learning process. It’s not a silver bullet solution since the bootstrapping is still present. However, it’s been proven to help on wide variety of reinforcement learning tasks involving DQN.³</p><p>The logic is simply bootstrapping from a separate network than the one being updated. In other words, there are two networks, copy of each other. Estimates are derived from one network, values are updated on the other network (called target network). At each tn_steps, (short for target network steps) the weights are copied from the target network to the original network, the network estimates are derived from.</p><p>Target Q-networks has a stabilizing effect on the early stages of the training process. Hyperparameter of tn_steps = 1 is used. It means that the target network is copied after each game. Every game lasts around 100 moves. So tn_steps = 1 actually means target network is copied every ~100 updates.</p><h3>Learning Rate</h3><blockquote>Learning rate is the most important hyperparameter to tune. —Andrew Ng</blockquote><p>In order to find the best learning rate and tune other hyperparameters systematically, HyperparameterSearch class is defined. After searching for a constant rate, <strong>0.009</strong> is determined to work best for now.</p><h4>Learning Rate Finder &amp; Cyclical Learning Rate</h4><p>Leslie Smith et al described a phenomenon, called “super-convergence” that a neural network could be trained way faster than standard methods.⁶ In this project, agents trained with cyclical learning rates seemed to do better than others for this problem, given the same number of episodes.</p><h4>LR Finder</h4><p>First, we do something called LR range test. It determines whether this method is applicable to the problem. Training starts with a very small learning rate and increases over episodes. Ideally, at one point, model stops improving and accuracy plateaus, stops increasing. Learning Rate at that point is the maximum learning rate to be used in cyclical learning rate schedule. 1/3rd or 1/4th of that is the minimum learning rate.</p><p>However, there is no accuracy in this problem. Instead, I used mean loss occurred during training of an episode. Batch size of SGD is set around 100–300. Therefore, each loss was being generated over 30,000 transitions. That was needed to make the plot as smooth as below. Otherwise, it would be too noisy and uninterpretable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*iFCOYoOOu4tttRIbU93hTQ.png" /><figcaption>According to LR Finder method, max learning rate would be around 10^-3.5 to 10^-3.</figcaption></figure><p>From the plot above, we can conclude that max learning rate can be 10^-3 and minimum learning rate. 1/4th of that.</p><h4>Cyclical Learning Rate Schedule</h4><p>To clarify, the word “cyclical” just means the learning rate goes from min_lr to max_lr, and then goes down, looks just like the plot below. The tipping point doesn’t have to be half-way, it could be earlier down to 1/4th. The idea is based on a concept called <a href="https://en.wikipedia.org/wiki/Simulated_annealing">simulated annealing</a> and is popular in deep learning literature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0TqYfIQwZ85jfnLW7A5Dg.png" /></figure><h3>Training</h3><p>If you wish to train models yourself, be ready to move things to AWS. It takes couple hours to train an agent that plays well on the 4x5 (original) game. Just to clarify, using GPU will not speed things up as there are no convolutional layers in the model. You also don’t need a super powerful instance on AWS, I did all the training on <strong>c5.xlarge EC2 </strong>instances.</p><h3>Model Validation and Action ⚔️</h3><p><a href="https://github.com/arapfaik/td-deepreinforcementlearning-part2">Link to GitHub Repository</a></p><p>Although not the most automated method, one way to validate models was to simply look at and compare q-values the model predicts for equivalent actions. Another way is to compare predicted q-values for mirror imaged states. Explanation of why those would be good heuristics is explained in <a href="https://medium.com/p/2eb789c2ff5e">Part 1</a>. Comparing the results with the tabular model’s outputs in part 1, we see that DQN’s outputs are not as consistent as tabular q-learning’s outputs. This is due to both the fact that we are doing approximation and the table size is much bigger.</p><p>However, the agent will pick the action with highest q-value anyway. Even though there is a big discrepancy among the numbers, in both cases the agent will perform the same (equivalent) action. Since the states are mirror imaged along y axis, actions 1 and 6 correspond to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACIf5Vq49ngXzFJH7JJv2g.png" /></figure><p>Our learning algorithm, TD(0) is proven to converge deterministically to a single answer for tabular implementations of the algorithm. Tabular methods can often find exact solutions, that is, they can often find exactly the optimal value function and the optimal policy.¹</p><p>This contrasts with the approximate method described here, which only find approximate solutions, but which in return can be applied effectively to much larger problems. As in all of artificial intelligence, there is a tension between breadth of applicability and mathematical tractability. An agent that learns an optimal policy has done very well, but in practice this rarely happens. For this task, optimal policies can be generated only with extreme computational costs. We can only approximate to varying degrees.¹</p><p>Manual validation of the model is obviously time consuming and not practical at all. Because of that, plotting of heuristic metrics along with loss and episodes is explained in the next part.</p><h3>What is next?</h3><p>Measuring and plotting is key to deep learning research. In Part 3, plotting method is explained. Also, agent is finalized and challenged against players online. <strong>Taking the input from the screen, clicking on appropriate spots, agent was able to beat majority of the players.</strong></p><p><a href="https://medium.com/p/e4a2992112a1">Link to Part 3</a></p><h3>About Me</h3><p>I’m a Data Scientist, living in San Francisco. Passionate about finding answers from data. Find me on Linkedin: <a href="http://linkedin.com/in/sakarya">Ömer Sakarya</a></p><h3>References</h3><p>[1]: Sutton &amp; Barto. <a href="https://www.amazon.com/Reinforcement-Learning-Introduction-Adaptive-Computation-ebook/dp/B07JN1QFW5/ref=sr_1_2?crid=352FL757QDCAK&amp;dchild=1&amp;keywords=sutton+and+barto+reinforcement+learning&amp;qid=1587862288&amp;sprefix=sutton+barto+rein%2Caps%2C249&amp;sr=8-2"><em>Reinforcement Learning, An Introduction</em></a><em> </em>(2018)</p><p>[2]: Goodfellow, Bengio &amp; Courville. <a href="https://www.amazon.com/Deep-Learning-NONE-Ian-Goodfellow-ebook/dp/B01MRVFGX4/ref=sr_1_3?dchild=1&amp;keywords=deep+learning&amp;qid=1587862365&amp;sr=8-3"><em>Deep Learning</em></a><em> </em>(2016)</p><p>[3]: Hasselt et al. <a href="https://arxiv.org/abs/1812.02648"><em>Deep Reinforcement Learning and the Deadly Triad</em></a><em>. </em>arXiv:1812.02648v1 [cs.AI] 6 Dec 2018</p><p>[4]: Hasselt et al. <a href="https://deepmind.com/research/publications/human-level-control-through-deep-reinforcement-learning"><em>Human-level control through deep reinforcement learning</em></a>. Nature 518, pages529–533. 2015</p><p>[5]: Schaul et al. <a href="https://arxiv.org/abs/1511.05952"><em>Prioritized Experience Replay</em></a>. arXiv:1511.05952v4 [cs.LG] 25 Feb 2016</p><p>[6]: Smith et al. <a href="https://arxiv.org/abs/1708.07120"><em>Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates</em></a><em>. </em>arXiv:1708.07120v3 [cs.LG] 17 May 2018</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7097478d402" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/playing-treasure-drop-with-deep-reinforcement-learning-part-2-3-e7097478d402">Playing Treasure Drop with Deep Reinforcement Learning — Part 2/3</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>
        <item>
            <title><![CDATA[Playing Treasure Drop with Deep Reinforcement Learning — Part 1/3]]></title>
            <link>https://medium.com/data-science/playing-treasure-drop-with-reinforcement-learning-tabular-q-learning-part-1-x-2eb789c2ff5e?source=rss-ebcfa050d49f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb789c2ff5e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-plays-puzzle]]></category>
            <dc:creator><![CDATA[Sakarya]]></dc:creator>
            <pubDate>Wed, 13 May 2020 05:39:11 GMT</pubDate>
            <atom:updated>2020-05-15T02:10:10.358Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI Plays Puzzle</h4><h3>Playing Treasure Drop with Deep Reinforcement Learning — Part 1/3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CINe-_itkSwA7A3fA-xBYA.png" /><figcaption>This is what the agent “sees” while playing against other players online.</figcaption></figure><h4><strong>In this article series, I went through explaining the Reinforcement Learning (RL) project I have worked on. At the very end, you will know how this works:</strong></h4><p><a href="https://youtu.be/FhhPJIZnJ1M">WATCH This AI beat human player in a real time puzzle game</a></p><p>The idea of applying reinforcement learning to a novel, not-yet-explored problem have always intrigued me. I had a lot of free time to get busy amidst the coronavirus pandemic. Also, I used to play this game back then when I was younger. This project made just a perfect side hustle to work on during this time.</p><p>I discussed unique and notable aspects of the problem, what techniques I used and why. Hopefully, readers interested in Deep Reinforcement Learning find all of this insightful.</p><h4>In Part 1 (this part),</h4><p>Started out attacking a smaller and easier version of the original problem, by reducing size of the game table. This reduced the state space significantly, making problem more approachable. Along with the smaller problem, a relatively simpler technique, geared towards smaller state spaces: Tabular Q-learning is used. It helped building intuition about the problem. This intuition was very useful later on when solving the problem with Deep Q-learning Networks (DQN).</p><h4>In Part 2,</h4><p>After getting the validation and early success needed with tabular approach, DQN is implemented for the same problem as Part 1 using Keras library. However, learning process got unstable due to the nature of the project. Several methods are borrowed from research papers and implemented to mitigate the problem. Those are namely, Prioritized Experience Replay, Target Q-Network, Cyclical Learning rate with Learning Rate Finder. (<a href="https://medium.com/p/e7097478d402">Part 2</a>)</p><h4>Finally in Part 3,</h4><p>Tracking learning progress and plotting is key to deep learning research. In order to track the learning progress, heuristic metrics are explained and plotted along with the MSE loss over iterations of episodes. Trained models are challenged against each other to understand which learning process yields better agents. Agents are trained for different rounds of the game (1, 2, 3 and 4) and put together to perform online. Framework for taking input from computer screen and performing actions are explained. <strong>Taking the input from the screen, clicking on appopriate spots, agent was able to beat majority of the players.</strong> (<a href="https://medium.com/p/e4a2992112a1">Part 3</a>)</p><p><strong>GitHub repository for Part 1/3:</strong><a href="https://github.com/arapfaik/td-deepreinforcementlearning-part1">td-deepreinforcementlearning-part1</a></p><h4>In this part,</h4><p>our problem domain, the game of <em>Treasure Drop</em> is explained and broken into pieces in terms of five major elements of any reinforcement learning application:<strong> <em>Environment</em>,<em> Agent</em>,<em> State</em>,<em> Action</em> and <em>Reward</em></strong>. Following that, the learning algorithm is briefly touched upon and reasons given why it’s suitable for this problem. Next, heuristic metrics for convergence are defined and our model is evaluated by both metrics, and by (the fun part) playing against it.</p><p>Let’s start with defining the Environment.</p><h3>Environment</h3><p>Each player takes turns dropping one coin at a time into the top of the board. The goal of the game is to make drops which will cause coins falling out of the bottom of the board, into the point slots. Hence the name, <em>Treasure Drop!</em> The greater the point values, the better. For more description about the game: <a href="https://yppedia.puzzlepirates.com/Official:Treasure_Drop">Link to Official Website</a></p><p>If you are curious about how the final agent performs against real players online, feel free to take a look at the video below. Watching it is strongly recommend in order to get a better understanding of the game, as it’s challenging to explain the game dynamics merely by textual description.</p><p><strong>WATCH: How agent performs in “real world”</strong></p><p>As you might have seen in the video, the game is played in four rounds. For each round, the scores at the bottom of the board are different. For the sake of simplicity during the training of models, rounds are ignored, they are not an input for the model. Only round one (first round) is considered for a given model.</p><p>You might be wondering then, how the agent in the video performs in a 4-round game? The answer is, there are actually 4 models, each trained individually for a different rounds, different scores, put together using a wrapper class. Only one is activated depending on the round of the game.</p><p>The game mechanics is simulated in python to create a training environment. TreasureDrop class is the abstraction of the game. Here is a console output of printState() method below. Also, demo() method of the agent class lets you play against it by taking input from console. It was very useful to see how the agent plays against me over the course of this project.</p><p>demo() method also prints predicted q-values. Being familiar with the game, I was able to judge quickly if q-values made sense or not. In the figure below,“O” denotes a lever with a coin in the slot, whereas “V” denotes one without. Don’t worry about the rounds for now, only round 1 is considered for this part. Imagine they don’t exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2CRQSGC_CN-fxMerTsRfA.png" /></figure><p>The board above is 4x5. Board sizes are referred by {width of the top row} x {height of the board}. It’s good to start small in any project. It is easier to train an agent for a smaller board size. Also, it validated the assumption that this problem was learnable by reinforcement learning techniques. For this part, we will solve for the smaller board sizes such as those:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYV7pQvR-HU1dQHhvLK4vA.png" /></figure><p>In order to apply a technique that has more success rate, and to validate my assumption that this game is learnable, tabular approach to the problem is used first. Smaller size is used in order to render the problem feasible. There are 2⁶⁰ possible states in the original (4x5) game table. It’s computationally infeasible to build a table with 2⁶⁰ entries. But it’s OK for the sizes above,</p><h3>State</h3><p>Which brings our discussion to the definition of <em>state</em>. The game has couple data points that could be included into the state and can be perceived by the model. Those are namely, round, scores, whose turn it is and position of levers. In order to keep the model simpler and training process robust, only collective <em>lever states</em> are considered to be included in the state. A <em>lever state</em> is the state of an individual lever, encoded as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JzEPfixibHqN9dJanT0e8w.png" /></figure><p>As you might have noticed in the video, that is exactly how a lever is perceived by the model. <em>State</em> of the game is simply collection of indidivual <em>lever states</em>. Every lever state is added up from left to right, top to bottom, in the same order as written English. The corresponding state for the given game table is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcZfHYV_FTBarThh12SzbQ.png" /><figcaption><strong>State</strong> is the input to the model. It’s put together by concatenating lever states.</figcaption></figure><h3>Action, Reward and Next State</h3><p>An <em>action</em> refers to dropping a coin from the top of the game table from any of the slots. Slots are indexed starting from 0, and incremented by one as moving to the right. Depending on the <em>action</em> taken, a<em> reward</em> and <em>next state</em> will follow deterministically. Reward is sum of total points gained after taking an action. That is determined by coins reaching the scores at the bottom of the board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rruZ6uICSCpqDIc9eTSLvw.png" /></figure><h3>Agent</h3><p><em>Policy </em>determines what action is taken next. Q-values for each action will be determined by the underlying model. Agent follows <em>greedy policy</em>, meaning that it will pick the action with the highest q-value.</p><p>Reinforcement Learning is about learning from interaction how to behave in order to achieve a goal. The reinforcement learning agent and its environment interact over a sequence of discrete time steps throughout the course of training. The goal is, again, to train an agent that makes good <em>sequence of decisions.</em></p><p>This decision process is modeled as Markov Decision Process (MDP). In MDPs, we estimate the value Q(s, a) of each action a in each state s. Q-value, 𝑄(𝑠, 𝑎) is the <em>expected discounted reward</em> if we perform action 𝑎 in state 𝑠, then follow optimal policy from then on. These state and action dependent quantities are essential to accurately assigning credit for long-term consequences to individual action selections. ² ³</p><p>Consider the figure above. Given state s and actions 0, 1, 2 and 3, our policy picks the action with <strong>highest</strong> Q-value among Q(s, 0), Q(s, 1), Q(s, 2) and Q(s, 3). Therefore, the task of reinforcement learning becomes finding a function Q that correctly outputs Q-values.</p><p>In order to come up with that function, in this part, we will build a table that has entries (q-values) for each (state, action) pair. This is known as Q-table. In the following parts, this Q-value function will be approximated instead. However, the learning algorithm in both tabular and DQN implementations will stay the same.</p><h3>Learning Algorithm</h3><blockquote>If one had to identify one idea as central and novel to reinforcement learning, it would undoubtedly be temporal-difference TD learning.</blockquote><blockquote>— Sutton &amp; Barto</blockquote><p>Temporal-difference learning, as known as TD learning is selected for the learning algorithm. It’s job is to update the Q-value function at every time step. Meaning that it will update some entry in the Q-table every time agent takes an action.</p><p>One of the advantages of TD methods over other reinforcement learning methods are that, TD methods can learn directly from raw experiences without a model of the environment’s dynamics. Also, TD updates can invoke on every step, contrast to Monte Carlo (MC) methods, in which algorithm waits until the end of the episode in order to do the update. This makes TD very natural to implement in an online fashion. ² The method used in this project is called one-step TD, as known as TD(0). One-step simply means that the update equation considers only one-step of rewards.</p><p>Initially, all Q-values are initialized to arbitrary values. Agent plays the game by following epsilon-greedy policy, at each iteration, agent drops a coin and receives a reward, At each iteration, Q-value function is updated according to the Bellman equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CNWwfvW-KN-BiMiyO38IQ.png" /><figcaption>Bellman Equation is heart of Q-learning. This is also how the table is updated at each step in TD(0) algorithm.</figcaption></figure><p>For a fixed size of policy, TD(0) is proven to converge deterministically to a single answer for tabular implementations of the algorithm. ²</p><h3>Modifications to the Bellman Equation</h3><p>Due to nature of the problem, one small change was needed to be made to the Bellman Equation. In some of the popular and well known reinforcement learning problems such as <a href="https://cs.stanford.edu/people/karpathy/reinforcejs/gridworld_td.html">gridworld</a>, <a href="https://towardsdatascience.com/ai-learning-to-land-a-rocket-reinforcement-learning-84d61f97d055">lunar lander</a> and <a href="https://towardsdatascience.com/cartpole-introduction-to-reinforcement-learning-ed0eb5b58288">cartpole</a>, the action of the next state is also decided by agent. In other words, the next state belongs to the same agent. Our problem is a turn-based game, next state does not belong to the agent. Matter of fact, <strong>the next state actually belongs to the enemy.</strong></p><p>In lunar landing, it’s desirable to go to a state with a high q-value. Whereas in our problem, it is sort of the opposite. Agent has to make sure that while aiming to collect the most rewards, the next states must always be a of as low value as possible. To repeat, the maximum value of the (next state, action) is as important to us as the reward itself. This is a zero-sum game and a winning strategy would be to restrict enemy’s rewards as well as earning rewards at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*sTjVwXJKP1VqzTJNNu0L_w.gif" /><figcaption>Learned final agent versus online opponent.</figcaption></figure><p>The agent plays under the username “Playwme”. Although not always, it usually avoids such actions taken by the opponent, knowing that the next state might bring more points to the enemy than the short-term reward. Because of this phenomena, agent <strong>has to </strong>make sure that the enemy doesn’t get to make too valuable actions, at least not better than the reward we are getting.</p><p>This piece of knowledge about game dynamics necessitates a small change to the update equation TD(0) algorithm uses (Bellman Equation) in order to gear it towards this problem.</p><p>Because of this domain-specific phenomena, it makes sense to switch the plus sign belonging to the <em>discount factor</em> and therefore <em>estimate of optimal future value</em> to negative. It’s denoted in red in the following modified Bellman’s Equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHEQW47YFxdyIzeY52x69w.png" /></figure><p>To translate this change in written English, what it means is: {value of state, action} = {the reward I get} – {the maximum value of next state, action belonging to the enemy}</p><h3>Hyperparameters</h3><p>There is not much hyper parameter tuning taking place here since this is just a toy example. However, mentioning the effect of exploration rate is worthwhile.</p><p>Exploration rate has an effect on the distribution of states the agent encounters throughout the course of learning. <strong>In Data Science, underlying distribution of data determines what the model learns.</strong></p><p>If the exploration rate is low, (around 0.05–0.1) agent is exposed to states that are likely to be encountered during a competitive game more frequently than the case with a high exploration rate. Conversely, if the exploration rate is 1, the agent plays randomly and gets exposed to states when the actions are randomly picked. The agent will learn more about what it gets exposed to, just like humans.</p><p>Let’s assume there is an <em>edge state</em>, a state that is not likely to be reached without intensive exploration. If the exploration rate is low, that state would not be reached well enough, resulting in a not-so-accurate q-value in the table. Also let’s assume there is a <em>core state</em>, an important state that is frequently encountered during some point at competitive games, the exploration rate needs to be low in order to get exposed to that state more. The more agent gets exposed to the core state, the better it knows how to behave when faced with that core state during a competitive game.</p><p>Whether the exploration rate is 0.05 or 1, Q-table will fill up with the correct q-values sooner or later, depending on the size of the table. It is just a matter of time for the edge and core states to be explored depending on the exploration rate. Tabular implementations of TD(0) are guaranteed to converge to the right solution.</p><h3>Model Validation</h3><p>Although not the most scientific, the most fun way of validating the model is to play against it. As an automated way of testing the model, there is no direct way of doing it as in lunar landing in which the cumulative reward would make sense. However, there are couple ways in which we can obtain a “heuristic” score of the model’s ability to capture the right q-values. One of them is to look at the q-values for two mirror imaged boards below. Two mirror imaged boards simply mean that the game tables are inverted by the y axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Fc7NJwt6-9nxG1FyoeCKg.png" /></figure><p>Notice how the actions corresponding to each other have very close Q-values? Why does this matter? If the Q values are very close for actions corresponding to the equivalent action on the other table, it means that our model can see that both actions bring the same reward and transition to an equivalent state. It’s worthy to note that the model is able to capture that without us supplying the game mechanics or letting the model know that the two states are mirror images of each other along the y-axis.</p><p>Note that the scores might not event exist, let alone being close if the state is one that is not likely to occur during a competitive game. After all, what we are dealing with here is a statistical model, no magic. If the agent have not encountered the state during training, chances are, it won’t have any opinion about it.</p><p>Another heuristic is based on the fact that some of the neighboring action pairs transition to the same next state and reap the same reward. More specifically, if a top-row lever has a coin on it, both left and right actions lead to the same effect for that lever, and hence same effect for the entire board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wY0H0PQw6GgndcrIDfuGrQ.png" /></figure><p>As in the figure above, the Q-values for 0 &amp; 1 and 4 &amp; 5 are very close. This is because simply, both actions will lead to the same reward and next state, both by moving the coin on that lever. If the agent figured this out, it probably figured out the whole game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*csQnFeSS_H6zea2xEjqD_w.gif" /></figure><p>That it not the case for actions 2 and 3, although they are next to each other. Therefore, it would make sense for those two actions to share a very close q-learning. Again, if the model can say that the q-values for those actions are very close, it’s a strong indicator that the model understood the game very well.</p><h3>Model in Action ⚔️</h3><p><a href="https://github.com/arapfaik/td-deepreinforcementlearning-part1">Link to GitHub Repository</a></p><p>Go ahead and run the notebooks. There are two notebooks in the GitHub repository. One for running the agent from already calculated q-tables. On the other one, you can train an agent from scratch just by running the cells all the way down.</p><p>See if you can beat it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcGK3ogUX4bpz9x0JHZrUg.png" /></figure><h3>What is Next?</h3><p>Now we know that the problem is solvable by reinforcement learning methods. In Part 2, we exchange tabular implementation for DQN to applicability for larger problems.</p><p>Tabular methods can often find exact solutions, that is, they can often find exactly the optimal value function and the optimal policy. This contrasts with the approximate methods described in the next parts, which only find approximate solutions, but which in return can be applied effectively to much larger problems.²</p><p><a href="https://medium.com/p/e7097478d402">Link to Part 2</a></p><h3>About Me</h3><p>I’m a Data Scientist, living in San Francisco. Passionate about finding answers from data. Find me on Linkedin: <a href="http://linkedin.com/in/sakarya">Ömer Sakarya</a></p><h3>References</h3><p>[1]: <a href="https://yppedia.puzzlepirates.com/Official:Treasure_Drop">Treasure Drop: Puzzle Pirates Official Website</a></p><p>[2]: Sutton &amp; Barto. <a href="https://www.amazon.com/Reinforcement-Learning-Introduction-Adaptive-Computation-ebook/dp/B07JN1QFW5/ref=sr_1_2?crid=352FL757QDCAK&amp;dchild=1&amp;keywords=sutton+and+barto+reinforcement+learning&amp;qid=1587862288&amp;sprefix=sutton+barto+rein%2Caps%2C249&amp;sr=8-2"><em>Reinforcement Learning, An Introduction</em></a><em> </em>(2018)</p><p>[3]: Goodfellow, Bengio &amp; Courville. <a href="https://www.amazon.com/Deep-Learning-NONE-Ian-Goodfellow-ebook/dp/B01MRVFGX4/ref=sr_1_3?dchild=1&amp;keywords=deep+learning&amp;qid=1587862365&amp;sr=8-3"><em>Deep Learning</em></a><em> </em>(2016)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb789c2ff5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/playing-treasure-drop-with-reinforcement-learning-tabular-q-learning-part-1-x-2eb789c2ff5e">Playing Treasure Drop with Deep Reinforcement Learning — Part 1/3</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>
        <item>
            <title><![CDATA[Selenium Tutorial: Scraping Glassdoor.com in 10 Minutes]]></title>
            <link>https://mersakarya.medium.com/selenium-tutorial-scraping-glassdoor-com-in-10-minutes-3d0915c6d905?source=rss-ebcfa050d49f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d0915c6d905</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Sakarya]]></dc:creator>
            <pubDate>Mon, 14 Oct 2019 14:51:24 GMT</pubDate>
            <atom:updated>2020-04-06T00:38:39.918Z</atom:updated>
            <content:encoded><![CDATA[<p>I scraped jobs data from Glassdoor.com for a project. Let me tell you how I did it…</p><h4>What is Scraping?</h4><p>It’s a method for collecting information from web pages.</p><h4>Why Scraping?</h4><p>Other than the fact that it is fun, Glassdoor’s library provides a limited number of data points. It doesn’t allow you to scrape jobs or reviews. You only get to scrape companies, which was useless in my case. In this guide, I will share my way of doing it along with the Jupyter Notebook.</p><h4>Why Selenium?</h4><p>Good question! Glassdoor renders its content with Javascript. Which means that a simple get request to the webpage below would return only the visible content. We are interested in more than that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3hYmMuIjXpQQEL_5ODoSw.png" /></figure><p>There are data points such as company valuation and job location under the “Company” tab and we want to access that information as well. The webpage does not show that content unless the user clicks on the “Company” tab. This makes clicking on the “Company” tab necessary. Using requests library and doing simple get requests would not work for this type of website. Therefore, the only way to scrape that data is to write a program that mimics a human user. Selenium is a library that lets you code a python script that would act just like a human user.</p><h4>What we will build?</h4><p>Essentially we will be building a python script that would give us a DataFrame like this:</p><figure><img alt="Job listings DataFrame, scraped from Glassdoor.com" src="https://cdn-images-1.medium.com/max/1024/1*hEHM3uj2i3zljqowhIpC7A.png" /></figure><p>The python script will exactly do the following. Search for a given keyword, click on each job all on the job listings all the way down, click on different tabs in the job description panel, scrape all the data. When it reaches the end of the list, it will go to the next page of results and keep doing the same thing, until a target number of jobs scraped. The final result will simulate Google chrome like the following. Everything is automated, no human interaction involved below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nDuesTz6v46eEQZKnZ5kdQ.gif" /></figure><h4>Pre-requisites</h4><ul><li>Working knowledge of python</li><li>python version 3.x</li><li>Jupyter notebook installed</li><li>Very basic knowledge of html</li><li>Some knowledge of <a href="https://www.w3schools.com/xml/xml_xpath.asp">XPath</a> would also go a long way.</li><li><a href="https://pypi.python.org/pypi/selenium"><strong>selenium</strong></a> library installed</li><li><a href="https://sites.google.com/a/chromium.org/chromedriver/downloads"><strong>ChromeDriver</strong></a><strong> </strong>placed on a directory you know.</li></ul><h4>The Core Principle of Web Scraping</h4><p>It is quite simple. Let’s assume you have an eye on some web page element (such as text) and would like to scrape it. Elements on a web page reside in a hierarchy. You just need to tell your code the “address” of the element within that hierarchy.</p><p>Let’s take the headquarters information of a company as an element of interest. In the picture below, the headquarters of this company is San Francisco, CA. Therefore, we should scrape “San Francisco, CA”. All you need to do is, right-click and “Inspect Element”. That will open a small window with the html content of the web page, with your element highlighted for you. You also see where the elements are placed in the hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NdhpIPkbyOaXkiJWHJuuw.png" /></figure><p>You can not see the rest of the hierarchy in the picture but it does not really matter anyway. Because we will use relative address in order to explain where the element is. We are going to say, look for a div, with a class of “infoEntity” that has a label as a child, which has “Headquarters” as text, and take the text inside the following sibling of it. We are just going to say it in a formal way. The XPath below does just that. We do not have to mention the whole hierarchy because chances are, this description fits only this html element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjlcZih8mUWjos1YX1INOQ.png" /></figure><pre>#Also putting the code in text form in case you&#39;d like to copy and paste.</pre><pre>try:<br>        headquarters = driver.find_element_by_xpath(&#39;.//div[<a href="http://twitter.com/class">@class</a>=&quot;infoEntity&quot;]//label[text()=&quot;Headquarters&quot;]//following-sibling::*&#39;).text       <br>    except NoSuchElementException:<br>        headquarters = -1</pre><p>If you understand what we’re doing here, it means that you can easily scrape almost any webpage you’d like. We are basically describing the long, awkward sentence in the paragraph above in a formal way. Feel free to take a deeper look into <a href="https://devhints.io/xpath">XPath</a> if you’d like.</p><p>Also, notice that we have put the statement inside a try-catch clause. This is good practice if you are scraping web elements since they might not even exist. For glassdoor’s case, not all fields are always available. A company might not have put up their headquarters to glassdoor. If that’s the case, for the data fields, you might want to assign a “not found” value. I have chosen -1 for that purpose.</p><h4><strong>The Code</strong></h4><p>You can download the Jupyter notebook <a href="https://github.com/arapfaik/scraping-glassdoor-selenium"><strong>here</strong></a><strong> </strong>. If you were able to understand what we did above and have a basic knowledge of python, you should be able to read the code with comments. For the rest of this post, I will explain little tricks in the code that are not so obvious why.</p><p>Note that you need to change the path to the chromedriver so that it points to the chromedriver in your local file system.</p><h3>Bypassing the Sign-Up Prompt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5F8YgliOlMUYAtAcuw0BlA.gif" /><figcaption>Bypassing the sign-up prompt</figcaption></figure><p>One challenge scraping the glassdoor was that if you have not signed up, which in our case you won’t, as soon as you click anywhere on the screen, it asks you to sign up. A new window comes up and blocks selenium from clicking anywhere else. This is the case every time selenium does a new search or go to the next page of job listings. The way we are dealing with this is that we click the X button to close it right after clicking on an arbitrary job posting on the website. In the code, the arbitrary job is the topmost job listing. It comes selected as default. Therefore that element’s class name is “selected”. We can find and click on it by find_element_by_class_name(“selected”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qD7LTA1kynsMGeblSJhR4A.png" /></figure><h4>How About Glassdoor API?</h4><p>As of today, Glassdoor does not have any public API for Jobs. Which means that you have to do scraping if you want to get data about job posting. I heard you saying thank you. You are welcome.</p><p>Also, Glassdoor does not have an API for reviews either, which might be of interest to you. I would recommend <a href="https://nkoenig06.github.io/scrape-gd.html">this</a> tutorial in case you would like to obtain reviews.</p><h4>Getting rejected or throttled by Glassdoor</h4><p>One other point about Glassdoor’s website is that, if you get too aggressive about get requests, Glassdoor will start rejecting or throttling your connections. In other words, if you were to do a get request to multiple links at once, it is likely that your IP address will get blocked, or you’ll have a slow connection. Those things leave us no other option than writing a script that browses the website like a human would, clicking through jobs listings, without raising too many eyebrows on Glassdoor’s servers.</p><h4>It is annoying that a new Chrome window opens every time I run the script.</h4><p>I totally hear you on that. You can also let selenium do all the scraping in the background, without opening a browser window, although it might get tricky. This way of scraping is called “headless”. You need to paste this code between your driver definition and driver.get and your script should do the scraping in the background.</p><p>options.add_argument(‘headless’)</p><h4>Pros</h4><p>Small chance of getting caught by glassdoor and your http requests starting to getting rejected or throttled.</p><p>You are getting more data fields than Glassdoor’s API. In fact, you are able to get even more if you extend the code for scraping the data points you are looking for.</p><h4>Cons</h4><p>This method is suitable if you are looking to scrape couple hundreds of jobs. For thousands, you might want to leave your laptop overnight or have multiple jupyter notebooks do the scraping simultaneously, which gets messier since it increases the density of http requests to Glassdoor, which in turn, increases your IP address to be blocked.</p><h4>THE END 🎉 🎊</h4><p>Hope you enjoyed reading, cheers! 😊 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d0915c6d905" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Must Know List of Libraries for Android Game Developers]]></title>
            <link>https://medium.com/android-bits/most-frequently-sdks-used-by-top-game-apps-8977f18d8cb0?source=rss-ebcfa050d49f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8977f18d8cb0</guid>
            <category><![CDATA[google-play-store]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Sakarya]]></dc:creator>
            <pubDate>Fri, 04 Oct 2019 21:13:36 GMT</pubDate>
            <atom:updated>2019-10-10T14:48:33.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IP-81XmD8ylh01H5DW2WrQ.jpeg" /></figure><h3>Top SDK Libraries Used By Top Game Apps</h3><p>Interested in mobile game development? Want to find out what SDKs are commonly used among top game apps? Well, you are welcome to take a look at our curated list of most common SDKs among top 100 game apps in the Google Play Store. Knowing each and every SDK in this list will empower every mobile game developer. Being aware of what tools are available brings developers much closer to building great apps.</p><h3>What is an SDK?</h3><p>SDK stands for software development kit. They are basically shortcuts for app developers, providing functionality that would otherwise take a lot of time to code. If your app is going to make it big, it is likely that you are going to implement SDKs in your app here and there. SDKs are created for apps to succeed!</p><p>We have curated the SDKs that have been currently used by the game apps in the Top 100 Free category in the Google Play Store. The data is from Mobile Action’s SDK Intelligence tool.</p><p>There are different SDKs for different purposes. Among most common use cases for implementing an SDK are advertising and development aid are the biggest categories for SDKs. Let’s start by game engines.</p><h4>Game Engine</h4><p>You need to pick a game engine for your app. Well, here are the three popular game engines used: Unity3d, Fmod, Cocos2DX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNcMAIt9yTQzrKkvc8WaOw.png" /></figure><h4>Development Aid</h4><p>Apart from game engine, your app would need all sorts features demanding all sorts of development aids. A huge list of development aid SDKs came up during our analysis. If you are new to game app development or if you are already developing games for android, it is very useful to know what tools are out there to help you developing your apps. This list excludes native SDKs that have been used by almost all the apps such as XML PULL, Android Package Management, Android Support and Google Mobile Services. Following is a list of other most commonly used ones: OpenGL, Apache Http, Firebase, Bolts Base Library, OkHttp, Google GSON, Multidex, Retrofit, ZXing, fabric, Picasso, Exoplayer, Volley, Dagger, EventBus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYFDJLVVGcGRAnzxhJvx7A.png" /></figure><h4>Advertisement</h4><p>You will need to make money at the end of the day. In case your app is free and without in-app purchases, Advertisement SDKs will help you monetize your app with advertising. Here is the list of the most popular advertisement SDKs. Keep in mind that our sample includes free apps only. Therefore, the percentages are highly likely to be biased (bigger than usual) compared to paid apps: Google Ads, Facebook Ads, Unity Ads, IronSource, Applovin, Vungle, Adcolony, Integral Ad Source, Mopub, Chartboost, TapJoy, Inmobi, Fyber, Millenial Media, Amazon Advertising, Smaato, hyprMX, myTarget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6r8zkFc9OANgdEpBZ9TRPg.png" /></figure><h4>Mobile Analytics</h4><p>Mobile Analytics SDKs help you collect insights about how your users interact with your app. It is almost essential to any app to collect usage data and SDKs make this so much easier: MOAT, Crashlytics, AppsFlyer, Tenjin, Flurry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nX7gAgep-MPaXA97QJcv1Q.png" /></figure><h4>Social Network</h4><p>Either take it as a fun fact or not, %93 percent of top 100 free game apps use Facebook’s SDK. Which means that around %90 of those apps use Facebook login.</p><h4>Payment</h4><p>Interestingly, payment SDKs are not popular among top free game apps. This aligns with the fact that Advertisement SDKs are wildly popular in this category, as seen by the list above. Only one payment SDK were popular enough to be considered mentioning, Amazon Payment services were implemented by merely %7 of the apps in the top games charts.</p><h4>Final Note</h4><p>We hope that readers benefit from knowing what SDKs are available for mobile game development. This list is not exhaustive as we have omitted the SDKs that were not used by more than %10 of the apps we have considered for this study. Once again, our sample of apps were the top 100 free game apps in Google Play Store.</p><p>All data is sourced from <a href="http://mobileaction.co/"><strong>Mobile Action</strong></a><strong>’s </strong><a href="https://www.mobileaction.co/blog/mobile-action-news/product-update-sdk-intelligence-available/"><strong>SDK Intelligence</strong></a> tool. If you are interested in learning more, feel free to <a href="http://bit.ly/2HYm3Eh"><strong>Schedule a demo</strong></a> with us. One of our team members will be in contact with you.</p><p>If you enjoyed, don’t withhold your claps. 😊 😊 😊 Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8977f18d8cb0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-bits/most-frequently-sdks-used-by-top-game-apps-8977f18d8cb0">A Must Know List of Libraries for Android Game Developers</a> was originally published in <a href="https://medium.com/android-bits">Android Bits</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 RNNs, Sequence to Sequence Language Translation and Attention]]></title>
            <link>https://medium.com/data-science/introduction-to-rnns-sequence-to-sequence-language-translation-and-attention-fc43ef2cc3fd?source=rss-ebcfa050d49f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc43ef2cc3fd</guid>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[seq2seq]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <dc:creator><![CDATA[Sakarya]]></dc:creator>
            <pubDate>Sun, 23 Jun 2019 14:19:06 GMT</pubDate>
            <atom:updated>2019-06-28T23:40:58.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CC9bYb65DtGlg2X349IYOg.png" /></figure><p>The goal of this post is to briefly introduce RNNs (Recurrent Neural Networks), sequence to sequence language translation (seq2seq) and Attention. I will try to make it as simple as possible. You only need to know:</p><ol><li><a href="http://cs229.stanford.edu/section/cs229-linalg.pdf">Linear algebra</a></li><li><a href="https://towardsdatascience.com/comprehensive-introduction-to-neural-network-architecture-c08c6d8e5d98">Neural networks</a></li></ol><p>In case you feel rusty on the topics, feel free to review them before you start reading by clicking on the links above.</p><p>I recall that when I have first learned feed-forward neural networks, I taught to myself, would that be possible to build this network of neurons in a better way? Because in the human brain, neurons are connected in a more complex way then they do in a feed-forward neural networks. Turns out that, researchers continuously find new ways to align neurons to get them to do something useful. RNNs are one of them.</p><p>In a neural network, you have one output per input. You have an image and you have a label, for instance. There is no way you can input image after image on Neural Networks and get an output based on all of them. The nature of neural networks make them unable to process sequential data.</p><p>On the other hand, RNNs work very well with sequential data. They have a mechanism of “remembering” the previous inputs and producing an output based on all of the inputs. This makes them well-suited for sequential type of data such as text, audio, video or any time-series data.</p><p>The diagram below shows five variations of RNNs. Red vectors are inputs whereas blue vectors are the outputs. First one is a one input to one output situation. Which is essentially a neural network. The others are capable of sequential inputs and outputs, such as:</p><p><strong>one to many: </strong>image -&gt; caption sentence<br><strong>many to one: </strong>sentence -&gt; sentiment (positive / negative label)<br><strong>many to many:</strong> a sentence in English -&gt; a sentence in Turkish<br><strong>the other many to many: </strong>frames of video -&gt; coordinates of bounding boxes around an object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDYrtsaNKU28qbd9dccPcw.png" /></figure><p>Let’s start to look under the hood by looking at a feed-forward neural network with one hidden layer. Since each layer is essentially a linear transformation and therefore a matrix multiplication, I am denoting each layer’s operation with a set of parameters in matrix form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIEQOAIDzkw8urP7FFEI4A.png" /></figure><p>An input of size 5 goes through a matrix multiplication with a 5x3 matrix, producing the input for the hidden layer, vector of size 3. Then, it gets multiplied by a 3x4 matrix, producing an out put of 4. Pay attention to the vector of size 3 here. In RNNs, we will call it the <em>hidden state.</em></p><p>Let’s take a look at slightly modified version of that. We have added just the area inside the dashed rectangle. Also, we have added one more parameter matrix, 3x3 in this case. What happens is that, we are adding one more input from the bottom. All inputs need to be of the same size. Because it also goes through the same, blue matrix multiplication as the bottom one. Notice that, the hidden output we had before gets multiplied by a square matrix before being combined with the new input. We never know what that operation is. It is just something that the RNN learns to do itself while training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_oVm1iB6vjtxIpy_iL3mA.png" /></figure><p>Now, let’s extend the dashed area and make it a loop. This way, the input can be of any size larger than or equal to one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l2eElFbuqF_fXCcQbkaoAA.png" /></figure><p>What we are essentially doing is that, we are applying a recurrent formula to every input from the sequence. What we have at the very end depends on the whole input sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPoj4Sm-kJKvjqr4mNAcBA.png" /></figure><p>Notice: the same function and the same set of parameters are used at every time step.</p><p>To delve deeper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*NyJiZyl-xtDcQZI0wX9thg.png" /></figure><p>To picture it with the parameters we initially had:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jTnjL3LMYfhCBRSfgAV_Q.png" /></figure><p>What you have just read is an explanation of Vanilla RNNs, the most basic form of RNNs. It’s easy to learn, however, they are hard to train. The reason is that, the values in the hidden states tend to exponentially explode or vanish. More advanced RNNs such as LSTM and GRUs mitigate that problem by adopting more sophisticated mechanisms. <a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21">There is an excellent blog post by Michael Nguyen on LSTMs and GRUs.</a> I would strongly suggest you to check it out for further reading.</p><h3>Part 2: RNNs with words: Language Models</h3><p>Language Models try to predict the next word, given a sequence of words. It might sound useless at first, as it did to me. However, they are usually components of other more useful Natural Language Processing systems.</p><p>Let’s look at a diagram very similar to our Vanilla RNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zq4WlcQrHcd6dlfmu98Q-A.png" /></figure><p>Here, the inputs to the RNN are word embeddings, not actual words. If you don’t know what a word embedding is, think hash function, but for vectors. Instead of representing words from vocabulary as one-hot encoded vectors, embeddings represent them as lower dimension vectors. It provides the benefit of faster linear operations because of lower dimension vectors. That’s what <em>E</em> means in the diagram.</p><p>We, Wh, and U are blue, green and orange matrices in the previous diagrams, respectively. This diagram depicts training of a Language Model. “The students opened their exams…” are from the training corpus; the sentence actually exists. We are penalizing the Language model by a loss function comparing pairs of y_hat^(1) and x^(2), y_hat^(2) and x^(3) and so on. Notice that as we go on towards the right, model also keeps the hidden state so that it keeps track of the past words.</p><p>After trained for a while, a language model can generate text by predicting the next for over and over. Notice that, the predicted words, y_hat^(i) are the input for the next step of operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tU4JxcBFuYG0uZIdEpDbrQ.png" /></figure><h3>Part 3: Sequence to Sequence Machine Translation</h3><p>RNNs are also capable of doing natural language translation, aka. machine translation. It involves two RNNs, one for the source language and one for the target language. One of them is called an <em>encoder, </em>and the other one<em> decoder. </em>The reason is that, the first one encodes the sentence into a vector and the second one converts the encoded vector into a sentence in target language.</p><h4>Encoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMgHqTod9DT4dTymcLf0yw.png" /></figure><p>The encoder is an RNN. Given the source sentence, it produces an encoding. Notice the benefit of RNNs here. The size of input sentence can be any size.</p><h4>Decoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vSZhReamsgVas2brl1dFg.png" /></figure><p>The decoder is a separete RNN. Given the encoded sentence, it produces the translated sentence in target language. Notice the purple, dashed arrows. Every predicted word is an input to the next prediction. This is the recurring nature of RNNs and it is very interesting to me that they can do a significant work such as language translation by being connected like that.</p><p>At each step of the decoder, given the hidden state and input word vector as input, the argmax of a probability distribution of words is chosen as the most probable word. This is called greedy decoding. The problem with that is, the decoder is going one by one. At one point, if the sentence does not make sense, it can not go back.</p><p>Also, the whole sentence being encoded in a single vector is hard to translate into a sentence. After the encoding step, it is essentially a mapping from sentence to a vector. It it really hard for the decoder to derive an order for the words in the target language. That’s where attention comes into play.</p><h3>Part 4: Attention</h3><p>Attention lets the decoder to focus on specific parts of the input sentence for each output word. This helps the input and output sentences to align with one another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NVOXo0n0rsmEavHcnbeBDg.png" /></figure><p>In the picture, the blue ovals are simply dot products with the sentence encoding and hidden states.</p><p>For the French sentence above, the highest attention score belongs to “les”. This will cause the decoder to start the translated sentence with “the”. When I first saw that diagram, I thought that, if the correct translation started with “pauvres”, there is no way the decoder would get it right. However, since this neural network is supposed to be trained end-to-end, it will also learn to produce correct attention scores along the way.</p><h3>Closing Note</h3><p>For complete beginners, this might be a lot of information in a short text. Rachel Thomas’s way of introducing to RNN at a class at USF have inspired me to write this blog post. I wanted to sum up what caught my interest on a high-level. Feel free to ping me if you have any questions! 🎉 🎊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc43ef2cc3fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/introduction-to-rnns-sequence-to-sequence-language-translation-and-attention-fc43ef2cc3fd">Introduction to RNNs, Sequence to Sequence Language Translation and Attention</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>