Skip to content

Temporal Difference Learning ​

Learning from incomplete episodes — Q-learning, SARSA, and bootstrapping


One-Sentence Summary ​

Temporal Difference (TD) learning combines Monte Carlo's model-free learning with Dynamic Programming's bootstrapping to update value estimates after each step, without waiting for episode completion.


Core Concept: Bootstrapping ​

TD learning's key insight: update estimates based on other estimates rather than waiting for final outcomes.

Monte Carlo vs Dynamic Programming vs TD ​

MethodUpdates WhenRequires ModelUses
Monte CarloEnd of episodeNoActual returns
Dynamic ProgrammingAny timeYesExpected returns
TD LearningEach stepNoEstimated returns

TD combines the best of both worlds:

  • From MC: Learn directly from experience (model-free)
  • From DP: Update estimates using other estimates (bootstrapping)

TD(0): The Foundation ​

The TD Update Rule ​

V(St)←V(St)+α[Rt+1+γV(St+1)⏟TD Target−V(St)]

Where:

  • α = learning rate
  • γ = discount factor
  • Rt+1+γV(St+1) = TD target (bootstrapped estimate)
  • Rt+1+γV(St+1)−V(St) = TD error (δt)

TD Error: The Learning Signal ​

The TD error δt measures the surprise between our prediction and what we observe:

δt=Rt+1+γV(St+1)−V(St)
TD ErrorMeaningUpdate Direction
δt>0Outcome better than expectedIncrease V(St)
δt<0Outcome worse than expectedDecrease V(St)
δt=0Prediction was accurateNo change

TD Error Over Training


SARSA: On-Policy TD Control ​

SARSA learns action-values (Q-values) while following the current policy.

The SARSA Update ​

Q(St,At)←Q(St,At)+α[Rt+1+γQ(St+1,At+1)−Q(St,At)]

Name origin: State, Action, Reward, State, Action

SARSA Algorithm ​

Initialize Q(s, a) arbitrarily
For each episode:
    Initialize S
    Choose A from S using policy derived from Q (e.g., epsilon-greedy)
    For each step of episode:
        Take action A, observe R, S'
        Choose A' from S' using policy derived from Q
        Q(S, A) <- Q(S, A) + alpha * [R + gamma * Q(S', A') - Q(S, A)]
        S <- S'
        A <- A'
    Until S is terminal

On-Policy Behavior ​

SARSA is on-policy because it updates Q using the action A′ that the policy actually selects, including exploratory actions.

Consequence: SARSA learns a safer policy that accounts for exploration behavior.


Q-Learning: Off-Policy TD Control ​

Q-learning learns the optimal action-values regardless of the policy being followed.

The Q-Learning Update ​

Q(St,At)←Q(St,At)+α[Rt+1+γmaxaQ(St+1,a)−Q(St,At)]

Key difference from SARSA: Uses maxaQ(S′,a) instead of Q(S′,A′)

Q-Learning Algorithm ​

Initialize Q(s, a) arbitrarily
For each episode:
    Initialize S
    For each step of episode:
        Choose A from S using policy derived from Q (e.g., epsilon-greedy)
        Take action A, observe R, S'
        Q(S, A) <- Q(S, A) + alpha * [R + gamma * max_a Q(S', a) - Q(S, A)]
        S <- S'
    Until S is terminal

Off-Policy Behavior ​

Q-learning is off-policy because:

  • Behavior policy: The policy used to explore (e.g., epsilon-greedy)
  • Target policy: The greedy policy it learns (always picks max Q)

These can be different, enabling learning from any exploration strategy.


SARSA vs Q-Learning: The Cliff Walking Example ​

SARSA vs Q-Learning Cliff Walking

The Setup ​

A grid world with:

  • Start state (bottom-left)
  • Goal state (bottom-right)
  • Cliff along the bottom (stepping in = large negative reward, return to start)
  • Two viable paths: safe (along top) vs optimal (along cliff edge)

Behavioral Differences ​

AlgorithmLearned PolicyWhy
SARSASafe path (top)Accounts for epsilon-greedy exploration near cliff
Q-LearningOptimal path (edge)Learns optimal regardless of exploration danger

SARSA learns the safer path because it knows that during exploration, the agent might accidentally fall off the cliff. Q-learning ignores this and learns the mathematically optimal path.

When to Use Each ​

Use SARSA WhenUse Q-Learning When
Safety matters during learningOnly final policy matters
Online deploymentOffline learning, then deploy
Robot that can damage itselfSimulation with no real consequence
Conservative behavior preferredPure optimality desired

Q-Table Evolution ​

Q-Table Evolution

The animation shows how Q-values propagate backward from the goal through the state space as the agent explores.


Experience Replay ​

A technique that dramatically improves sample efficiency in TD learning.

The Problem ​

TD updates are correlated (consecutive states are similar), leading to:

  • Unstable learning
  • Forgetting earlier experiences
  • Inefficient use of data

The Solution ​

Store experiences in a replay buffer and sample randomly:

Buffer={(s1,a1,r1,s1′),(s2,a2,r2,s2′),…}

Benefits:

  1. Breaks correlations: Random sampling decorrelates updates
  2. Data efficiency: Reuse each experience multiple times
  3. Stability: Prevents catastrophic forgetting

Implementation Sketch ​

python
# Store experience
buffer.append((state, action, reward, next_state, done))

# Sample random batch
batch = random.sample(buffer, batch_size)

# Update Q for each experience in batch
for (s, a, r, s_next, done) in batch:
    target = r + gamma * max(Q[s_next]) * (1 - done)
    Q[s][a] += alpha * (target - Q[s][a])

Convergence Properties ​

Theoretical Guarantees ​

AlgorithmConverges ToConditions
TD(0)True value functionUnder policy, infinite visits
SARSAOptimal Q*GLIE, Robbins-Monro
Q-LearningOptimal Q*All (s,a) visited infinitely

GLIE: Greedy in the Limit with Infinite Exploration

  • All state-action pairs visited infinitely often
  • Policy converges to greedy as t→∞

Robbins-Monro conditions (on learning rate αt):

∑t=1∞αt=∞and∑t=1∞αt2<∞

Common choice: αt=1/t or fixed small α with decaying exploration.

Practical Considerations ​

FactorEffect on Convergence
Learning rate too highOscillation, instability
Learning rate too lowSlow convergence
Exploration too highSlow convergence, noisy Q-values
Exploration too lowSuboptimal policy (stuck in local optimum)

Comparison Summary ​

AspectSARSAQ-Learning
PolicyOn-policyOff-policy
TargetQ(S′,A′)maxaQ(S′,a)
BehaviorConservativeRisk-neutral
Data ReuseLimitedExperience replay friendly
ConvergenceTo policy's QTo optimal Q*

Interview Questions ​

Q1: "Explain the difference between SARSA and Q-Learning." ​

"Both SARSA and Q-learning are TD control algorithms that learn Q-values, but they differ in their target calculation:

SARSA (on-policy):

  • Target: R+γQ(S′,A′) where A′ is the action actually taken
  • Learns Q-values for the policy being followed
  • More conservative because it accounts for exploratory actions

Q-Learning (off-policy):

  • Target: R+γmaxaQ(S′,a)
  • Learns optimal Q-values regardless of behavior policy
  • More sample-efficient (can use experience replay)

Example: In cliff-walking, SARSA learns the safer path because it knows epsilon-greedy might step off the cliff. Q-learning learns the optimal path along the edge because it assumes optimal behavior."

Q2: "What is bootstrapping in TD learning?" ​

"Bootstrapping means updating estimates based on other estimates rather than waiting for actual outcomes.

Non-bootstrapping (Monte Carlo):

  • Wait until episode ends
  • Use actual return: Gt=Rt+1+γRt+2+…

Bootstrapping (TD):

  • Update after each step
  • Use estimated return: Rt+1+γV(St+1)

Trade-off:

  • MC has no bias (uses true returns) but high variance
  • TD has bias (estimates may be wrong) but lower variance
  • TD is often preferred because it learns faster and works for continuing tasks."

Q3: "Why is experience replay important for Q-learning?" ​

"Experience replay stores transitions (s,a,r,s′) in a buffer and samples randomly for updates.

Benefits:

  1. Breaks temporal correlation: Consecutive samples are correlated; random sampling provides i.i.d.-like data for stable learning
  2. Sample efficiency: Each experience can be reused many times
  3. Enables off-policy learning: Q-learning can learn from any data, including old experiences

Why Q-learning but not SARSA?

  • Q-learning is off-policy, so it can learn from any data
  • SARSA is on-policy; old experiences may not reflect current policy's behavior

Limitation: Requires storing potentially large buffers (memory cost)"


Quick Reference Card ​

TEMPORAL DIFFERENCE LEARNING
---------------------------------------------------
TD(0):     V(S) <- V(S) + alpha * [R + gamma*V(S') - V(S)]
SARSA:     Q(S,A) <- Q(S,A) + alpha * [R + gamma*Q(S',A') - Q(S,A)]
Q-Learn:   Q(S,A) <- Q(S,A) + alpha * [R + gamma*max_a Q(S',a) - Q(S,A)]

TD ERROR (delta)
---------------------------------------------------
delta = R + gamma*V(S') - V(S)
Positive: outcome better than expected
Negative: outcome worse than expected

ON-POLICY VS OFF-POLICY
---------------------------------------------------
SARSA:     On-policy  - learns Q for behavior policy
Q-Learn:   Off-policy - learns Q* regardless of behavior

KEY PROPERTIES
---------------------------------------------------
Bootstrapping: Updates use estimates (not final returns)
Model-free:    No environment model needed
Online:        Updates after each transition

EXPERIENCE REPLAY
---------------------------------------------------
Store: (s, a, r, s', done) in buffer
Sample: Random batch for updates
Benefits: Breaks correlation, reuses data

Further Reading ​

  • Sutton & Barto, Chapter 6: Temporal-Difference Learning
  • Watkins (1989): Q-Learning (original paper)
  • Rummery & Niranjan (1994): SARSA introduction
  • Lin (1992): Experience Replay in RL