Q-learning and SARSA
Q-learning, SARSA and Expected SARSA step by step on Gymnasium's cliff walking and frozen lake: every ε-greedy choice, TD target and update, against the exact optimum.
Updated
- States, actions, rewards and the Q table
- ε-greedy exploration
- TD targets: off-policy Q-learning vs on-policy SARSA
- Why SARSA takes the safe path on the cliff
- Value iteration and the optimal Q*
Intuition
Learning by trial and error
Cliff walking: a 4 × 12 grid, walking from the bottom-left corner to the bottom-right. Each step costs −1; stepping onto the cliff in the bottom row costs −100 and sends you back to the start. At first the agent knows nothing and can only wander; it acts ε-greedily: 90% of the time it takes the action it currently thinks best, 10% of the time a random one, to discover new paths.
The three small labs below really learn in your browser. Darker blue means a higher ; arrows are each cell's current greedy action; the red row is the cliff and green the goal; the orange line is the route actually taken in the previous episode.
In the first 1000 steps only 5 episodes are completed, with an average return of −585: most of the time is spent wandering and falling off the cliff. After 20,000 steps Q-learning's greedy route is the 13-step shortest path along the row just above the cliff; SARSA's goes one row further round, 15 steps.
Math
Markov decision processes and the Bellman equation
An environment is described by states, actions, transition probabilities and a discount . The optimal action value satisfies the Bellman optimality equation:
When the transition probabilities are known, applying this equation repeatedly computes directly (value iteration), which this page uses as the reference answer. When they are not, the samples the agent experiences are all there is to approach it bit by bit — that is TD learning.
Three targets
| Algorithm | Next-state value | Type | Learns |
|---|---|---|---|
| Q-learning | Off-policy | The optimal policy's | |
| SARSA | , with drawn ε-greedily and actually taken | On-policy | The ε-greedy policy's own |
| Expected SARSA | On-policy | Same as SARSA, with lower variance |
A terminal state's value is 0. The gap between target and old value, , is the TD error, and the learning rate sets how far each update moves towards the target.
The classic comparison on the cliff
, , , trained for 100,000 steps:
| Q-learning | SARSA | |
|---|---|---|
| Greedy route | 13 steps, hugging the cliff | 15 steps, one row away |
| Average return of the last 100 episodes (while exploring) | −49.83 | −19.57 |
| Mean | 0.147 | 1.619 |
| States whose greedy action is optimal | 97.3% | 75.7% |
Q-learning learns "what if I always take the best action from now on", so its Q approaches and its route is the shortest; but it is still acting ε-greedily, and along the cliff edge one random step can send it over, so the return it earns while learning is actually worse. SARSA builds "I will sometimes step randomly" into its values and prefers a slightly longer way round. Expected SARSA also learns the 15-step safe route.
Set to 0 (no exploration) and after 20,000 steps every Q-learning episode returns −13: the route is the same, it simply never falls off at random.
Frozen lake: a slippery world
In the frozen lake (Gymnasium FrozenLake 4 × 4) the ice is slippery: an intended move succeeds with probability 1/3, and slides to each side with 1/3 each. Reaching the goal scores 1; falling into a hole ends the episode.
When slippery, the optimal policy eventually reaches the goal from the start with probability 82.35% (value iteration gives at ). After 20,000 steps of Q-learning the greedy policy succeeds 78.05% of the time, and after 100,000 steps exactly the optimal 82.35%. The actual average return of the last 100 episodes is only about 0.39: that is the real result with ε exploration and at most 100 steps per episode, which is not the same thing as "the greedy policy's success probability with unlimited steps". Without slipping the greedy route is 6 steps; this site's grid world takes 16.
How it is computed, with real numbers
Once the lab above has loaded, this panel works through the same formulas with its current numbers.
Experiment
Follow the lesson
Course
Lesson 1: from wandering to the shortest path
5 steps · each one: set up and run → look → answer
1. Getting started
Default cliff walking with Q-learning, 1000 steps. Open "Returns".
2. The shortest path
Run to 20,000 steps and go back to "Values & policy".
3. SARSA
Switch the algorithm to SARSA.
4. No exploration
Back to Q-learning, with exploration rate ε set to 0.
5. Slipping
Switch to the 4×4 frozen lake (slippery) and run 100,000 steps. Open "V against V*".
Try these settings
Exercises
Exercises
Exercise 1: not a step too many
With Q-learning, get the average return of the last 20 episodes to −13 (every episode the 13-step shortest path, never falling).
Hint
Set the exploration rate ε to 0 and train 20,000 steps: every episode returns −13. With ε = 0.1 a random step sooner or later makes some episode longer or sends it over the cliff.
- Average return of the last 20 episodes ≥ -13
Exercise 2: optimal on slippery ice
On the slippery lake, make the greedy action optimal in every state.
Hint
The defaults trained for 100,000 steps: 100%. At 50,000 steps it is not quite there (90.9%).
- Optimal actions ≥ 100.0%
Quiz
Further reading
Frequently asked questions
What is the difference between Q-learning and SARSA?
Both learn a Q table with TD updates; they differ in the next-state value in the target. Q-learning takes maxₐ′ Q(s′, a′) (off-policy, learning the optimal policy); SARSA takes Q(s′, a′) of the next action it will actually execute (on-policy, learning the current exploring policy). On cliff walking, Q-learning learns the shortest path along the edge and SARSA a safer route.
Does Q-learning always converge?
In the tabular case, if every state–action pair is visited infinitely often and the learning rate decreases appropriately, Q-learning converges to Q* with probability 1 (Watkins and Dayan, 1992). With a neural network approximating Q there is no such guarantee — see DQN.
How should I choose ε in ε-greedy?
Too small and you may never discover a better path; too large and you keep wandering even after learning. A common choice decays it from 1 to about 0.05. This page fixes it at 0.1 by default to show the difference between Q-learning and SARSA clearly.
What is TD learning?
Temporal-difference learning: instead of waiting for the episode to end, it updates the current estimate towards "one step of reward plus the estimate of the next state's value" (bootstrapping). It sits between Monte Carlo (wait for the end, use the real return) and dynamic programming (needs the transition probabilities).
What if there are too many states for a table?
Use function approximation: replace the Q table with a neural network that takes a state and outputs each action's Q. That is DQN; it also needs experience replay and a target network to train stably.
Further reading
- Watkins, Dayan, Q-learning, Machine Learning, 1992: the convergence proof.
- Rummery, Niranjan, On-line Q-learning using connectionist systems, 1994: where SARSA comes from.
- Sutton, Barto, Reinforcement Learning: An Introduction, 2nd edition, 2018: chapter 6 (example 6.6 is this page's cliff walk).
- van Seijen et al., A theoretical and empirical analysis of Expected Sarsa, 2009.
- Gymnasium, Toy Text environments: the standard implementations of cliff walking and the frozen lake.