<?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 Ashutosh Makone on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Makone on Medium]]></description>
        <link>https://medium.com/@ashutoshmakone?source=rss-fdec78b582dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gVXHxGe2Imnl9WAcFsiH6g.jpeg</url>
            <title>Stories by Ashutosh Makone on Medium</title>
            <link>https://medium.com/@ashutoshmakone?source=rss-fdec78b582dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:01:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutoshmakone/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[Reinforcement Learning 8: Pick and Place Robot in an E-Commerce Store Warehouse i.e.]]></title>
            <link>https://ashutoshmakone.medium.com/reinforcement-learning-8-pick-and-place-robot-in-an-e-commerce-store-warehouse-i-e-78d7af7e60c8?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/78d7af7e60c8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Tue, 31 Aug 2021 00:04:48 GMT</pubDate>
            <atom:updated>2021-08-31T02:32:29.282Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reinforcement Learning 8: Pick and Place Robot in an E-Commerce Store Warehouse i.e. Q-Learning in Action</h3><p>Walk the Talk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w61465C7pmlrYW3k" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaearle?utm_source=medium&amp;utm_medium=referral">Joshua Earle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Generally, the Embedded people or the robotic amateurs, when experiment with pick and place robot without using reinforcement learning, they feed a full map of the environment in the memory of robot. What we are doing here is completely different. The robot will be trained using Q-Learning. It will know nothing about the environment initialy. It doesn’t even know that there is a destination where it has to reach. It will figure out everything over a lot of episodes using Q-Learning.</p><p>Its is very fascinating to see Q-Learning in action. To demonstrate that, i am considering a pick and place robot in an E-Commerce store warehouse. We will give the location of an object, which will also be the starting location of the robot and from there it will find the best path to carry the object to the packaging area. There are obstacles in the path and there is going to be a penalty (negative reward) if the robot bumps into the obstacle. Also it has to reach the packaging area in minimum amount of time, so there is a very small negative reward for every step it takes. The environment is shown below, in a not so pretty diagram. Take time to understand the environment to fully appreciate the power of Q-learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*OJN7QIqugY2M4tT1r28ztA.jpeg" /><figcaption>Fig 1: Map of warehouse of E-Commerce store.</figcaption></figure><h3><strong>Understanding The Environment</strong></h3><p>The total environment is divided into a grid of 8 by 8. So there are 8 rows and 8 columns. Those rows and columns are indexed from 0 to 7 as shown in the left and top of figure 1. These indices are also used in the code to help traversing using loops. But every cell in the grid is also given a code name. These code names are shown in top right corner of every cell. The names start from A1, A2…… A8 for first row and so on. The red cells are the one’s which are forbidden for the robot. If it bumps into this red area, then there is a rewards of -20 as shown in the bottom. From information given in the bottom, it is also clear that reaching the target at Cell E8 which is at index (4,7) has a reward of 100 (that’s where the packaging area is) and robot is allowed to move along all the white cells which has a reward of -1. This negative reward of -1 will motivate the robot to hurry up. The final result of the Q-Learning code is given in terms of code names and not in terms of indices, so that its easier to trace the output. In fact that was the very purpose of code names.</p><h3>Understanding The Code</h3><p>The code is available in my Github <a href="https://github.com/ashutoshmakone/Reinforcement-Learning-for-E-Commerce-Q-Learning-in-Action-">here</a> . Please keep an eye on the code while reading this section. The code is mostly self explanatory (really!).</p><p>First we create a numpy array which represents the map of rewards in ware house. So the array element is -1 for white cells, -20 for red cells and 100 for green cells. Then we define epsilon for Epsilon Greedy Strategy. Then discounting factor, learning rate and number of actions. All these terms are already explained in my previous articles. A Q-table is defined as a numpy array and initialized with zeros. Its a three dimensional array with number of rows and columns of warehouse as first two dimensions and number of actions i.e. 4 as the third dimension.</p><p>A dictionary is created to map the indices with the code names. So a tuple containing indices is the key and a code name is the value of the dictionary. A function called location_next( ) takes current row and current column and selected action as input and returns the new row and new column that the agent will get into after performing the action. The action is decided by the function action_next( ) using Epsilon Greedy Strategy. The start_pos( ) functions assigns a random starting position for the agent during every episode of training.</p><p>Then a for loop which runs for 1000 times to train the agent, first gets a starting position for the agent from start_pos( ) function. Then a while loop runs until the agents doesn’t enter into an illegal(red colored) cell. Following steps are performed in the while loop that are essential for Q learning.</p><p>1. From current row and column, based on Epsilon Greedy Strategy next action is selected.</p><p>2. The current row and current column are saved as old row and old column.</p><p>3. The location_next( ) function gives next location based on the selected action</p><p>4. Reward is obtained for this selected location.</p><p>5. For on action performed in old row and column, the Q value is obtained from the map_rewards numpy array.</p><p>6. Using reward obtained in step 4 and Q value of old location obtained in step 5, the temporal difference is calculated. This calculation also requires the value of gamma and the maximum Q value for current position of agent.</p><p>7. Using the temporal difference, Q value of old location and alpha, a new Q value is calculated.</p><p>8. This new Q value is updated in the Q table.</p><p>To understand these steps fully refer to my previous article,”Reinforcement Learning 7: Q-Learning”. I am giving the relevant equation from that article i.e.equation 3 for reference below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/0*9IK-9GifaTcAl8dC.png" /></figure><p>This equation which updates the values in Q table is used to train the agent with reinforcement learning and is coded in python using steps given above.</p><p>After training, finally when final_path( ) function is called with any starting location for agent that we choose, the final_path( ) function returns, the best path for the agent (pick and place robot in our case). Now that the training is over and its time to get the results, the action_next( ) function takes value of 1 for epsilon to exploit the environment. Suitable actions are chosen from the learned Q-table and the best path is returned in the form of series of code names. The reverse mapping from indices of locations to the code names is done by the get_codeNames_path( ) function.</p><p>Go through this explanation of code multiple times to get full understanding of the code available in my <a href="https://github.com/ashutoshmakone">Github</a>.</p><h3>Results</h3><p>Finally when the code is tested for multiple random input locations of robot, accurate results are obtained.</p><ol><li>For example</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*gbnXinl0OjPIfjmC8rl37w.png" /></figure><p>If the input locations of robot is given as (3,3), the it chooses the path as shown in above image. I have drawn this path with blue color on the warehouse map with freehand for demonstration as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*rBspy4v5Noe0SL52-ch6Zw.jpeg" /></figure><p>2. The second input is given as (5,0)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_zaDoBqnSww9oo7FiKSQQ.png" /></figure><p>The output look like this ..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*6pVlSzKBe3EYyHZUicHC7w.jpeg" /></figure><p>3. The third input is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXAIn6TkLWZyaAOpuwSSHA.png" /></figure><p>And corresponding output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*_j_rbmI0B0Sx4NYLiOk2VA.jpeg" /></figure><p>More sample inputs and their output paths are given in Github.</p><p>I hope this implementation of Q-Learning is quite clear to you now. Please feel free to give suggestions, feedback or ask queries</p><p>Happy Coding !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78d7af7e60c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning 7: Q-Learning]]></title>
            <link>https://ashutoshmakone.medium.com/reinforcement-learning-7-q-learning-675ee255ebf6?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/675ee255ebf6</guid>
            <category><![CDATA[markov-decision-process]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[deep-q-learning]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 21:27:02 GMT</pubDate>
            <atom:updated>2021-08-23T21:27:02.685Z</atom:updated>
            <content:encoded><![CDATA[<p>The result of action depends upon the very quality of the action …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S2-2ekW7ZRI_2bRV" /><figcaption>Photo by <a href="https://unsplash.com/@geekgunda?utm_source=medium&amp;utm_medium=referral">Chinmay Bhattar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In one of my previous articles, Reinforcement Learning 5: Finite Markov Decision Processes (part-3), I explained action value function which is denoted by q(s,a) or simply q. The optimal q value function is denoted by q*. The optimal q value also gives, optimal policy.</p><p>Remember, q function is a function of state and action. It is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*dG_wYiDl6Cy9kVTAR0frhg.png" /></figure><p>The optimal q function returns the expected return when action a is taken in state s. This Bellman equation also shows that it is the expected return of immediate reward and the discounted value of optimal q value in next state. The optimal q value in next state is maximum of the return for all possible actions in that next state.</p><p>The bellman equation is used to calculate the q value for each state and is updated after every episode. With enough number of episodes, the q value converges to its optimal value. So a simple table can be created and updated for each pair of state and action. At the start, all q values are initialized with zeros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rbKg3q7iQUmCGBHtCEMUw.jpeg" /><figcaption>Fig 1: A simple maze</figcaption></figure><p>Figure 1 shows a simple maze that we have considered in one of my previous articles. Initially the q table will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*Uj6MgI7tPjTWIE7GtQlSsA.png" /></figure><p>All Q values are initialized to zero. As the agent will move around the environment (as per its exploration and exploitation policy), the q values in the table will be updated as per the Bellman equation and eventually it will converge to optimal q values. This table will then be used to define the optimal policy. Thus basically q value indicates the quality of an action a in a given state s.</p><p>Thus Q-learning is trying to find the optimal policy without trying to find the underlying mathematical model. Hence Q-learning is considered model free.</p><h3>What if the Environment is changing with time ?</h3><p>In a lot of real world scenarios,the environment itself is changing. If we consider a pick and place robot, if during its learning phase, a new obstacle is added to the environment, then how the agent will cope up with this situation. The concept of temporal difference comes to the aid……</p><h4>Temporal Difference</h4><p>Temporal Different denoted by TD(s,a), is the measure of how much the Q-function changes from the older value to the newer value. It can be mathematically written as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*KshNlu1qM7YDwtGxo7bDsA.png" /></figure><p>Rearranging, it gives…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ja-3STny8N1MuM5gmUDJ8Q.png" /><figcaption>Equation 1</figcaption></figure><p>Lets call it equation 1.</p><p>Rearranging this gives the expression for TD as…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*EXVR3C6SkQaeWeGI4YbenQ.png" /></figure><p>The first term on right hand side is the current Q value and we know that it can be calculated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*3PHltTDnupO05_rqBDd_SQ.png" /></figure><p>Putting this back into expression of TD gives …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*b0_bDszhvGoRzdICSFbEow.png" /><figcaption>Equation 2</figcaption></figure><p>Lets call it equation 2. Putting this in equation 1 gives…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*vsVc5_bGYIvXwHWnfX0X2g.png" /><figcaption>Equation 3</figcaption></figure><p>Lets call it equation 3. The expression in square bracket is for TD. The alpha term added to the equation is called learning rate and it tells how quickly can the agent adapt to the changes in the environment.This equation gives us a way to update the Q-table. We will use these equations in next article to demonstrate a complete example of Q learning. We will do this in python from scratch.</p><p>The real fun is about to begin !!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=675ee255ebf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning 6: Exploration vs Exploitation]]></title>
            <link>https://ashutoshmakone.medium.com/reinforcement-learning-5-exploration-vs-exploitation-c1bae5a2ea42?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1bae5a2ea42</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[exploration-exploitation]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Sun, 22 Aug 2021 23:20:16 GMT</pubDate>
            <atom:updated>2021-08-22T23:22:34.932Z</atom:updated>
            <content:encoded><![CDATA[<p>How much greedy is good enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*brcWZn6GeiJqRmJO" /><figcaption>Photo by <a href="https://unsplash.com/@gabriel_meinert?utm_source=medium&amp;utm_medium=referral">Gabriel Meinert</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before getting into Q-Learning, lets understand the importance concept of Exploration vs Exploitation.</p><h3>Exploration vs Exploitation</h3><p>Exploration is trying new possibilities in order to find better rewards. Exploitation is to keep opting for same actions that has given some significant rewards in the past. To illustrate this we can consider an example of restaurants. Suppose i recently start living in a new city. On a lazy weekend, i am fade up of cooking myself and and want to try a restaurant. I start visiting different restaurants on every weekend. In 2 to 3 weekends i discovered a restaurant and i found it really good. So for next few weekends i visited the same restaurant. This has now become my number one favorite restaurant. This is called exploitation: keeping visiting something that is sure to get some good result/reward. But in doing so, i might be missing on restaurants which are even better than this one. But by visiting only this restaurant, i will never know what i am missing. So a better strategy is to visit a different restaurant once in a while. Doing this may sometime lead to disappointment (due to not so good food as compared to my number one favorite restaurant), but sometime i may find a restaurant which is better than my previous number one favorite restaurant. This is called exploration. Exploration is trying new unknown actions which may lead to either disappointment or better reward.</p><p>Thus there are two terms : Exploration and Exploitation. Exploitation gives the agent a guaranty of reward, but it may not be the best reward possible in the environment. In Exploitation a lot of environment remains unexplored. While in Exploration, agent tries to opt for unknown actions, which he hasn’t tried before which takes him to unknown states, this may lead to either disappointment or better reward. For best possible results from reinforcement learning, both Exploration and Exploitation are important.</p><p>What is a perfect balance between Exploration and Exploitation is an important question and there are various strategies to deal with this, This dilemma is unique to reinforcement learning and its never encountered in supervised or unsupervised learning.</p><p>In a planning context, exploration means trying actions that improve the<br>model, whereas exploitation means behaving in the optimal way given the current model.</p><p>To make it even more clear let me give a quick example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pC6bsiWY0j-t2lbfhqk8Dg.jpeg" /><figcaption>Fig 1: Exploration vs. Exploitation</figcaption></figure><p>Suppose the agent is in state 5. Its start moving in the environment randomly. It goes up to state 1 and then to state 2 where the reward is +3 as written in bracket. Now that it knows, the path 5–1–2 always gives a rewards of +3, if it keeps selecting these actions, then its called Exploitation. But this way rest of the environment will remain unexplored. So, once in a while if, it tries a different path to find if there is a better reward waiting for it somewhere, then that’s called Exploration. So instead of moving to state 1 , if it moves into state 9, in few episodes, it may discover that there is a better reward in state 12.</p><h4>Epsilon greedy strategy</h4><p>One way to keep a balance between Exploration and Exploitation is called as Epsilon greedy strategy. Epsilon is the Exploration rate whose value is always between 0 and 1. When Epsilon=1, the agent is in fully exploration mode.So it only cares about exploring the environment. This is a good way to start initially. But after a while when the environment becomes more familiar, the agent may decide to reduce the value of epsilon gradually. So now after a while if Epsilon becomes equal to 0.9, the 90% of the time the agent is still exploring the environment while 10% of the time it is interested in grabbing the rewards that it has discovered during exploration in the past. As environment becomes more and more familiar and there is less of it remained to explore, the value of Epsilon goes on decreasing and exploiting becomes more important. In other words, agent becomes more greedy over the time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1bae5a2ea42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning 5: Finite Markov Decision Processes (part-3)]]></title>
            <link>https://ashutoshmakone.medium.com/reinforcement-learning-5-finite-markov-decision-processes-part-3-e085b64a4503?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e085b64a4503</guid>
            <category><![CDATA[monte-carlo-method]]></category>
            <category><![CDATA[markov-decision-process]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Sun, 25 Jul 2021 04:36:51 GMT</pubDate>
            <atom:updated>2021-07-25T04:36:51.370Z</atom:updated>
            <content:encoded><![CDATA[<p>That’s part of the policy. To keep switching gears. — Ridley Scott</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JOinTAz2fk6UY0Io" /><figcaption>Photo by <a href="https://unsplash.com/@hpzworkz?utm_source=medium&amp;utm_medium=referral">Hassan Pasha</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Policies and Value Functions</h3><p>Estimating value functions is the vital aspect of reinforcement learning. It tells how good it is to perform a given action in a given state and how good it is to get maximum expected return. A policy is a function that maps a given state to probabilities of selecting each possible action from that state. The policy of an agent changes with experience.</p><p>There can be multiple value functions corresponding to multiple policies. The policy that gives the greatest value of expected return is called as the optimal policy and the corresponding value function is called the optimal value function</p><p>I know the things are bit messy so far, but they will eventually get crystal clear to you. keep reading …….</p><p>Just to give you an idea of how optimal value function and optimal policy are related to each other, i will give you an example in following image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*RvmqtzWFcRsynO60uCIxVg.png" /></figure><p>So just for you, i have jumping ahead a lot, like a lot. So the above diagram shows an optimal value function(V with a *) on the left and optimal policy (pi with a *) on the right. To get these values, an agent has to do a lot of interactions with the environment, keep calculating and updating value functions and after a lot of experience, it arrives at the optimal value function shown on left(i have skipped all those steps for now). So how these values are calculated is something i will cover later. But do you see any correlation between values on the left and the arrows on the right. You are right. From every cell the arrow goes in the direction of maximum value in the adjacent cell in left, right, top and bottom. So once an agent has this optimal policy, then there is no confusion. If you drop the agent in any of the cells, it surely knows where to go next. It has to follow the arrows, that’s it. got it? Now lets begin from beginning…</p><h3>Policies and Value Functions</h3><p>There are two types of value functions. State value function and action value function. Lets get some notations clear…..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*fyJu6yzbdobXx3KkULOoLw.png" /></figure><h4>State value function:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*OEZ9ZPiF1ooA3iWJ-cBGjw.png" /></figure><p>The above equation is the formulation of state value function which is denoted by v. As we know, E indicates Expected value, G indicates returns, R indicates rewards and gamma is the discounting rate. All of this is explained in my previous article.</p><p>Thus the first step says that, the state value function is the expected return when starting in s and following a policy pi thereafter. Remember that its not just the immediate reward but the total cumulative reward, that is expected here, as shown in second step.</p><h4>Action value function:</h4><p>Similarly action value function is defined as the expected return of taking action a in state s under a policy pi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*xh-0fZ-KLjVImy0xpCIIXw.png" /></figure><p>Evidently, action value function is denoted by q.</p><h4>A glimpse of Monte Carlo:</h4><p>The agent has to gain a lot of experience through interactions with environment to estimate the state value function and action value function. For example, if an agent while following a particular policy, maintains an average of the actual returns, that have followed a particular state, then the average will converge to the state’s value i.e. the value function of the state. But for this convergence, the number of times the agent encounters that state should tend to infinity(theoretically).</p><p>If instead of maintaining average of just one value of actual returns, we maintain separate averages of actual returns for every possible action from that state, then we will converge to action value function.</p><p>These kind of methods are called <em>Monte Carlo Methods</em>.</p><h4>Recursive Relationship of Value Functions</h4><p>We can develop the recursive relationship for value functions, just like we had for return G.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQQO_w_4nV7LwVWcUcbUQA.png" /></figure><p>There are four steps above. Lets go through them one by one. First step simply says, that the state value function for a given state is equal to the expected returns when the agent is in that state. The second step simply replaces return G with its expression, that we already learned in my last article. Just to revise, the return G at time t is equal to the immediate reward at time t+1 added with discounted cumulative return at time t+1.</p><p>The third step replaces the “expected” part of step 2 with actual probabilities. We already know that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*7L0wqdhHw2HDCNpUyapaoQ.png" /></figure><p>So the first summation in step 3, iterates over all actions possible in that state and multiplies the probability of each action with the next summations. s is the current state and s’ is the next state. The next two summations iterates over all possible combinations of next states and resulting rewards. So how to interpret p(s’,r|s,a) ? If the given current state is s and if the agent takes an action a in this state then, p(s’,r|s,a) is the probability of s’ being the next state with r being the corresponding reward. The square bracket in step 3 is similar to square bracket in step 2, except the fact that the returns in next state s’ are replaced with expected returns for all possible next states s’. (Because there is different probability of going into any of the next possible states and hence different expected return)</p><p>In fourth step the summations are combined for s’ and r. Also the expectation term in step 3 is replaced by state value function of s’, by definition. Thus the forth step gives recursive relation between state value function of s and s’.</p><p>This forth step is also called the Bellman equation for state value function.</p><h3>Optimal Policies and Optimal Value Functions</h3><p>So after all the reinforced learning, the agent has to come up with an optimal policy. So a policy is considered as the optimal policy if its expected return is greater than all other policies. In other words, a policy whose state value function is greater than all other policies, is the optimal policy and the corresponding state value function is called as optimal state value function. As shown in the very first diagram, the optimal policy is denoted by pi with a star and the optimal state value function is denoted by v with a star. If there are more than one policies with same highest state value function, then all of them are denoted by the same notation. The optimal state value function is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*XMIPVXro8ba1LSrMblt2_Q.png" /></figure><p>Optimal policies also share the same optimal action-value function defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*5kTJqZQ_91oLmKY_5bLlWg.png" /></figure><h3>Backup Diagrams</h3><h4>Backup diagrams for state value function and action value function:</h4><p>Backup diagrams are used to depict the relationships between states, possible actions from those states and possible next states resulting from those actions. They are called backup diagrams because they transfer value information to the state or state-action pair from the successor states or state-action pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*NwP8EPGMmu8UuE5bycYRUQ.png" /><figcaption>Backup diagrams for state value function</figcaption></figure><p>Shown above is a backup diagram for state value function. Each open circle represents a state and each solid circle represents a state–action pair. From the first state shown at the top, the agent can take an action from a set of actions based on probability pi. Three possible actions are shown in figure. These three actions lead to next state s’ from a set of states based on probability p with a reward of r. The backward propagation of value information in such diagrams helps in calculating the state value function for state s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*uhaoOdRNfobPcxj-fTJs1Q.png" /><figcaption>Backup diagrams for action value function</figcaption></figure><p>Backup diagrams for action value function is shown in above diagram. There is a state-action pair at the top. Based on the probability, the actions leads us to next state s’ from a set of states. And from thereon, based on a probability pi, an action is taken which leads to next state-action pair. The backward propagation of value information in such diagrams helps in calculating the action value function for state-action pair (s,a).</p><h4>Backup diagrams for optimal state value function and optimal action value function:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*dIVIobk67xhK4-VqLuLznQ.png" /><figcaption>Backup diagrams for optimal state value function and optimal action value function</figcaption></figure><p>These are the Backup diagrams for optimal state value function and optimal action value function. They are very similar to the previous backup diagrams, with a difference that an arc is shown after every state. The agent has choices at those arcs and the arc indicates that the maximum over those choices is taken while computing optimal state value function and optimal action value function.</p><h3>What next?</h3><p>Bellman equation is a linear equation with a very high computational complexity of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*ecyp_wjzWGYKvQQ_itW80A.png" /></figure><p>It is ok to use it for small problems. But to handle bigger problems, we need more innovative mathematical tools listed below</p><ol><li>Dynamic Programming</li><li>Monte Carlo Evaluation</li><li>Temporal-Difference Learning</li></ol><p>Stay tuned !!!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e085b64a4503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning 4: Finite Markov Decision Processes (part-2)]]></title>
            <link>https://ashutoshmakone.medium.com/reinforcement-learning-4-finite-markov-decision-processes-part-2-35abce41044d?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/35abce41044d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[markov-decision-process]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Sat, 24 Jul 2021 18:20:47 GMT</pubDate>
            <atom:updated>2021-07-24T18:20:47.462Z</atom:updated>
            <content:encoded><![CDATA[<p>There is always some maths ….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7kusv4INVaf05BTd" /><figcaption>Photo by <a href="https://unsplash.com/@roman_lazygeek?utm_source=medium&amp;utm_medium=referral">Roman Mager</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Episodic Tasks and Continuing Tasks</h3><p>The agent-environment interaction can happen in two types of situations. One in which, the interaction can be broken into sub-sequences called as episodes. For example a game play. In games like chess or Atari games, every game is a episode which ends in a state called terminal state. The terminal state can be winning or loosing or a game being draw. After this terminal state the game is reset and the next episode starts all over again. Not just games, but any tasks that can be broken into such episodes are called as Episodic Tasks. All the non-terminal states are denoted by S while all the states including terminal state are denoted by ‘S+’. The time of termination is denoted by T and its value normally varies from episode to episode.</p><p>The other type, where the task can not be broken into any such episodes, rather it goes on continuously without any break or terminal state, is called as Continuing Task. Here the time of termination T is infinity. The examples of Continuing Task can a robot who is suppose to work continuously without a break throughout it life span.</p><h3>Returns and Episodes</h3><p>There is a mathematics that is running behind the agents goal to maximize the cumulative reward. By now it must have been very clear that cumulative reward is the result of, not only the next immediate reward but all the rewards the agent is going to receive in the long run. In general, the target is to maximize the expected return, where the return is denoted by G and it is defined as some specific function of the reward sequence. In simplest case, this return can be considered as the simple sum of all the rewards as follows. (but its not always the right way to define the return)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*OHlD9-kJf15q85RuLqMeuA.png" /><figcaption>Equation 1 : Total Return as a simple sum of all rewards in an episodic task</figcaption></figure><p>Thus the return G at time t, is the sum of all rewards at time steps t+1, t+2,t+3…….. up to T. This definition of return G can be suitable for some episodic tasks. But for continuing tasks where the time of termination, T is infinite, the return G could also be infinite. For example if the return at each time step is 1, then total return is infinity. To avoid this a discounting factor(also called discount rate) gamma is included in the expression as follows…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*FZF32ji63eJ_oenlUpNALQ.png" /><figcaption>Equation 2: Total Return as a sum of all rewards with discount rate in a continuing task</figcaption></figure><p>The discount rate gamma is always in the range from 0 to 1. suppose its value is 0.9, then the first reward at time t+1 is taken as it is, while the next reward at time t+2 is multiplied by 0.9. Hence 90% of its value is considered. The third reward at time t+3 is multiplied by 0.9 x 0.9 = 0.81. Hence 81% of its value is considered. For fourth reward, only (0.9 x 0.9 x 0.9 =0.729) 72.9% of its value is considered in total return. And so on …… Thus a reward received after k+1 time steps, is multiplied by gamma to the power k as shown in second equation in above figure.</p><p>Thus the immediate reward is given highest importance while the future rewards are given less importance. The farther it is in future, the less is its role in computing the return G. Hence if the discounting rate is less than 1 and the reward sequence is bounded, then the infinite sum in above equation has a finite value. If the discounting rate is zero, then in the above equation, all the terms except the first term with reward at time t+1, become zero. This kind of agent is “myopic” as it is only interested in maximizing the immediate reward and doesn’t care about the subsequent rewards. On the other hand, as the discounting rate gamma approaches 1, the future rewards are taken into account more strongly and the agent becomes more farsighted.</p><p>For example, in the game of chess, an agent who cares only about the next move has very high chances of loosing the game while an agent who can foresee future moves, has very high chances of winning.</p><p>Bobby Fischer, my most favorite chess player, while playing a game, which is now famously known as <a href="https://www.youtube.com/watch?v=A82NI_42kgY">the game of the century</a>, once said that he had next 16 moves already calculated in his head before he sacrificed his queen (which is also considered as the move of the century) in that game and eventually won it while playing against Donald Byrne<strong> </strong>who held the title of international master. Bobby was only 13.</p><p>The above equation can be arranged in a more meaningful way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*5ubboODeJfHJEPouu1HyJQ.png" /></figure><p>Taking gamma common in second step and replacing the bracket with return at next time step t+1. The “poetic” meaning of this equation is that, while choosing any action the agent has to take into account the immediate reward (first term) and the cumulative foreseen discounted reward/return (second term) from resulting next state.</p><p>Now, even if every reward becomes 1 in an infinite sequence i.e. in a continuing task, still the total return will not be infinite as long as we keep discounting factor less than 1 as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*Pq6_a56URv2D6cv3MxkgEA.png" /></figure><h3>Unified Notations for Episodic and Continuing Tasks</h3><p>In our future discussions, sometimes we deal with episodic tasks and sometimes with continuing tasks, but most often with both. So it is convenient to obtain one notation that covers both the cases simultaneously. Equation 1 above, is for episodic tasks while equation 2 is for continuing task. These two can be unified by a scheme as shown in figure below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*qiJNqOYFCmMhUeHdnntmQA.png" /></figure><p>Lets consider an episodic task with T=3 i.e. task with only 3 time steps and every reward is equal to 1. So the return G can be expressed with only three terms of equation 1. So total return =R1+R2+R3= 1+1+1=3. Now lets imagine a special absorbing state drawn with a solid square in above figure. This state transitions only to itself and generates only rewards of zero. So after R1, R2 and R3 states, we can conveniently assume R4, R5, R6 …… and so on, without really affecting the total return, as these newly assumed returns are all zeros. So now the total return =R1+R2+R3+R4+R5+ ……… = 1+1+1+0+0+0+0 …….=3. Thus our episodic task with T=3 can now be considered as a continuing task with T=infinity, without affecting the total return. And for this continuing task equation 2 is now equally applicable. Thus we have unified the notations for Episodic and Continuing Tasks.</p><p>See you in the next part !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35abce41044d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning 3: Finite Markov Decision Processes (part-1)]]></title>
            <link>https://ashutoshmakone.medium.com/reinforcement-learning-3-finite-markov-decision-processes-part-1-3cc0a513a9ae?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cc0a513a9ae</guid>
            <category><![CDATA[markov-chains]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[markov-decision-process]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Sat, 24 Jul 2021 13:27:35 GMT</pubDate>
            <atom:updated>2021-07-24T13:27:35.203Z</atom:updated>
            <content:encoded><![CDATA[<p>Learning along the way …..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k9gJr9agJ8-2osKK" /><figcaption>Photo by <a href="https://unsplash.com/@alschim?utm_source=medium&amp;utm_medium=referral">Alexander Schimmeck</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Markov Chains and Markov Process</h3><blockquote>According to Wikipedia,</blockquote><blockquote>“A <strong>Markov chain</strong> is a <a href="https://en.wikipedia.org/wiki/Stochastic_model">stochastic model</a> describing a <a href="https://en.wikipedia.org/wiki/Sequence">sequence</a> of possible events in which the probability of each event depends only on the state attained in the previous event”.</blockquote><p><strong>Andrey Andreyevich Markov </strong>was a phenomenal Russian mathematician who is best known for his work on stochastic processes. In probability theory , any process with which some randomness is associated is called stochastic process. Markov chain talks about a sequence of events in which the probability of every event depends on its previous event. For example if there is a sequence of events like e1, e2, e3, e4, e5, e6…….. whose corresponding states are s1, s2, s3, s4, s5, s6….. respectively then the probability of occurrence of event say e5 corresponding to state s5 depends only on state s4 of event e4.</p><p>Thus mathematically,</p><p>P(s5|s4) = P(s5|s4,s3,s2,s1)</p><p>Yes, the vertical line in above equation has the same meaning of conditional probability. Thus s4 is the present state and P(s5|s4) is the probability of occurrence of s5. So the probability of state s5 given s4 has occurred is same as probability of state s5 given s4,s3,s2 and s1 has occurred. Thus to predict s5, s4 is enough and the information associated with s3, s2 and s1 is not necessary. Such a sequence of possible events is called as Markov chain. A simple example of Markov chain is a game of snakes and ladders which is played with a dice. Every next move in such a game depends on its current state(position) and not on previous states.</p><p>The same concept can be applied to a Markov process.</p><blockquote>According to Wikipedia,</blockquote><blockquote>A stochastic process has the Markov property if the conditional probability distribution of future states of the process (conditional on both past and present values) depends only upon the present state; that is, given the present, the future does not depend on the past. A process with this property is said to be <strong>Markovian</strong> or a <strong>Markov process</strong>.</blockquote><p>Thus a process in which the occurrence of future states depends only on the present state and not on the past states.</p><h3>Markov Decision Process</h3><blockquote>According to Wikipedia,</blockquote><blockquote>In mathematics, a <strong>Markov decision process</strong> (<strong>MDP</strong>) is a discrete-time stochastic control process. It provides a mathematical framework for modeling decision making in situations where outcomes are partly random and partly under the control of a decision maker.</blockquote><blockquote>At each time step, the process is in some state s and the decision maker may choose any action a that is available in state s. The process responds at the next time step by randomly moving into a new state s ′ and giving the decision maker a corresponding reward R( s , s ′ )</blockquote><p>There are various things to understand</p><ol><li>MDP is a discrete process. That means the events are going to occur at discrete time steps like t1, t2, t3, t4, t5……. and so on.</li><li>The outcomes are partly random. They are not fully under the control of a decision maker. That means there is some stochasticity associated with them. The decision maker is the one that was referred as Agent in my last article.</li><li>In every state s, the Agent has a set of possible actions available to him. Depending on which action he chooses, he goes into a new state denoted by s’. And depending on the effectiveness of this action, he gets a reward R.</li></ol><h3>Finite Markov Decision Process</h3><p>A Markov Decision Process has three elements associated with it.</p><ol><li><strong>S:</strong> A set of all possible states also called as state space.</li><li><strong>A:</strong> A set of all possible actions also called as action space.</li><li><strong>R:</strong> Immediate reward that the agent receives after transitioning from state s to s’.</li></ol><p>A Markov Decision Process in which there are finite number of elements in set S, A and R, i.e. there are finite number of states, actions and rewards, is called as Finite Markov Decision Process.</p><p>If the previous state is s and a is the action taken in previous state, then the probability of next state being s’ with a reward of r is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*g59LrTA1_gBDqwyiTVrWjg.png" /></figure><p>The equal to sign with a dot on it indicates that its not really an equation. The RHS is merely elaborated definition of LHS. So if s and a are the state and action in time step t-1 then the probability of s’ being the next state with reward r is given by above equation/definition. The quantities on right hand side of vertical line | in LHS and RHS are previous state and previous action while those on left right hand side of vertical line are probable present state and reward.</p><p>For this process to be a Markov decision process, every state in the process must include the necessary information about all the past interactions between agent and environment that may affect the future decisions. If every state, in process satisfies this condition then it is said to have the Markov property.</p><p>The expected rewards for state action pairs can be expressed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*0PArJIdJ2KizqBAJvVLBZA.png" /></figure><p>E indicates the expected value of expression inside square bracket. The expression inside the square bracket is reward R at this time step t if the previous state was t-1 and previous action was a.</p><p>In general, actions can be any decisions we want to learn how to make and the states can be anything we can know that might be useful in making them.</p><h4>More about Agent and Environment</h4><ol><li>Agent is part of environment but it is crucial to define the boundary between agent and environment.</li><li>Anything, that an agent cant change arbitrarily is considered to be outside of it and is part of the environment.</li><li>Every thing in the environment is not always assumed to be unknown to the agent.</li><li>The agent often knows how the reward is calculated as a function of its actions and states.</li><li>But the agent do not have any control over how the reward is computed.</li><li>Sometimes the agent knows everything about the environment, but it doesn’t always mean that its easy for the agent to solve the Reinforcement Learning problem, just as we know how the Rubik’s cube works, but its not easy to solve it.</li><li>The agent-environment boundary represents the limit of the agent’s absolute control, not of its knowledge.</li><li>Reinforcement Learning problem is the problem of goal directed learning from interactions of agent with the environment inside the abstract MDP framework.</li><li>Any such problem can be reduced to three signals : choices made by agent(actions), the basis on which the choices are made(states), the agent’s goal (rewards).</li></ol><h3>Goals and Rewards</h3><p>The environment gives a reward to agent for each action taken by an Agent. A reward is nothing but a scalar signal. It can be a positive reward for a good action, negative reward for a bad action and a zero reward for actions that do not matter much. This is just one way in which this can be done. There can be others schemes as well. The agent’s goal is to maximize the rewards. Not just the immediate reward for present action taken from present state, but also all the future rewards. In other words, we can say the goal is to maximize the cumulative reward in the long run.</p><blockquote>So the reward hypothesis goes like this:</blockquote><blockquote>That all of what we meant by goals and purposes can be well thought of as the maximization of the expected value of the cumulative sum of a received scalar signal (called reward)</blockquote><p>For example, if we want to train a robot to find and collect empty soda cans for recycling, then we can give a positive reward, every time it finds a can. We can give a negative reward, every time it bumps into things, so that it learn to escape things. If we give a small negative reward for every step, that do not result in collection of a can, the robot will learn to find the cans as quickly as possible.</p><p>There can be situations in which rewards can be given for intermediate steps. For example in games where the player is running along a track or a path in a territory, then intermediate rewards can be given for collecting gold coins or weapons. But sometimes giving intermediate reward may actually land up the agent in a bad situation. For example while playing chess, we know that in some situations, we may sometimes have to sacrifice our pieces or skip the chance of taking opponents pieces, to increase our chances of winning. So a positive reward can be given to agent, only if the agent wins the game and not for taking the opponent’s pieces. Otherwise the agent instead of trying to win the game, may try to maximize the reward by taking the opponent’s pieces. It may make moves for taking the opponent’s pieces that may result in making its own kings vulnerable or loosing the opportunity of opponent’s checkmate.</p><blockquote>The final take away is “ The reward signal is your way of communicating to the agent what you want it to achieve, not how you want it achieved”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cc0a513a9ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning 2: Terminology and Bellman Equation]]></title>
            <link>https://ashutoshmakone.medium.com/reinforcement-learning-2-terminology-and-bellman-equation-e19a31449b58?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e19a31449b58</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[value-function]]></category>
            <category><![CDATA[bellman-equation]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 09:22:29 GMT</pubDate>
            <atom:updated>2021-07-12T02:36:39.612Z</atom:updated>
            <content:encoded><![CDATA[<p>… and so the adventure begins !!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ys9AkuX32BScqCYr" /><figcaption>Photo by <a href="https://unsplash.com/@syinq?utm_source=medium&amp;utm_medium=referral">Susan Q Yin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Richard S. Sutton and Andrew G. Barto in their book titled “Reinforcement learning”, which is main inspiration for this series of articles, describe it as…</blockquote><blockquote>Reinforcement learning is learning what to do — how to map situations to actions — so as to maximize a numerical reward signal. The learner is not told which actions to take, but instead must discover which actions yield the most reward by trying them. In the most interesting and challenging cases, actions may affect not only the immediate reward but also the next situation and, through that, all subsequent rewards. These two characteristics — trial-and-error search and delayed reward — are the two most important distinguishing features of reinforcement learning.</blockquote><p>Ohhh wait !!! is that too much take in one go? Lets start by understanding the basic terminology with the help of a simple example of a maze ….</p><h3>Terminology</h3><p>Figure 1 shows a simple maze.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhdU2pzvIWJLhXEobOiFdg.png" /><figcaption>Figure 1 : Maze</figcaption></figure><p><strong>Agent :</strong> Agent is someone who explores and tries to get rewards in an environment. In our example, its a robot, which currently stands in state 1. In general it can be any smart entity like a piece of software. The goal of an agent is to maximize the reward.</p><p><strong>Environment :</strong> The situation which is being explored by the agent is call environment. The entire grid with all 12 states is the environment in figure 1.</p><p><strong>States :</strong> Various positions/locations in the environment are called states. There are 12 states starting from 1 to 12 in this environment. There might be any forbidden states, like state 6 in the figure. So if our environment is a room, then state 6 may be surrounded by walls, so that the robot is unable to get into that state.</p><p><strong>Actions :</strong> Actions are allowed moves for the agent to move in the environment. Our robot is allowed to take four actions : move-up, move-down, mode-left, move-right. These actions are limited by the current position of the agent. For example, from state 1, it can either move right or move down. So other actions are not allowed. When in state 11, it can move left, right or up.</p><p><strong>Reward:</strong> When the agent moves in maze and reaches a desirable position, then it gets some positive reward while there might be positions where the agent should not enter to avoid any loss. In the maze, state 12, which has a trophy symbol in it, is the desirable state, so the agent might get a reward of +10 when it reaches there. But by mistake if it enters state 8, which has a danger symbol in it, it might get a reward of -10. So to maximize the reward, the agent has to reach state 12. In other words, reward is a result of certain action that an agent takes to move into certain state. Remember that initially the agent knows nothing about the environment and it learns to maximize its rewards with experience by many trials and errors. Apart from state 8 and 12, other states can also be assigned rewards, depending on the problem statement.</p><p>For example, apart states 6, 8 and 12, we assign a reward of -1 for moving into every other state. Thus if the agent moves from state 1 along 2–3–7–11–12, the total reward is ( -1–1–1–1+10)=6 while if it moves from state 1 along 2–3–4–3–7–11–12 then the total reward is ( -1–1–1–1–1–1+10)=4. And by comparison the agent learns to avoid going from 3 to 4. This is how we force him to learn the best way to maximize the cumulative reward. Hence the name reinforcement learning.</p><p>The reward is mostly denoted by R and the general form of expressing it is as follows</p><p>R(s,a) = reward of moving from state s with action a.</p><p>For example, in our grid</p><p>R(s1,”move-right”) = -1</p><p>R(s4,”move-down”)= -10</p><p>R(s11,”move-right”)= +10</p><h3>Interaction between Agent and Environment</h3><p>The Interaction between Agent and Environment can be nicely explained using figure 2 below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/0*c75q8pIbVei9IRLL.png" /><figcaption>Figure 2: Interaction between Agent and Environment</figcaption></figure><p>Suppose the agent is in state s1 and from there it takes as action a1 at time step t1 and due to this interaction with environment it gets a reward of R2 and it goes into state s2. Again at time step t2 it will take an action a2 due to which it will get a reward R3 and it will go into state s3. Thus the interaction will proceed as per following sequence</p><p>s1,a1,R2,s2,a2,R3,s3,a3,R4………… and so on</p><p>In our maze example, this process will go on until the agent either reaches s8 where it gets the worst reward and the process terminates or it reaches s12 where it gets the best reward and the process terminates. This entire sequence becomes one experience for the agent and the process restarts as above from s1,a1,R2,s2,a2,R3 ……… and so on, for next experience.</p><p>There are two important things about this interaction</p><ol><li>The environment is completely unknown to the agent. The agent only knows that it can move left, right, up or down. But is doesn’t know how many total states are there in environment. It doesn’t know that there is a big reward waiting for it at s12 or there is a big loss in reward waiting for it in s8. It has to learn everything with experience.</li><li>The environment is not static. It may change over time.</li></ol><h3>Bellman Equation</h3><p>The Bellman equation is used to calculate value function for all valid states and it is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*lRvm6Dyp89b4PrA-QI7O9Q.png" /></figure><p>First i will explain this equation, then i will give sample calculation for Bellman equation to get value function and then i will show how to get the optimal path using value function. So have patience ….</p><p>The gamma in Bellman equation is called discounting factor. its value is in the range 0 to 1. For now lets consider that gamma =1. (more about it in a while)</p><p>The R(s,a) term in the equation is called immediate/instant reward. For example in our maze environment R(s1,”move-right”) = -1. Now s’ is the next state where the agent goes from state s. Hence V(s’) is the value function of state s’, i.e. the maximum reward that can be obtained when agent starts from s’. Consecutively to get V(s’) we need R(s’,a) and V(s’’) and so on</p><p>So if s1 is the starting state, then from there it can go to 2 or 5. If it goes to 2 then next state can be 1 or 3 (yes agent can go back, the environment is completely unknown to it.) If, from 1 it goes to 5 then next state can be 1 or 9. From 3 it can go to 2, 4 or 7. And so on ……. There are enormous number of possibilities.</p><h3>Sample Calculations</h3><p>In Bellman equation s indicates current state and s’ indicates next state. so lets calculate the value function for state 1. As i said there are enormous number of possibilities to roam around the maze if you start from 1. We have to calculate the RHS of Bellman equation for all those possibilities and choose the maximum as v(1) i.e. value function of 1. evidently 1–2–3–7–11–12 looks like the optimal path, hence lets do the calculations for this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*69G7VcytMMZZSASUpUJ9cw.png" /></figure><p>This is just one of the values obtained from one possible paths from state 1 to any other state. You can see that these calculations are recursive. Doing the same calculations for all other possible paths will give more values of v(1) and as the equation suggests , we have to choose the maximum out of them. In our maze 5 is evidently the maximum value possible. You must have already guessed that the same value can be obtained over the path 1–5–9–10–11–12. But still 5 is the maximum we have got.</p><p>Hence v(1) = 5.</p><p>Similarly we can calculate v(2) by considering all the possible paths that start from s2 and reach to any other state. Please try these calculations. I am giving all the values in figure 3 below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74LAC4HqI7xtxI5L2Bjn0g.png" /><figcaption>Figure 3: Maze with value functions for all states</figcaption></figure><p>The value functions for all states are given in red and these values are circled in figure 3. After getting these values, it is now easier for the agent to navigate for maximum reward. It has to just move in the direction of increasing values of value function. So if the agent is in state s3, it can go to s2, s4 or s7. But s7 has higher value function so it will move to s7 and so on. So now our agent has learnt by reinforcement technique.</p><h3>What about discounting factor (gamma) ?</h3><p>In Bellman equation R(s,a) is the instant reward of current action and V(s’) is the cumulative future reward of all actions that follow from s’ onward. Thus the value of gamma decides how much importance is to be given to the cumulative future reward as compared to the instant reward R(s,a). if gamma = 1, then it means equal importance is given to all future rewards. If gamma = 0.9, then 90% importance is given to reward at next state s’ and 81%(0.9 x 0.9 = 0.81) importance is given to reward at next to next state and so on. And according all calculations will change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19a31449b58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variational Autoencoders (VAE)]]></title>
            <link>https://ashutoshmakone.medium.com/variational-autoencoders-vae-60a73c8cb05a?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/60a73c8cb05a</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[variational-inference]]></category>
            <category><![CDATA[reparameterization-trick]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 05:32:42 GMT</pubDate>
            <atom:updated>2021-07-10T05:57:58.625Z</atom:updated>
            <content:encoded><![CDATA[<p>Autoencoders with variational inference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ozWFozT4g1fI6UBM" /><figcaption>Photo by <a href="https://unsplash.com/@vsmilelx?utm_source=medium&amp;utm_medium=referral">浮萍 闪电</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>There are generative models and there are discriminative models. Discriminative models discriminate between different kinds of data instances while generative models generate new instances of data. There are many types of generative models. Variational Autoencoders is certainly one of the most popular generative models. They were introduced by Diederik P Kingma and Max Welling in their research paper titled “ Auto-Encoding Variational Bayes” which can be found <a href="https://arxiv.org/pdf/1312.6114.pdf">here</a></blockquote><h4>How is it different from Autoencoder?</h4><p>So what is the difference between Autoencoders and Variational Autoencoders? An Autoencoder is mostly used for dimensionality reduction. So as shown in the figure 1, the input(x) is a high dimensional vector while the encoded representation(z) is a low dimensional vector. In order to faithfully reconstruct the input vector at the output (x’) the encoder network has to learn the features of input data. For example if the input data is images of forest then, the encoder vector will learn various features like color/shape of trees, color/shape of their trunk and color of background of sky etc. These features are preserved in encoded representation with less number of dimensions. And then the decoder network, reconstructs the original image from this representation. There are multiple applications in which Autoencoders can be used but the basic philosophy remains the same. The middle portion of the diagram is narrow and it is also called as bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*FFgwlnAd6XDeI0RX.png" /><figcaption>Fig 1 : Architecture of Autoencoders</figcaption></figure><h4>Architecture of Variational Autoencoders</h4><p>Variational Autoencoders are different in a way that instead of learning the features of input data, they learn the probability distribution of features. Thus as shown in figure 2, the distribution of various features is learned in terms of its mean and standard deviation. This way we achieve a continuous and smooth representation called as latent space representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fuEjOcDbyn3kSqtH.png" /><figcaption>Fig 2: Architecture of Variational Autoencoders</figcaption></figure><p>Every distribution in this latent space is then randomly sampled and passed to the decoder network. The decoder is now able to generate data (images of forest as specified in above example) which is similar(but not same) to our training data. This network can thus be used to generate similar dataset and this generation is evidently stochastic is nature. This is the intuition behind Variational Autoencoders as a generative model.</p><p>The encoder model and the decoder model in Variational Autoencoder are also called as recognition model and generative model respectively.</p><h4>Formulation</h4><p>As shown in figure, the input dataset is x with probability function p(x) and we want to model this distribution. The latent space encoding vector is z. So according to Bayes’ Theorem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*8WsTDmIrS5q3YOz4fQZGbA.png" /></figure><p>The set of relationships between input data and latent space can be defined as</p><p><strong>p(z) :</strong> Prior</p><p><strong>p(x|z):</strong> Likelihood</p><p><strong>p(z|x):</strong> Posterior</p><p>The denominator of RHS can be computed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*oI_gyiO-ZW3r0jQLjxEa5w.png" /></figure><p>But this integral is very difficult to calculate in higher dimensional space. One way to solve it is by using variatonal inference. If we can choose another distribution say q(x|z) (which can be computed) such that it approximates to p(x|z), then our problem is solved. So the objective is to make q(x|z) with same distribution as p(x|z), which can be done by minimizing their KL divergence. KL divergence is a measure of similarity between two distribution. A lower value of KL diversion indicates higher similarity between distributions. A detailed description of how this is solved can be found <a href="https://www.youtube.com/watch?v=uaaqyVS9-rM">here</a>. Ultimately it all boils down to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*pDbi96WHSA1powx-Ej8ndg.png" /></figure><p>The first term is the likelihood of observing x given z and the second term is KL divergence of p and q. So basically to make q similar to p, we can maximize the first term and/or minimize the second term. This process of approximating q to p is called variatonal inference.</p><h4>Reparameterization Trick</h4><p>Another problem we encounter is regarding back-propagation. As we know during back-propagation, all the elements in network should be differentiable. But the stage of random sampling is stochastic and hence not differentiable. To overcome this problem a new element called epsilon is introduced in the network. Thus the latent space distribution of z which is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*mes6JcMDUz1FfKhWbD-w0g.png" /></figure><p>is modified as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*KEAvhBnVJ6NcU6tVWrfOUQ.png" /></figure><p>given that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*Amqm0APz2w--IZeevaCdTA.png" /></figure><p>where there is element-wise product between sigma and epsilon. This epsilon takes care of the stochastic part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/0*xxlUm-N4vfaC_VZR" /><figcaption>Reparameterization trick.</figcaption></figure><p>Thus the clever trick here is that the mean and standard deviation are the only elements that we want to train by calculating gradients and doing backpropagation. Epsilon has a fix distribution and do not need to be trained. This is called as reparameterization trick.</p><p>I hope this article well summarizes the concept behind Variational Autoencoders !!!! Feedback and suggestions are most welcomed !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60a73c8cb05a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster RCNN]]></title>
            <link>https://ashutoshmakone.medium.com/faster-rcnn-502e4a2e1ec6?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/502e4a2e1ec6</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[mask-rcnn]]></category>
            <category><![CDATA[faster-rcnn]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 15:51:21 GMT</pubDate>
            <atom:updated>2020-12-12T12:03:37.913Z</atom:updated>
            <content:encoded><![CDATA[<h4>Faster than fast</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WpFClyHqHRmfDmZG" /><figcaption>Photo by <a href="https://unsplash.com/@valerieblanchett?utm_source=medium&amp;utm_medium=referral">Valerie Blanchett</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>Fast R-CNN was introduced in April 2015. It was faster than R-CNN. But not fast enough and hence unsuitable for real time applications. Faster R-CNN was introduced by <a href="https://arxiv.org/pdf/1311.2524.pdf">Ross Girshick et al.</a> in the June of same year and its much faster that Fast R-CNN. The research paper can be found <a href="https://arxiv.org/pdf/1506.01497.pdf">here</a>.</p><h3>2. First Look at Faster R-CNN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*IZi_Jiv9l0cx4u2jji_4vw.png" /><figcaption><strong>Figure 1 :</strong> Faster R-CNN overview</figcaption></figure><p>First we will learn the high level working of Faster R-CNN using Figure 1. Try to see that most of the network works very much like Fast R-CNN( except RPN). Keep an eye on Figure 1 while reading following steps.</p><ol><li>The input image is first fed to Convolutional neural network which extracts features and generates a feature map.This feature map is Fed to region proposal network (RPN).</li><li>Anchors are generated for input image ( not shown on Figure 1). The anchors are like fixed size bounding boxes which will try to cover objects of different size and aspect ratio. These anchors span over the entire image to cover all the objects present in it. More details about anchor will be covered in next section.</li><li>In Faster R-CNN, RPN is used to generate object proposals, also called region proposals. RPN is also a CNN. The output of initial layers of this CNN goes into two branches. The first branch is for objectness classification which gives two probabilities of whether any object is present in a given anchor or not. Second branch is bounding box regressor which adjusts the boundaries of bounding boxes to fit the objects inside it(if any object is at all present inside them.)</li><li>These object proposals generated by RPN are then projected onto the feature map, generated in step 1.</li><li>RoI pooling is used to extract feature vectors corresponding to each object proposal. This process is explained in full details in my previous story on Fast R-CNN <a href="https://ashutoshmakone.medium.com/fast-r-cnn-42c8b345d788">here</a>.</li><li>These feature vectors are given as an input to a fully connected layer, whose output then goes into two branches. One branch for multiclass classification and other for bounding box regression. Remember that this bounding box regressor is different from bounding box regressor in RPN.</li><li>The multiclass classification branch uses a number of convolution layers and a softmax layer to classify corresponding object proposal into any of the object categories (classes). Background of the image is also considered as one of categories.</li><li>The bounding box regressor branch further refines the boundaries of bounding boxes to fit the boundaries of object present inside them.</li></ol><p>In a nutshell, for generating object proposals, Fast R-CNN uses selective search , whereas Faster R-CNN uses RPN. Faster R-CNN can be thought of combination of RPN and Fast R-CNN detector.</p><p>This completes our high level understanding of Faster R-CNN. If you want to go deeper, follow along……</p><h3>3. More insights into Faster R-CNN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*B-Bk-UIYkSrDE6IOl9Ylpg.png" /><figcaption><strong>Figure 2 : </strong>Unified network of Faster RCNN</figcaption></figure><p>A broad overview of Faster R-CNN is given by Figure 2.</p><blockquote>To put everything in context …..</blockquote><blockquote>Faster R-CNN generates a lot of anchor boxes of different size and aspect ratio, all over the image to accommodate all the objects present in an image. First a pretrained CNN like ResNet-101 or VGG16 can be used to generate a feature map for input image. RPN checks which of the anchors really contain objects and modifies their boundaries to fit the object inside them. Now an object may be present in more than one overlapping anchors. Non-maximum suppression (NMS) is used to keep only the best fitting anchor and reject the rest. These selected anchors (object proposals) are used to extract the fix length feature vectors from feature map using RoI pooling. These feature vectors are further used for multiclass classification to get the object present in the corresponding object proposal and for bounding box regressor to refine the boundaries of bounding box to precisely fit the object.</blockquote><blockquote>I hope this makes sense.</blockquote><blockquote>A broad overview of Faster R-CNN is given by Figure 2.</blockquote><p><strong>3.1 Anchors and Region Proposal Network</strong></p><p>OK. So I will try to oversimplify it………</p><p>The most basic task CNNs can effectively perform is to classify images. All algorithms in the family of R-CNN, <em>are</em> very clever ways of extending this capacity of CNNs to detect objects in an image.</p><p>So the most logical thing to do is to do it in following two steps.</p><ol><li>Extract the regions in an image that contain an object.</li><li>Then use CNN on each of those regions to identify the object inside them, just like we do for basic classification task.</li></ol><p>But how can we get the regions (anchors in our case) in an image that contain objects? We can try all possible combination of anchor height and width. But that would leave us with insane number of anchors for one image. We can draw infinite number of rectangle on an image withing repetition, can’t we? ( by the way, before R-CNN, some methods actually used to do something similar to that! can you believe? I don&#39;t want to confuse you by giving more details. But it was called exhaustive search. It was very very slow. And hence selective search was proposed? But selective search was also not fast enough and so …… stop!)</p><p>We can draw infinite number of rectangle on an image without repetition, can’t we? Instead Faster R-CNN does it in a clever way…..</p><p>Consider an image of typical size 600 x 1000 pixels. We will select locations on this image with a distance (also called stride) of 16 pixels. Thus we get locations in 1000/16 = 62 columns and 600/16= 37 rows as shown in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*Mo7RTv1PVwcdM3YFXwz3Vw.png" /><figcaption><strong>Figure 3:</strong> Location to place anchor boxes on image of size 600 x 1000 with stride equal to 16</figcaption></figure><p>Figure 3 contains an image where we choose location in a grid of 62 columns and 37 rows. Thus we have 37 x 62 = 2294 location at each location, we will consider 9 anchors with three sizes and 3 aspect ratios.</p><p>As shown in Figure 4, the anchors have three scales with box areas of 128x128(shown in red), 256x256(shown in orange) and 512x512(shown in green). For every scale there are three anchors with three aspect ratios of 1:1, 1:2 and 2:1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*3PJCwHL-ncqnsnVdTy5hfA.png" /><figcaption><strong>Figure 4:</strong> Anchor boxes</figcaption></figure><p>In Figure 3we have 2294 locations and for every location we will consider 9 anchor boxes centered at the location as shown in Figure 4. Thus, in all, we will have 2294 x 9 = 20646 anchors.</p><p>Now a very commonsensical (it is a valid word according to <a href="https://dictionary.cambridge.org/dictionary/english/commonsensical">cambridge</a>) question to ask is what if there are objects in image which do not fit exactly in any of those 20646 anchor. And the answer is, firstly, the anchor sizes are chosen such that objects of different shapes and sizes would fit approximately in one of those anchor and secondly, we are going to use bounding box regressor twice in our network to refine those anchor boxes as per the object boundaries.</p><p>As you can very easily imagine, that for locations near the border on an image, the corresponding bounding boxes will go out of the image. They are called cross-boundary anchors. So when we remove the cross-boundary anchors from all the 20646 anchors, we will be left with around 6000 anchors.</p><p>Note that these cross-boundary anchors are removing only for training. During testing , the cross-boundary anchors are clipped to the image boundary.</p><p>The objectness classification branch of RPN, then calculates the objectness score of each anchor, which indicates its possibility of containing an object. The bounding box regressor refines the anchor to fit to the object.</p><p><strong>3.2 Labeling</strong></p><p>Positive label is assigned to two kinds of anchors</p><ol><li>The anchors with highest IoU with ground truth box.</li><li>The anchors with IoU greater than 0.7 with ground truth box.</li></ol><p>We assign a negative label to a non-positive anchor if its IoU ratio is lower than 0.3 for all ground-truth boxes.</p><p>Rest of the proposals do not contribute to training.</p><p><strong>3.3 Non-maximum supression (NMS)</strong></p><p>Non-maximum suppression is a technique used to reduce the number of candidate boxes by eliminating boxes that overlap by an amount larger than a threshold.</p><p>Some of the anchors try to enclose the same object and have high overlap with each other. NMS considers IoU threshold (typically 0.7) and all the overlapping proposals with IoU less than the threshold are rejected, which leaves us with around 2000 region proposals to be processed by Fast RCNN detector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxTMK8K7ViccQGLQNEnyoQ.png" /><figcaption><strong>Figure 5:</strong> Region proposals given by RPN</figcaption></figure><p>Figure 5 shows region proposals produces by region proposal network. Objectness score of each region proposal is also shown.</p><p>( Figure 5 is taken from original research paper. Though it labels every region with name of object, I don&#39;t think names are available at this stage in the network. Please let me know your views in comment section)</p><p><strong>3.4 RoI Pooling</strong></p><p>RoI pooling works just like the way it used to work in Fast R-CNN.</p><p>The input images are resized such that the shorter side becomes 600 pixels. Fast R-CNN can accept input image with any size such that the longer side should not exceed 1000 pixels when the shorter side is resized to 600 pixels.</p><p>The convolutional layers do not have any problem with this variable image size. But the output of convolutional layers is of different size for different sizes of input images. And next fully connected layers do not accept input of variable size. So it is necessary to bring the output of convolutional layers to a fix size before feeding it to fully connected layers. This is done by RoI Pooling.</p><p>Suppose we want to resize the output of convolutional layers corresponding to region proposal to H x W. Then we divide the corresponding feature map into a grid of size H x W containing bins of size h/H and W/w where h and w are height and width of feature map corresponding to region proposal. Then max pooling is applied on all bins to get a resized feature map of H x W.</p><p><strong>3.5 Sharing Features with RPN and Fast R-CNN</strong></p><p>In Faster R-CNN training is single stage using multi-task loss. The anchors are labeled as discussed in section 3.2. The loss function is combination of classification loss and bounding box regression loss.</p><p>Faster R-CNN has two networks : RPN and Fast R-CNN. If we train them independently, then their layers will be modified in different ways. But we want Faster R-CNN to be a unified network with shared convolutional layers.</p><p>The research paper uses the approach of alternative training for all its experiments. In alternative training RPN is trained first which generates region proposals. Then Fast R-CNN is trained on those proposals. The network thus tuned by Fast R-CNN is then used to initialize RPN. And so on …. This solves our purpose of unified network with shared features.</p><p><strong>3.6 Final Multi-class Classification</strong></p><p>RoI feature vectors obtained from RoI pooling are then passed through a sequence of fully connected layers. And the output goes into two sibling output layers/branches : one branch of Multi-class Classification<strong> </strong>and the other branch containing bounding box regressor as can be seen in Figure 1.</p><p>The Multi-class Classification branch predicts probabilities of the corresponding RoI belonging to any of the object classes or to the ‘background’ class. In short, this branch performs Multi-class classification and it finds out the object that is present in corresponding region of interest.</p><p>The bounding box regressor branch refines the boundaries of bounding boxes to fit the boundaries of object present inside them.</p><h3><strong>4. Results</strong></h3><ol><li>The computation of proposals with Faster R-CNN is nearly cost free as compared to Fast R-CNN.</li><li>Faster R-CNN is a unified object detection algorithm with near real time frame rates.</li><li>With VGG16 as backbone network, it takes just 198 ms for object detection, including all steps.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=502e4a2e1ec6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast R-CNN]]></title>
            <link>https://ashutoshmakone.medium.com/fast-r-cnn-42c8b345d788?source=rss-fdec78b582dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c8b345d788</guid>
            <category><![CDATA[semantic-segmentation]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[fast-rcnn]]></category>
            <dc:creator><![CDATA[Ashutosh Makone]]></dc:creator>
            <pubDate>Tue, 08 Dec 2020 18:08:32 GMT</pubDate>
            <atom:updated>2020-12-09T07:15:20.266Z</atom:updated>
            <content:encoded><![CDATA[<h4>Improved R-CNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cOrgKBPbMVUjHAj_" /><figcaption>Photo by <a href="https://unsplash.com/@gnidertam?utm_source=medium&amp;utm_medium=referral">Gnider Tam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>1. Introduction</strong></h3><p>R-CNN is slow. Detecting with R-CNN with VGG16 backbone takes 47 seconds for one image at test time. That makes it unsuitable for low latency applications. So in April 2015 Ross Girshick who was also one of the authors of R-CNN, single handedly proposed a better algorithm, called Fast Algorithm. The research paper can be found <a href="https://arxiv.org/pdf/1504.08083.pdf">here</a>. In this write up, we will get down to the nitty gritty of Fast R-CNN. But before that it is highly recommended to read my previous medium story on R-CNN <a href="https://ashutoshmakone.medium.com/">here</a>, as I will be using a lot of terms and concepts from R-CNN while assuming that you know them well.</p><p>CNNs are inherently capable of classifying images. It is helpful to look at R-CNN and Fast R-CNN as methods to extend this inherent capacity of CNNs for detecting objects in an image. Detecting objects means finding out the class of objects along with their actual locations in an image. So it involves classification and localization as well.</p><p>Suppose we have three classes of objects. Mountain, sea and building. CNNs can very easily tell us, if an image contains a mountain or not, or if an image contains a building or not. But if we have a sea and a mountain and a building , all in the same image then CNNs can not directly be used for all three objects. In such a case, we can extract regions from an image, that may contain an object and then apply CNN on those regions separately to check if any of those regions contain a sea or a mountain or building. And in a nutshell, that’s what R-CNN does. Those extracted regions ( generally obtained using selective search) which were called region proposals in R-CNN are called object proposals or regions of interest (RoI) in Fast R-CNN. And the entire process of object detection is done more intelligently in Fast R-CNN to give better performance in terms of speed and memory requirement.</p><h3><strong>2. First Look at Fast R-CNN</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtgqLtJFFoxXR4gP4f31PA.jpeg" /><figcaption><strong>Figure 1 :</strong> Fast R-CNN overview</figcaption></figure><p>Fast R-CNN first computes the feature map for entire input image and then from that feature map, extracts feature vectors corresponding to each RoI using RoI pooling. These feature vectors are then used for classification and localization. Keep an eye on Figure 1 while reading following steps</p><ol><li>The input image along with a set of object proposals(also called region of interests) are given as a input to the convolutional neural network (CNN).</li><li>The CNN, which contains several convolutional and max pooling layers produce a feature map for input image as shown in Figure 1. This way we get one feature map for entire input image and its much smaller in size than the input image because of stride.</li><li>Next stage is RoI pooling layer. It is different from regular max pooling layer and its job is to extract fixed length feature vectors from feature map. Thus we get feature vectors corresponding to every region of interest. They can further be used for classification and localization.</li><li>These RoI feature vectors then pass through a sequence of fully connected layers. And the output goes into two sibling output layers/branches : one branch containing softmax layer and the other branch containing bounding box regressor as can be seen in Figure 1.</li><li>The Softmax branch predicts probabilities of the corresponding RoI belonging to any of the object classes or to the ‘background’ class. In short, this branch performs classification and it finds out the object that is present in corresponding region of interest.</li><li>The bounding box regressor branch predicts the refined location of object in term of r,c,,h and w; Where (r,c) specifies the coordinates of top left corner of the bounding box for corresponding object and (h,w) are height and width of the bounding box. This stage is necessary because the RoIs given by selective search are not perfect and need refinement.</li></ol><p>This completes our high level understanding of Fast R-CNN. If you want to go deeper, follow along……</p><h3><strong>3. More insights into Fast R-CNN</strong></h3><blockquote>According to <a href="https://en.wikipedia.org/wiki/Region_Based_Convolutional_Neural_Networks">Wikipedia</a> ……</blockquote><blockquote>While the original R-CNN independently computed the neural network features on each of as many as two thousand regions of interest, Fast R-CNN runs the neural network once on the whole image. At the end of the network is a novel method called ROIPooling, which slices out each ROI from the network’s output tensor, reshapes it, and classifies it. As in the original R-CNN, the Fast R-CNN uses Selective Search to generate its region proposals.</blockquote><blockquote>This is exactly what we learned in previous section.</blockquote><p><strong>3.1 Initializing Fast R-CNN from pretrained network</strong></p><p>When a pretrained network like VGG16 is used to initialize Fast R-CNN , then VGG16 is modified in following three ways. Again keep an eye on Figure 1 while reading following points</p><ol><li>The last max pooling layer is replaced by an RoI pooling layer.</li><li>The last fully connected layer and softmax layer are replace with sibling branches of softmax and bounding box regressor.</li><li>The network is modified to take two inputs: images and RoIs.</li></ol><p>Few of VGG16&#39;s last layers are fine tuned for transfer learning.</p><p><strong>3.2 How does RoI pooling works?</strong></p><p>For Fast R-CNN, the input images are resized such that the shorter side becomes 600 pixels. Fast R-CNN can accept input image with any size such that the longer side should not exceed 1000 pixels when the shorter side is resized to 600 pixels.</p><p>The convolutional layers do not have any problem with this variable image size. But the output of convolutional layers is of different size for different sizes of input images. And next fully connected layers do not accept input of variable size. So it is necessary to bring the output of convolutional layers to a fix size before feeding it to fully connected layers. This is done by RoI Pooling.</p><p>Lets take an example…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*qqRq1H_4fLZ7APonSJf2jA.jpeg" /><figcaption><strong>Figure 2 : </strong>Feature map with variable RoI sizes example</figcaption></figure><p>Suppose we give an image and two object proposals as an input to CNN and CNN produces a feature map of size 21 x 16 as shown in Figure 2. There are two boxes(red and blue) in Figure 2. These two boxes correspond to two object proposals. These boxes are of different size and they are much smaller than their corresponding object proposals due to stride. The aim of RoI pooling is to resize them and bring them to a smaller and same size. In our example we will resize both of them to a fix size of 3 x 3. So here H=3 and W=3. How this is done is very interesting….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSth-1AFe6rD_38djyNQTw.jpeg" /><figcaption><strong>Figure 3 : </strong>RoI pooling for RED RoI</figcaption></figure><p>The first step is to divide the RED RoI into a grid having 3 x 3 = 9 bins. The RED RoI is of size 18 x 10 as shown in Figure 2. Because we want to resize it to H x W, we will create bins of height = 18/3=6 and width = 10/3=3. Please note that 10 is not multiplier of 3 and hence bins in last column of grid has more width. On these 9 bins we apply max pool (get one maximum number from each bin) and we get a 3 x 3 resized feature map as shown in the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-36tjzMLQ0zOEd1dDWSo2A.jpeg" /><figcaption><strong>Figure 4: </strong>RoI pooling for BLUE RoI</figcaption></figure><p>For BLUE RoI also, the first step is to divide it into a grid having 3 x 3 = 9 bins. The BLUE RoI is of size 16 x 13 as shown in Figure 2. Because we want to resize it to H x W, we will create bins of height = 16/3=5 and width = 10/3=3. Please note that 16 and 13 are not multiplier of 3 and hence bins in last row and last column of grid has more height and width respectively. On these 9 bins we apply max pool (get one maximum number from each bin) and we get a 3 x 3 resized feature map as shown in the right.</p><p>This is how, in spite of having RoI of variable size, we are always capable of resizing them to same size. Here we have resized them to 3 x 3 but in actual research paper while using VGG16 as CNN the author has resized it to 7 x 7 using RoI pooling. Thus H=W=7. The resized RoI are then flattened and fed to next fully connected layers, whose output goes to two sibling layers as shown in Figure 1.</p><p><strong>3.3 Are more proposals always better?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Suxh9ZxW1WsSMhrDDUtytA.jpeg" /><figcaption><strong>Figure 5 : </strong>Performance for various schemes.</figcaption></figure><p>The author of Fast R-CNN carried out an experiment where the vary the number of object proposals and check the performance of object detection. The performance for object proposals generated using selective search is shown by solid blue line in Figure 5 and it is observed that the mAP actually goes down when the number of object proposals increase beyond a certain range.</p><p><strong>3.4 Softmax vs. SVM</strong></p><p>If you remember from my previous story on R-CNN, R-CNN uses number of class specific linear SVMs for classification. Why Fast RCNN uses softmax?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxEvjW1MX3PksG2YGdCvag.jpeg" /><figcaption><strong>Figure 6 :</strong> mAP values for Softmax vs SVMs</figcaption></figure><p>Experiments were carried out using networks of small, medium and large size. They are referred as S, M and L respectively. As shown in Figure 6 R-CNN was using SMVs only. But Fast R-CNN when tried with SVMs and softmax, performed slightly better with softmax.</p><p><strong>3.5 Comparing R-CNN and Fast R-CNN architectures</strong></p><ul><li>For R-CNN, training is a multistage pipeline. It first trains ConvNets followed by SVMs and then followed by bounding box regressor. In Fast R-CNN training is single stage using multi-task loss. Hence it is faster.</li><li>In R-CNN all object proposals are separately feed to CNN to get the fixed length feature vectors. Fast R-CNN takes entire image as input, generates its feature map using CNN in one pass and then feature vectors corresponding to each region proposal are extracted from feature map using RoI pooling. Hence it is faster. This is called sharing computation or sharing features.</li><li>The features extracted from CNN in R-CNN require hundreds of gigabytes of storage. Fast R-CNN do not need to store any features.</li></ul><p><strong>3.6 Comparing R-CNN and Fast R-CNN results</strong></p><ul><li>Fast R-CNN trains very deep VGG16 networks 9 times faster than R-CNN.</li><li>R-CNN with VGG16 takes 47 seconds to detect objects in one test image while Fast R-CNN takes only 0.3 seconds(Excluding object proposal time).</li><li>Fast R-CNN achieves an mAP of 66% on PASCAL VOC 2102 dataset. mAP of R-CNN for same dataset is 62%.</li></ul><p><strong>3.7 Drawbacks of Fast R-CNN</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*ukJk4pdphyeOM3ZbueSUfQ.jpeg" /><figcaption><strong>Figure 7: </strong>Test time comparisons</figcaption></figure><p>The speed of Fast R-CNN is limited by the time taken by selective search to generate object proposals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*F9MYy4KXkAyBRSp6pX44pQ.png" /></figure><p>As can be seen from Figure 7, there is a huge difference in test times of Fast R-CNN with and without considering the time taken by selective search to generate region proposals at test time.</p><p>considering the time taken by selective search the test time is 2.3 seconds. Though this is a great improvement over R-CNN, but still Fast R-CNN is not suitable for real time applications</p><p>This is the perfect time to start talking about Faster R-CNN , a state of the art algorithm for object detection and semantic segmentation. As the name suggests its faster than the fast R-CNN.</p><p>Stay tuned …..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42c8b345d788" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>