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*
V*(s) = maxₐ Q*(s, a)−100
Preparing the lab…

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 max⁡aQ(s,a)\max_a Q(s, a); 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.

Q-learning, first 1000 stepsPreparing…
Q-learning, 20,000 stepsPreparing…
SARSA, 20,000 stepsPreparing…

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 P(s′,r∣s,a)P(s', r \mid s, a) and a discount γ\gamma. The optimal action value satisfies the Bellman optimality equation:

Q∗(s,a)=E[ r+γmax⁡a′Q∗(s′,a′) ]Q^*(s, a) = \mathbb{E}\big[\, r + \gamma \max_{a'} Q^*(s', a') \,\big]

When the transition probabilities are known, applying this equation repeatedly computes Q∗Q^* directly (value iteration), which this page uses as the reference answer. When they are not, the samples (s,a,r,s′)(s, a, r, s') the agent experiences are all there is to approach it bit by bit — that is TD learning.

Three targets

AlgorithmNext-state value V^(s′)\hat V(s')TypeLearns
Q-learningmax⁡a′Q(s′,a′)\max_{a'} Q(s', a')Off-policyThe optimal policy's Q∗Q^*
SARSAQ(s′,a′)Q(s', a'), with a′a' drawn ε-greedily and actually takenOn-policyThe ε-greedy policy's own QQ
Expected SARSA∑a′π(a′∣s′) Q(s′,a′)\sum_{a'} \pi(a' \mid s')\, Q(s', a')On-policySame as SARSA, with lower variance

A terminal state's value is 0. The gap between target and old value, δ=r+γV^(s′)−Q(s,a)\delta = r + \gamma \hat V(s') - Q(s, a), is the TD error, and the learning rate α\alpha sets how far each update moves towards the target.

The classic comparison on the cliff

ε=0.1\varepsilon = 0.1, α=0.1\alpha = 0.1, γ=0.99\gamma = 0.99, trained for 100,000 steps:

Q-learningSARSA
Greedy route13 steps, hugging the cliff15 steps, one row away
Average return of the last 100 episodes (while exploring)−49.83−19.57
Mean ∣max⁡aQ−V∗∣\lvert \max_a Q - V^* \rvert0.1471.619
States whose greedy action is optimal97.3%75.7%

Q-learning learns "what if I always take the best action from now on", so its Q approaches Q∗Q^* 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 ε\varepsilon 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.

Slippery lake, 100,000 stepsPreparing…
Not slippery, 5000 stepsPreparing…
Grid world, 20,000 stepsPreparing…

When slippery, the optimal policy eventually reaches the goal from the start with probability 82.35% (value iteration gives V∗(start)=0.542V^*(\text{start}) = 0.542 at γ=0.99\gamma = 0.99). 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. 1. Getting started

    Default cliff walking with Q-learning, 1000 steps. Open "Returns".

    The first 5 episodes average −585. Why so low?
  2. 2. The shortest path

    Run to 20,000 steps and go back to "Values & policy".

    Why does Q-learning's greedy route hug the cliff?
  3. 3. SARSA

    Switch the algorithm to SARSA.

    Why does SARSA go one row further round (15 steps)?
  4. 4. No exploration

    Back to Q-learning, with exploration rate ε set to 0.

    Why is every episode now exactly −13?
  5. 5. Slipping

    Switch to the 4×4 frozen lake (slippery) and run 100,000 steps. Open "V against V*".

    The greedy policy now reaches the goal 82.35% of the time. Why not 100%?

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

Why is Q-learning called “off-policy”?
On cliff walking, which earns more return while learning?
A discount γ closer to 1 means…

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