<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/reinforcement-learning-q-learning-with-the-hopping-robot/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://qualityandinnovation.com/2017/12/24/reinforcement-learning-q-learning-with-the-hopping-robot/"> R – Quality and Innovation</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><strong>Overview:</strong> Reinforcement learning uses “reward” signals to determine how to navigate through a system in the most valuable way. (I’m particularly interested in the variant of reinforcement learning called “Q-Learning” because the goal is to create a “Quality Matrix” that can help you make the best sequence of decisions!) I found a toy robot navigation problem on the web that was solved using custom R code for reinforcement learning, and I wanted to reproduce the solution in different ways than the original author did. This post describes different ways that I solved the problem described at <a rel="nofollow" href="http://bayesianthink.blogspot.com/2014/05/hopping-robots-and-reinforcement.html" target="_blank">http://bayesianthink.blogspot.com/2014/05/hopping-robots-and-reinforcement.html</a></p>
<p><strong>The Problem:</strong> Our <em>agent</em>, the robot, is placed at random on a board of wood. There’s a hole at s1, a sticky patch at s4, and the robot is trying to make appropriate decisions to navigate to s7 (the target). The image comes from the blog post linked above.</p>
<p><img data-orig-file="https://qualityandinnovation.files.wordpress.com/2017/12/hopping-robot.png?w=456" data-orig-size="557,458" data-medium-file="https://qualityandinnovation.files.wordpress.com/2017/12/hopping-robot.png?w=456?w=300" data-attachment-id="3464" data-image-meta="{" data-image-description="" src="https://qualityandinnovation.files.wordpress.com/2017/12/hopping-robot.png?w=456" data-permalink="https://qualityandinnovation.com/2017/12/24/reinforcement-learning-q-learning-with-the-hopping-robot/hopping-robot/" data-large-file="https://qualityandinnovation.files.wordpress.com/2017/12/hopping-robot.png?w=456?w=557" alt="" data-image-title="hopping-robot" sizes="(max-width: 557px) 100vw, 557px" data-comments-opened="1" class="wp-image-3464" data-recalc-dims="1"></p>
<p>To solve a problem like this, you can use MODEL-BASED approaches if you know how likely it is that the robot will move from one state to another (that is, the <em>transition probabilities</em> for each action) or MODEL-FREE approaches (you don’t know how likely it is that the robot will move from state to state, but you <em>can </em>figure out a reward structure).</p>
<ul>
<li><strong>Markov Decision Process (MDP)</strong> – If you know the states, actions, rewards, and transition probabilities (which are probably different for each action), you can determine the optimal policy or “path” through the system, given different starting states. (If transition probabilities have nothing to do with decisions that an agent makes, your MDP reduces to a <strong>Markov Chain</strong>.)</li>
<li><strong>Reinforcement Learning (RL)</strong> – If you know the states, actions, and rewards (but not the transition probabilities), you can still take an unsupervised approach. Just randomly create lots of hops through your system, and use them to update a matrix that describes the average value of each hop within the context of the system.</li>
</ul>
<p>Solving a RL problem involves finding the optimal value functions (e.g. the Q matrix in Attempt 1) or the optimal policy (the State-Action matrix in Attempt 2). Although there are many techniques for reinforcement learning, we will use Q-learning because we don’t know the transition probabilities for each action. (If we did, we’d model it as a Markov Decision Process and use the MDPtoolbox package instead.) Q-Learning relies on traversing the system in many ways to update a matrix of average expected rewards from each state transition. This equation that it uses is from <a rel="nofollow" href="https://www.is.uni-freiburg.de/ressourcen/business-analytics/13_reinforcementlearning.pdf" target="_blank">https://www.is.uni-freiburg.de/ressourcen/business-analytics/13_reinforcementlearning.pdf</a>:</p>
<p><img data-orig-file="https://qualityandinnovation.files.wordpress.com/2017/12/qlearning-eqn-feuerriegel.jpg" data-orig-size="641,109" data-medium-file="https://qualityandinnovation.files.wordpress.com/2017/12/qlearning-eqn-feuerriegel.jpg?w=300" data-attachment-id="3465" data-image-meta="{" data-image-description="" src="https://qualityandinnovation.files.wordpress.com/2017/12/qlearning-eqn-feuerriegel.jpg?w=829&h=142&fit=456%2C456" data-permalink="https://qualityandinnovation.com/2017/12/24/reinforcement-learning-q-learning-with-the-hopping-robot/qlearning-eqn-feuerriegel/" data-large-file="https://qualityandinnovation.files.wordpress.com/2017/12/qlearning-eqn-feuerriegel.jpg?w=641" alt="" data-image-title="qlearning-eqn-feuerriegel" sizes="(max-width: 641px) 100vw, 641px" data-comments-opened="1" class="wp-image-3465" data-recalc-dims="1"></p>
<p>For this to work, <em>all states</em> have to be visited a sufficient number of times, and <em>all state-action pairs </em>have to be included in your experience sample. So keep this in mind when you’re trying to figure out how many iterations you need.</p>
<h2><strong>Attempt 1: Quick Q-Learning with qlearn.R</strong></h2>
<ul>
<li><strong>Input</strong>: A rewards matrix R. (That’s all you need! Your states are encoded in the matrix.)</li>
<li><strong>Output</strong>: A Q matrix from which you can extract optimal policies (or paths) to help you navigate the environment.</li>
<li><strong>Pros</strong>: Quick and <em>very easy.</em> <strong>Cons</strong>: Does not let you set epsilon (% of random actions), so all episodes are determined randomly and it may take longer to find a solution. Can take a long time to converge.</li>
</ul>
<p>Set up the rewards matrix so it is a square matrix with <em>all the states down the rows, starting with the first </em>and <em>all the states along the columns, starting with the first:</em></p>
<pre>
hopper.rewards &lt;- c(-10, 0.01, 0.01, -1, -1, -1, -1,
         -10, -1, 0.1, -3, -1, -1, -1,
         -1, 0.01, -1, -3, 0.01, -1, -1,
         -1, -1, 0.01, -1, 0.01, 0.01, -1,
         -1, -1, -1, -3, -1, 0.01, 100,
         -1, -1, -1, -1, 0.01, -1, 100,
         -1, -1, -1, -1, -1, 0.01, 100)

HOP &lt;- matrix(hopper.rewards, nrow=7, ncol=7, byrow=TRUE) 
> HOP
     [,1]  [,2]  [,3] [,4]  [,5]  [,6] [,7]
[1,]  -10  0.01  0.01   -1 -1.00 -1.00   -1
[2,]  -10 -1.00  0.10   -3 -1.00 -1.00   -1
[3,]   -1  0.01 -1.00   -3  0.01 -1.00   -1
[4,]   -1 -1.00  0.01   -1  0.01  0.01   -1
[5,]   -1 -1.00 -1.00   -3 -1.00  0.01  100
[6,]   -1 -1.00 -1.00   -1  0.01 -1.00  100
[7,]   -1 -1.00 -1.00   -1 -1.00  0.01  100
</pre>
<p>Here’s how you read this: the rows represent where you’ve come FROM, and the columns represent where you’re going TO. Each element 1 through 7 corresponds directly to S1 through S7 in the cartoon above. Each cell contains a reward (or penalty, if the value is negative) if we arrive in that state.</p>
<p>The S1 state is <em>bad</em> for the robot… there’s a hole in that piece of wood, so we’d really like to keep it away from that state. Location [1,1] on the matrix tells us what reward (or penalty) we’ll receive if we start at S1 and <em>stay</em> at S1: -10 (that’s bad). Similarly, location [2,1] on the matrix tells us that if we start at S2 and move left to S1, that’s also bad and we should receive a penalty of -10. The S4 state is also undesirable – there’s a sticky patch there, so we’d like to keep the robot away from it. Location [3,4] on the matrix represents the action of going from S3 to S4 by moving right, which will put us on the sticky patch</p>
<p>Now load the qlearn command into your R session:</p>
<pre>
qlearn &lt;- function(R, N, alpha, gamma, tgt.state) {
# Adapted from https://stackoverflow.com/questions/39353580/how-to-implement-q-learning-in-r
  Q &lt;- matrix(rep(0,length(R)), nrow=nrow(R))
  for (i in 1:N) {
    cs &lt;- sample(1:nrow(R), 1)
    while (1) {
      next.states &lt;- which(R[cs,] > -1)  # Get feasible actions for cur state
      if (length(next.states)==1)        # There may only be one possibility
        ns &lt;- next.states
      else
        ns &lt;- sample(next.states,1) # Or you may have to pick from a few if (ns > nrow(R)) { ns &lt;- cs }
      # NOW UPDATE THE Q-MATRIX
      Q[cs,ns] &lt;- Q[cs,ns] + alpha*(R[cs,ns] + gamma*max(Q[ns, which(R[ns,] > -1)]) - Q[cs,ns])
      if (ns == tgt.state) break
      cs &lt;- ns
    }
  }
  return(round(100*Q/max(Q)))
}
</pre>
<p>Run qlearn with the HOP rewards matrix, a learning rate of 0.1, a discount rate of 0.8, and a target state of S7 (the location to the far right of the wooden board). I did 10,000 episodes (where in each one, the robot dropped randomly onto the wooden board and has to get to S7):</p>
<pre>
r.hop &lt;- qlearn(HOP,10000,alpha=0.1,gamma=0.8,tgt.state=7) 
> r.hop
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    0   51   64    0    0    0    0
[2,]    0    0   64    0    0    0    0
[3,]    0   51    0    0   80    0    0
[4,]    0    0   64    0   80   80    0
[5,]    0    0    0    0    0   80  100
[6,]    0    0    0    0   80    0  100
[7,]    0    0    0    0    0   80  100
</pre>
<p>The Q-Matrix that is presented encodes the best-value solutions from each state (the “policy”). Here’s how you read it:</p>
<ul>
<li>If you’re at s1 (first row), <strong>hop</strong> to s3 (biggest value in first row), then hop to s5 (go to row 3 and find biggest value), then hop to s7 (go to row 5 and find biggest value)</li>
<li>If you’re at s2, go <strong>right</strong> to s3, then hop to s5, then hop to s7</li>
<li>If you’re at s3, <strong>hop</strong> to s5, then hop to s7</li>
<li>If you’re at s4, go <strong>right</strong> to s5 OR hop to s6, then go right to s7</li>
<li>If you’re at s5, <strong>hop</strong> to s7</li>
<li>If you’re at s6, go <strong>right</strong> to s7</li>
<li>If you’re at s7, <strong>stay there</strong> (when you’re in the target state, the value function will not be able to pick out a “best action” because the best action is to do nothing)</li>
</ul>
<p>Alternatively, the policy can be expressed as the best action from each of the 7 states: <span><strong>HOP, RIGHT, HOP, RIGHT, HOP, RIGHT, (STAY PUT)</strong></span></p>
<h2><strong>Attempt 2: Use ReinforcementLearning Package</strong></h2>
<p>I also used the ReinforcementLearning package by Nicholas Proellochs (6/19/2017) described in <a rel="nofollow" href="https://cran.r-project.org/web/packages/ReinforcementLearning/ReinforcementLearning.pdf" target="_blank">https://cran.r-project.org/web/packages/ReinforcementLearning/ReinforcementLearning.pdf</a>.</p>
<ul>
<li><strong>Input</strong>: 1) a definition of the environment, 2) a list of states, 3) a list of actions, and 4) control parameters <strong>alpha</strong> (the learning rate; usually 0.1), <strong>gamma</strong> (the discount rate which describes how important future rewards are; often 0.9 indicating that 90% of the next reward will be taken into account), and <strong>epsilon</strong> (the probability that you’ll try a random action; often 0.1)</li>
<li><strong>Output</strong>: A State-Action Value matrix, which attaches a number to how good it is to be in a particular state <em>and</em> take an action. You can use it to determine the highest value action from each state. (It contains the same information as the Q-matrix from Attempt 1, but you don’t have to infer the action from the destination it brings you to.)</li>
<li><strong>Pros</strong>: Relatively straightforward. Allows you to specify epsilon, which controls the proportion of <em>random actions</em> you’ll explore as you create episodes and explore your environment. <strong>Cons</strong>: Requires manual setup of all state transitions and associated rewards.</li>
</ul>
<p>First, I created an “environment” that describes 1) how the states will change when actions are taken, and 2) what rewards will be accrued when that happens. I assigned a reward of -1 to all actions that are not special, e.g. landing on S1, landing on S4, or landing on S7. To be perfectly consistent with Attempt 1, I could have used 0.01 instead of -1, but the results will be similar. The values you choose for rewards are sort of arbitrary, but you do need to make sure there’s a comparatively large positive reward at your target state and “negative rewards” for states you want to avoid or are physically impossible.</p>
<pre>
y.env &lt;- function(state,action) {
   next_state &lt;- state
   if (state == state(&quot;s1&quot;) &amp;&amp; action == &quot;right&quot;)  { next_state &lt;- state(&quot;s2&quot;) }
   if (state == state(&quot;s1&quot;) &amp;&amp; action == &quot;hop&quot;)    { next_state &lt;- state(&quot;s3&quot;) }

   if (state == state(&quot;s2&quot;) &amp;&amp; action == &quot;left&quot;)  {
	next_state &lt;- state(&quot;s1&quot;); reward &lt;- -10 }
   if (state == state(&quot;s2&quot;) &amp;&amp; action == &quot;right&quot;) { next_state &lt;- state(&quot;s3&quot;) }
   if (state == state(&quot;s2&quot;) &amp;&amp; action == &quot;hop&quot;)   {
	next_state &lt;- state(&quot;s4&quot;); reward &lt;- -3 }

   if (state == state(&quot;s3&quot;) &amp;&amp; action == &quot;left&quot;)  { next_state &lt;- state(&quot;s2&quot;) }
   if (state == state(&quot;s3&quot;) &amp;&amp; action == &quot;right&quot;) {
	next_state &lt;- state(&quot;s4&quot;); reward &lt;- -3 }
   if (state == state(&quot;s3&quot;) &amp;&amp; action == &quot;hop&quot;)   { next_state &lt;- state(&quot;s5&quot;) }

   if (state == state(&quot;s4&quot;) &amp;&amp; action == &quot;left&quot;)  { next_state &lt;- state(&quot;s3&quot;) }
   if (state == state(&quot;s4&quot;) &amp;&amp; action == &quot;right&quot;) { next_state &lt;- state(&quot;s5&quot;) }
   if (state == state(&quot;s4&quot;) &amp;&amp; action == &quot;hop&quot;)   { next_state &lt;- state(&quot;s6&quot;) }

   if (state == state(&quot;s5&quot;) &amp;&amp; action == &quot;left&quot;)  {
	next_state &lt;- state(&quot;s4&quot;); reward &lt;- -3 }
   if (state == state(&quot;s5&quot;) &amp;&amp; action == &quot;right&quot;) { next_state &lt;- state(&quot;s6&quot;) }
   if (state == state(&quot;s5&quot;) &amp;&amp; action == &quot;hop&quot;)   {
	next_state &lt;- state(&quot;s7&quot;); reward &lt;- 10 }

   if (state == state(&quot;s6&quot;) &amp;&amp; action == &quot;left&quot;)  { next_state &lt;- state(&quot;s5&quot;) }
   if (state == state(&quot;s6&quot;) &amp;&amp; action == &quot;right&quot;) {
	next_state &lt;- state(&quot;s7&quot;); reward &lt;- 10 }

   if (next_state == state(&quot;s7&quot;) &amp;&amp; state != state(&quot;s7&quot;)) {
        reward &lt;- 10
   } else {
	reward &lt;- -1
   }
   out &lt;- list(NextState = next_state, Reward = reward)
   return(out)
}
</pre>
<p>Next, I installed and loaded up the ReinforcementLearning package and ran the RL simulation:</p>
<pre>
install.packages(&quot;ReinforcementLearning&quot;)
library(ReinforcementLearning)
states &lt;- c(&quot;s1&quot;, &quot;s2&quot;, &quot;s3&quot;, &quot;s4&quot;, &quot;s5&quot;, &quot;s6&quot;, &quot;s7&quot;)
actions &lt;- c(&quot;left&quot;,&quot;right&quot;,&quot;hop&quot;)
data &lt;- sampleExperience(N=3000,env=my.env,states=states,actions=actions)
control &lt;- list(alpha = 0.1, gamma = 0.8, epsilon = 0.1)
model &lt;- ReinforcementLearning(data, s = &quot;State&quot;, a = &quot;Action&quot;, r = &quot;Reward&quot;, 
      s_new = &quot;NextState&quot;, control = control)
</pre>
<p>Now we can see the results:</p>
<pre>
> print(model)
State-Action function Q
         hop     right      left
s1  2.456741  1.022440  1.035193
s2  2.441032  2.452331  1.054154
s3  4.233166  2.469494  1.048073
s4  4.179853  4.221801  2.422842
s5  6.397159  4.175642  2.456108
s6  4.217752  6.410110  4.223972
s7 -4.602003 -4.593739 -4.591626

Policy
     s1      s2      s3      s4      s5      s6      s7
  &quot;hop&quot; &quot;right&quot;   &quot;hop&quot; &quot;right&quot;   &quot;hop&quot; &quot;right&quot;  &quot;left&quot; 

Reward (last iteration)
[1] 223
</pre>
<p>The recommended policy is: <span><strong>HOP, RIGHT, HOP, RIGHT, HOP, RIGHT, (STAY PUT)</strong></span></p>
<p>If you tried this example and it didn’t produce the same response, don’t worry! Model-free reinforcement learning is done by simulation, and when you used the sampleExperience function, you generated a different set of state transitions to learn from. You may need more samples, or to tweak your rewards structure, or both.)</p>
<p> <a rel="nofollow" href="https://feeds.wordpress.com/1.0/gocomments/qualityandinnovation.wordpress.com/3463/" target="_blank"><img border="0" alt="" src="https://feeds.wordpress.com/1.0/comments/qualityandinnovation.wordpress.com/3463/"></a> <img border="0" alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" data-recalc-dims="1"></p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://qualityandinnovation.com/2017/12/24/reinforcement-learning-q-learning-with-the-hopping-robot/"> R – Quality and Innovation</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/iSDwqegG-Gs" height="1"></a></div>