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 , takes an action , receives a reward and moves to a next state . A policy 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:
- Planning. The agent knows the rules of the world (the model). Value iteration and policy iteration compute the best policy exactly, one step at a time.
- Learning. The agent does not know the rules. It walks through the world, tries actions and learns from the rewards it receives, with Q-learning or SARSA.
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 of a cell is the expected discounted sum of all future rewards when the agent starts in that cell. The action value is the same, but the first action is fixed to . 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 . A small dot means that all four actions are equally good.
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 , 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 it picks a random action, otherwise the greedy one. This rule is called ε-greedy.
Press Play to watch the orange agent, or press +100 episodes to learn fast. Each triangle is coloured by 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, : the best expected return from the start cell , computed by value iteration with the true model. Use Inspect to compare the learned values of a cell with the true .
3. Try this #
- 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 . 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.
- The discount changes the destination. Set the slip probability to 0. With the arrows from S go along the bottom row to +10. Now move down slowly. Question: at which 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 and . The reward of the third move is discounted by and the reward of the fifth by , and gives .
- Slip makes the agent careful. Go back to Two exits (slip 0.2, ). 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.
- The step reward. In Two exits (slip 0.2, ) set the step reward 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 and . 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 , more than any exit.
- Exploration against exploitation. In the learning figure choose Two exits, set the slip to 0 and . 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 it never tries anything new, so the triangles near +10 stay pale. Press Reset, set 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.
- Q-learning or SARSA on the cliff. In the world Cliff () 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 and press +1 episode: without random moves its return equals .
4. The math behind the figures #
Returns and values #
The return is the discounted sum of the rewards from time on:
Here is the reward received after the action (Sutton and Barto write for the same reward). The values of a policy are expected returns:
The expectation is over the random slips and over the policy's own choices. In this world the reward of one move is , where is the reward of the cell the agent enters (0 for a free cell), and is for the chosen direction and for each sideways one.
The Bellman equations #
Use 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:
The best possible values and satisfy the Bellman optimality equations, where the average over the policy becomes a maximum over actions:
The greedy policy with respect to , , 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.
Two exits without slip and with : 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 ?
The reward of the -th move is multiplied by . The +1 path is worth and the +10 path . The near exit wins only when , that is . Discounting favours near rewards, but a reward 10 times larger can make up for two extra steps.
Value iteration #
Value iteration turns the optimality equation into an update. Start with and apply to every cell at once (one sweep):
The Bellman optimality operator is a contraction in the max norm: for any two value tables, . So every sweep shrinks the error at least by the factor : . It also gives a stopping rule. If the largest change of a sweep is , then
This is the readout "distance to V* at most". In the chart, the largest change of each sweep stays below the dashed line , where is the change of the first sweep.
Value iteration with . About how many sweeps are needed to make the error bound one million times smaller?
We need , so . A close to 1 makes value iteration slow: with the same factor needs about 1375 sweeps.
Policy iteration #
Policy iteration starts from any policy and repeats two steps:
- Policy evaluation. For a fixed deterministic policy the Bellman expectation equation is linear: , where is the matrix of transition probabilities and the vector of expected rewards when the agent follows . So . The matrix is invertible for because every row of sums to at most 1. The figure solves this system with Gaussian elimination.
- Policy improvement. Make the policy greedy: . The policy improvement theorem says that then 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, is greedy with respect to its own values, so satisfies the Bellman optimality equation and 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 . It uses the one next state it really sees instead. After the step it computes a TD target and moves toward it with the learning rate :
The bracket is the TD error . If is terminal, the target is only . On average over , the Q-learning target is the right-hand side of the optimality equation for , with the current in place of . So Q-learning is a sampled version of value iteration on action values.
- Q-learning is off-policy. Its target uses the best next action, whatever the agent does next. It learns , the values of the greedy policy, even while it explores. (The guarantee needs every state and action to be tried infinitely often and step sizes with and . With a constant , as in the figure, the values keep moving a little in a world with slip.)
- SARSA is on-policy. Its target uses the action that the agent really takes next (the name comes from the five quantities ). It learns the values of the ε-greedy policy it follows, random moves included. That is why it keeps away from the cliff when .
In the world Cliff with , which statement is correct?
Q-learning evaluates the greedy policy, and without random moves the edge path is optimal (). SARSA evaluates the ε-greedy policy it follows. With 10% random moves, a cell next to the cliff is dangerous, so SARSA's values there are low and it learns a path farther away. During learning SARSA falls less often and earns more.
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 () 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 steps in the future is multiplied by . A small makes the agent short-sighted; a near 1 makes it patient. A rough measure is the effective horizon : about 10 steps for and 100 steps for . The discount also interacts with the other parts of the task:
- Distance: a far, large reward beats a near, small one only if is large enough (experiment 2).
- Risk: with slip, a short path next to a trap risks a large penalty soon, while the long safe path delays the reward. The discount sets the price of that delay (experiment 3).
- Step reward: with every extra step costs; with every step pays, and for near 1 the endless sum can be worth more than any exit (experiment 4).
The discount is part of the problem definition. Changing changes which policy is optimal, not only how fast the algorithms converge.
5. Related lessons #
- Reinforcement Learning: the full track. Its lessons on MDPs and the Bellman equations, dynamic programming, bandits and exploration, and TD control with SARSA and Q-learning go deeper into everything on this page.
- Inverse, determinant and projection: policy evaluation solves the linear system .
- Norms of vectors and matrices: the max norm behind the contraction argument.
- SGD and batch size: the Q-learning update is a stochastic approximation step with step size , like a step of SGD.
- Probability and Statistics: expectations and conditional expectations, the language of values and Bellman equations.