Type at least 2 letters. Enter opens the first result, Esc closes.

    learn.mohebi.ai

    Reinforcement learning in a gridworld

    Build a small world with walls, goals and traps. Watch value iteration and policy iteration solve it with the Bellman equations, then watch an agent learn the same kind of task by trial and error with Q-learning and SARSA.

    In reinforcement learning (RL) an agent acts in an environment. At each time step it is in a state ss, takes an action aa, receives a reward rr and moves to a next state s′s'. A policy π\pi is a rule that chooses the action in each state. The goal is a policy that collects as much reward as possible over time.

    This page has two simulations of the same small world:

    Play with both figures first, then do the experiments in section 3. Section 4 explains the math.

    1. Planning with a known model #

    The value V(s)V(s) of a cell is the expected discounted sum of all future rewards when the agent starts in that cell. The action value Q(s,a)Q(s,a) is the same, but the first action is fixed to aa. In the figure the colour of a cell is its value: blue for positive values, magenta for negative ones, stronger for larger size. The orange arrows are the greedy policy: in each cell, the action with the largest Q(s,a)Q(s,a). A small dot means that all four actions are equally good.

    Interactive figure: loading…

    Press Reset, then Step a few times, and watch the values spread out from the goals, one cell further with each sweep. Then press Run or Solve. Keep the edit tool on Inspect and click a cell to see its Bellman backup: the four action values and the sum behind the best one. Switch to Policy iteration and press Step: it alternates an exact evaluation of the current arrows with an improvement step, and the dashed violet cells are the ones the next improvement changes. Change the world with the edit tools and the worlds under the figure; every change is solved at once.

    2. Learning from experience #

    Now the agent does not know the slip probability or where the rewards are. It only sees what happens when it acts. It keeps a table of action values Q(s,a)Q(s,a), one number for each cell and action. The figure draws them as four triangles in each cell. After every step the agent moves one number a little toward a better estimate, the TD target (TD means temporal difference). To find out what works, it sometimes acts at random: with probability ε\varepsilon it picks a random action, otherwise the greedy one. This rule is called ε-greedy.

    Interactive figure: loading…

    Press Play to watch the orange agent, or press +100 episodes to learn fast. Each triangle is coloured by Q(s,a)Q(s,a) for the action that points to it, and the orange arrow is the greedy action. Yellow steps in the trail were random moves (exploration). The chart shows the return of every episode (dots), its running mean (line) and, dashed violet, V∗(s0)V^*(s_0): the best expected return from the start cell s0s_0, computed by value iteration with the true model. Use Inspect to compare the learned values of a cell with the true Q∗Q^*.

    3. Try this #

    1. The policy settles before the values. In the planning figure (world Two exits), press Reset, then press Step many times. Question: what stops changing first, the arrows or the numbers? What to see: the arrows do not change after sweep 11, but value iteration needs 52 sweeps until the largest change is below 10−610^{-6}. A greedy policy is often optimal long before the values are exact. Policy iteration (switch the algorithm) needs only 3 evaluations for the same world.
    2. The discount changes the destination. Set the slip probability to 0. With γ=0.9\gamma = 0.9 the arrows from S go along the bottom row to +10. Now move γ\gamma down slowly. Question: at which γ\gamma does the agent prefer the +1 exit? Hint: +1 is 3 moves from S and +10 is 5 moves from S. What to see: the arrows switch between γ=0.32\gamma = 0.32 and γ=0.31\gamma = 0.31. The reward of the third move is discounted by γ2\gamma^2 and the reward of the fifth by γ4\gamma^4, and γ2⋅1=γ4⋅10\gamma^2 \cdot 1 = \gamma^4 \cdot 10 gives γ=0.1≈0.316\gamma = \sqrt{0.1} \approx 0.316.
    3. Slip makes the agent careful. Go back to Two exits (slip 0.2, γ=0.9\gamma = 0.9). Question: which way does the agent go from S? What to see: it takes the long way over the top (9 moves) to +10. On the bottom row every move has a 10% chance to slip down into a trap, so the short way is risky. Set the slip to 0 and the short way becomes best. Then open the world Bridge: with slip 0 the agent crosses the bridge to +10, but with slip 0.02 it already prefers the +1 exit next to the start.
    4. The step reward. In Two exits (slip 0.2, γ=0.9\gamma = 0.9) set the step reward cc to −1. Question: what happens to the long safe way? What to see: every move now costs 1, so the long way is too expensive and the agent takes the short way along the traps (5 moves). Now set c=+0.5c = +0.5 and γ=0.99\gamma = 0.99. The agent avoids both exits: from S it moves up, away from the traps, and in the top row all actions are equally good (dots). Staying in the world forever is worth up to 0.5/(1−0.99)=500.5 / (1 - 0.99) = 50, more than any exit.
    5. Exploration against exploitation. In the learning figure choose Two exits, set the slip to 0 and ε=0\varepsilon = 0. Press +100 episodes three times. Question: does the agent find the +10 exit? What to see: in most runs it finds +1 first and then goes there every time. With ε=0\varepsilon = 0 it never tries anything new, so the triangles near +10 stay pale. Press Reset, set ε=0.5\varepsilon = 0.5 and press +100 episodes ten times: now, in most runs, the arrows from S point toward +10. The agent must explore (try actions that look worse) to find better rewards, and exploit (use what it knows) to collect them.
    6. Q-learning or SARSA on the cliff. In the world Cliff (ε=0.1\varepsilon = 0.1) press +100 episodes five times with Q-learning and look at the arrows and the chart. Then choose SARSA and do the same. Question: which algorithm learns the path right along the cliff, and which one collects more reward while it learns? What to see: Q-learning learns the shortest path, next to the cliff, but its random moves sometimes throw it into the cliff, so many of its returns are far below the dashed line and its mean return is low. SARSA learns a path one or two rows away from the cliff and has a higher mean return. Finally choose Q-learning again, train it, set ε=0\varepsilon = 0 and press +1 episode: without random moves its return equals V∗(s0)≈−2.64V^*(s_0) \approx -2.64.

    4. The math behind the figures #

    Returns and values #

    The return is the discounted sum of the rewards from time tt on:

    Gt=rt+γrt+1+γ2rt+2+⋯=∑k≥0γkrt+k=rt+γGt+1.G_t = r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} + \dots = \sum_{k \ge 0} \gamma^k r_{t+k} = r_t + \gamma G_{t+1}.

    Here rtr_t is the reward received after the action ata_t (Sutton and Barto write Rt+1R_{t+1} for the same reward). The values of a policy π\pi are expected returns:

    Vπ(s)=Eπ[ Gt∣st=s ],Qπ(s,a)=Eπ[ Gt∣st=s, at=a ].V^\pi(s) = \mathbb E_\pi[\,G_t \mid s_t = s\,], \qquad Q^\pi(s,a) = \mathbb E_\pi[\,G_t \mid s_t = s,\ a_t = a\,].

    The expectation is over the random slips and over the policy's own choices. In this world the reward of one move is r(s,a,s′)=c+R(s′)r(s,a,s') = c + R(s'), where R(s′)R(s') is the reward of the cell the agent enters (0 for a free cell), and P(s′∣s,a)P(s' \mid s,a) is 1−p1-p for the chosen direction and p/2p/2 for each sideways one.

    The Bellman equations #

    Use Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1} inside the expectation. The value of a state is the expected reward of one step plus the discounted value of the state where the agent lands. This is the Bellman expectation equation:

    Vπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a) [ r(s,a,s′)+γVπ(s′) ].V^\pi(s) = \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s,a)\,\big[\,r(s,a,s') + \gamma V^\pi(s')\,\big].

    The best possible values V∗V^* and Q∗Q^* satisfy the Bellman optimality equations, where the average over the policy becomes a maximum over actions:

    V∗(s)=max⁡a∑s′P(s′∣s,a) [ r(s,a,s′)+γV∗(s′) ],Q∗(s,a)=∑s′P(s′∣s,a) [ r(s,a,s′)+γmax⁡a′Q∗(s′,a′) ].V^*(s) = \max_a \sum_{s'} P(s' \mid s,a)\,\big[\,r(s,a,s') + \gamma V^*(s')\,\big], \qquad Q^*(s,a) = \sum_{s'} P(s' \mid s,a)\,\big[\,r(s,a,s') + \gamma \max_{a'} Q^*(s',a')\,\big].

    The greedy policy with respect to Q∗Q^*, π∗(s)=arg⁡max⁡aQ∗(s,a)\pi^*(s) = \arg\max_a Q^*(s,a), is optimal. The inspector of the first figure shows exactly one such backup: the sum over the (at most three) cells where the agent can land.

    Quick check

    Two exits without slip and with c=0c = 0: the +1 exit is 3 moves from S and the +10 exit is 5 moves from S. Which exit does the optimal policy choose for γ=0.5\gamma = 0.5?

    Value iteration #

    Value iteration turns the optimality equation into an update. Start with V0=0V_0 = 0 and apply to every cell at once (one sweep):

    Vk+1(s)=max⁡a∑s′P(s′∣s,a) [ r(s,a,s′)+γVk(s′) ],or shortVk+1=TVk.V_{k+1}(s) = \max_a \sum_{s'} P(s' \mid s,a)\,\big[\,r(s,a,s') + \gamma V_k(s')\,\big], \quad \text{or short} \quad V_{k+1} = T V_k.

    The Bellman optimality operator TT is a contraction in the max norm: for any two value tables, ∥TV−TU∥∞≤γ∥V−U∥∞\|TV - TU\|_\infty \le \gamma \|V - U\|_\infty. So every sweep shrinks the error at least by the factor γ\gamma: ∥Vk−V∗∥∞≤γk∥V0−V∗∥∞\|V_k - V^*\|_\infty \le \gamma^k \|V_0 - V^*\|_\infty. It also gives a stopping rule. If the largest change of a sweep is δ=∥Vk+1−Vk∥∞\delta = \|V_{k+1} - V_k\|_\infty, then

    ∥Vk+1−V∗∥∞≤γ1−γ δ.\|V_{k+1} - V^*\|_\infty \le \frac{\gamma}{1 - \gamma}\,\delta.

    This is the readout "distance to V* at most". In the chart, the largest change of each sweep stays below the dashed line δ1γk−1\delta_1 \gamma^{k-1}, where δ1\delta_1 is the change of the first sweep.

    Quick check

    Value iteration with γ=0.9\gamma = 0.9. About how many sweeps are needed to make the error bound γk∥V0−V∗∥∞\gamma^k \|V_0 - V^*\|_\infty one million times smaller?

    Policy iteration #

    Policy iteration starts from any policy and repeats two steps:

    1. Policy evaluation. For a fixed deterministic policy the Bellman expectation equation is linear: Vπ=rπ+γPπVπV^\pi = r_\pi + \gamma P_\pi V^\pi, where PπP_\pi is the matrix of transition probabilities and rπr_\pi the vector of expected rewards when the agent follows π\pi. So Vπ=(I−γPπ)−1rπV^\pi = (I - \gamma P_\pi)^{-1} r_\pi. The matrix I−γPπI - \gamma P_\pi is invertible for γ<1\gamma < 1 because every row of PπP_\pi sums to at most 1. The figure solves this system with Gaussian elimination.
    2. Policy improvement. Make the policy greedy: π′(s)=arg⁡max⁡aQπ(s,a)\pi'(s) = \arg\max_a Q^\pi(s,a). The policy improvement theorem says that then Vπ′(s)≥Vπ(s)V^{\pi'}(s) \ge V^\pi(s) in every state.

    There are only finitely many deterministic policies. Each improvement that changes an action makes the policy strictly better in at least one state, so no policy comes back and the loop stops. (This needs a tie rule: keep the old action if it is still among the best. The figure does this.) When no action changes, π\pi is greedy with respect to its own values, so VπV^\pi satisfies the Bellman optimality equation and π\pi is optimal. Policy iteration needs few iterations, but each one solves a linear system. Value iteration does cheap sweeps, but many of them.

    Q-learning and SARSA #

    Without a model the agent cannot compute the sum over s′s'. It uses the one next state it really sees instead. After the step (s,a,r,s′)(s, a, r, s') it computes a TD target and moves Q(s,a)Q(s,a) toward it with the learning rate α\alpha:

    Q-learning:Q(s,a)←Q(s,a)+α [ r+γmax⁡a′Q(s′,a′)−Q(s,a) ],SARSA:Q(s,a)←Q(s,a)+α [ r+γ Q(s′,a′)−Q(s,a) ].\begin{aligned} \text{Q-learning:}\quad & Q(s,a) \leftarrow Q(s,a) + \alpha\,\big[\,r + \gamma \max_{a'} Q(s',a') - Q(s,a)\,\big],\\ \text{SARSA:}\quad & Q(s,a) \leftarrow Q(s,a) + \alpha\,\big[\,r + \gamma\, Q(s',a') - Q(s,a)\,\big]. \end{aligned}

    The bracket is the TD error δ\delta. If s′s' is terminal, the target is only rr. On average over s′s', the Q-learning target is the right-hand side of the optimality equation for Q∗Q^*, with the current QQ in place of Q∗Q^*. So Q-learning is a sampled version of value iteration on action values.

    Quick check

    In the world Cliff with ε=0.1\varepsilon = 0.1, which statement is correct?

    Exploration and exploitation #

    To exploit means to take the action that looks best now. To explore means to try another action to learn more about it. Pure exploitation (ε=0\varepsilon = 0) can lock the agent onto the first reward it finds (experiment 5). Too much exploration wastes reward on random moves (experiment 6). ε-greedy is the simplest compromise. Other methods, such as optimistic initial values or upper confidence bounds (UCB), explore in a more directed way.

    Why the discount changes the policy #

    A reward that comes kk steps in the future is multiplied by γk\gamma^k. A small γ\gamma makes the agent short-sighted; a γ\gamma near 1 makes it patient. A rough measure is the effective horizon 1/(1−γ)1/(1-\gamma): about 10 steps for γ=0.9\gamma = 0.9 and 100 steps for γ=0.99\gamma = 0.99. The discount also interacts with the other parts of the task:

    The discount is part of the problem definition. Changing γ\gamma changes which policy is optimal, not only how fast the algorithms converge.