AnyLearn
All lessons
AIadvanced

Monte Carlo, TD, and Q-Learning

Leave the model behind. Monte Carlo methods wait for a full episode to update; TD methods bootstrap from the very next step. See exactly where SARSA and Q-learning diverge on the on-policy/off-policy axis, and why that single difference changes everything about convergence guarantees.

Not signed in — your progress and quiz score won't be saved.
Lesson progress1 / 10

Model-free learning

Dynamic programming requires knowing PP and RR exactly. In most real problems — games, robotics, dialogue — you cannot write down the transition model. Model-free methods learn directly from interaction: sample (st,at,rt,st+1)(s_t, a_t, r_t, s_{t+1}) tuples and update value estimates from those samples alone.

No model means you replace the expectation over PP with sampled experience. The price is variance: random samples are noisy. The reward is generality: the same algorithm applies whether you're playing Atari or controlling a power grid. Model-free methods are the workhorses of modern deep RL.

Two families differ in how much experience they use per update: Monte Carlo waits for a full episode; TD methods update after each step.

Full lesson text

All 10 steps on one page — for reading, reference, and search.

Show

1. Model-free learning

Dynamic programming requires knowing PP and RR exactly. In most real problems — games, robotics, dialogue — you cannot write down the transition model. Model-free methods learn directly from interaction: sample (st,at,rt,st+1)(s_t, a_t, r_t, s_{t+1}) tuples and update value estimates from those samples alone.

No model means you replace the expectation over PP with sampled experience. The price is variance: random samples are noisy. The reward is generality: the same algorithm applies whether you're playing Atari or controlling a power grid. Model-free methods are the workhorses of modern deep RL.

Two families differ in how much experience they use per update: Monte Carlo waits for a full episode; TD methods update after each step.

2. Monte Carlo returns

Monte Carlo (MC) policy evaluation runs the policy until the episode ends, computes the actual return Gt=k=0Tt1γkrt+k+1G_t = \sum_{k=0}^{T-t-1} \gamma^k r_{t+k+1}, and uses it to update:

V(st)V(st)+α[GtV(st)].V(s_t) \leftarrow V(s_t) + \alpha\bigl[G_t - V(s_t)\bigr].

Properties:

  • Unbiased: GtG_t is a true sample of the return under π\pi — no approximation.
  • High variance: a single trajectory can be wildly atypical.
  • Episodic only: requires terminal states; useless for continuing tasks.
  • No bootstrapping: each update uses only real rewards, never other value estimates.

MC is the right baseline for finite-horizon problems where variance is manageable. For long episodes, the variance compounds multiplicatively and learning slows to a crawl.

3. Temporal-difference learning: TD(0)

TD(0) bootstraps: it updates after one step, using the estimated value of the next state as a proxy for the rest of the return:

V(st)V(st)+α[rt+γV(st+1)TD targetV(st)].V(s_t) \leftarrow V(s_t) + \alpha\bigl[\underbrace{r_t + \gamma V(s_{t+1})}_{\text{TD target}} - V(s_t)\bigr].

The bracketed term δt=rt+γV(st+1)V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t) is the TD error — positive means the next state was better than expected, negative means worse.

Properties vs MC:

Monte CarloTD(0)
BiasNoneYes (uses VV estimate)
VarianceHighLow
Requires episode endYesNo
Online updatesNoYes

Bias is the price; low variance and online learning are the payoff.

4. The exploration-exploitation tradeoff

A value-function learner must also act. A greedy agent — always pick argmaxaQ(s,a)\arg\max_a Q(s,a) — exploits current knowledge but never discovers better actions. An agent that always explores learns the environment but never cashes in.

ϵ\epsilon-greedy is the simplest balance:

π(as)={argmaxaQ(s,a)with probability 1ϵuniform randomwith probability ϵ\pi(a \mid s) = \begin{cases} \arg\max_{a'} Q(s,a') & \text{with probability } 1-\epsilon \\ \text{uniform random} & \text{with probability } \epsilon \end{cases}

Typical schedule: start ϵ=1.0\epsilon = 1.0, anneal to 0.010.010.10.1 over training. Smarter alternatives exist (UCB, Thompson sampling, intrinsic motivation) but ϵ\epsilon-greedy is the de-facto baseline because it's simple, fast, and hard to beat on standard benchmarks.

5. SARSA: on-policy TD control

To learn QπQ^\pi model-free, apply TD to action values. SARSA (State-Action-Reward-State-Action) uses the actual next action at+1a_{t+1} sampled from the behavior policy:

Q(st,at)Q(st,at)+α[rt+γQ(st+1,at+1)Q(st,at)].Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\bigl[r_t + \gamma\, Q(s_{t+1}, a_{t+1}) - Q(s_t, a_t)\bigr].

SARSA is on-policy: the target Q(st+1,at+1)Q(s_{t+1}, a_{t+1}) is evaluated at the action the agent actually took under π\pi. This means SARSA learns the value of the exploratory policy (including those random ϵ\epsilon-greedy moves). In cliff-walking environments, SARSA learns a safer path away from the cliff because it accounts for its own exploration mistakes.

6. Q-learning: off-policy TD control

Q-learning replaces Q(st+1,at+1)Q(s_{t+1}, a_{t+1}) with the greedy maximum — regardless of what action was actually taken:

Q(st,at)Q(st,at)+α[rt+γmaxaQ(st+1,a)Q(st,at)].Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\bigl[r_t + \gamma \max_{a'} Q(s_{t+1}, a') - Q(s_t, a_t)\bigr].

This is off-policy: the target is the value of the greedy policy even though the agent behaves ϵ\epsilon-greedily. Q-learning directly approximates QQ^\star — it converges to the optimal action-value function under mild conditions (all state-action pairs visited infinitely, learning rates satisfying Robbins-Monro).

The key distinction: SARSA is safer in execution but Q-learning converges to the globally optimal policy. Deep RL (DQN and successors) is built on Q-learning.

7. Q-learning in code

A complete tabular Q-learning loop:

import numpy as np

def q_learning(env, n_episodes, alpha=0.1, gamma=0.99,
               eps_start=1.0, eps_end=0.01, eps_decay=0.995):
    Q = np.zeros((env.n_states, env.n_actions))
    eps = eps_start
    for ep in range(n_episodes):
        s = env.reset()
        done = False
        while not done:
            # epsilon-greedy action selection
            if np.random.rand() < eps:
                a = np.random.randint(env.n_actions)
            else:
                a = Q[s].argmax()
            s_next, r, done = env.step(a)
            # Q-learning update (off-policy: uses max, not actual a')
            td_target = r + gamma * Q[s_next].max() * (not done)
            Q[s, a] += alpha * (td_target - Q[s, a])
            s = s_next
        eps = max(eps_end, eps * eps_decay)
    return Q

Swap Q[s_next].max() for Q[s_next, a_next] (where a_next is sampled from π\pi) and you have SARSA.

8. TD(lambda) and eligibility traces

TD(0) updates from one-step returns; MC uses the full return. TD(λ\lambda) interpolates via the λ\lambda-return:

Gtλ=(1λ)n=1λn1Gt(n),G_t^\lambda = (1-\lambda)\sum_{n=1}^{\infty} \lambda^{n-1} G_t^{(n)},

where Gt(n)G_t^{(n)} is the nn-step return. At λ=0\lambda=0 you recover TD(0); at λ=1\lambda=1 you recover MC.

Eligibility traces implement this efficiently without storing all returns: each state gets a running trace et(s)e_t(s) that fades geometrically at rate γλ\gamma\lambda and spikes when ss is visited. The TD error propagates backward to all recently visited states proportionally to their trace. TD(λ\lambda) is strictly more data-efficient than TD(0) for most problems — it's the basis of the forward/backward view in classical RL.

9. On-policy vs off-policy: a critical comparison

The on-policy / off-policy distinction matters deeply:

SARSA (on-policy)Q-learning (off-policy)
Target policySame as behaviorGreedy (π\pi^\star)
Converges toQπQ^\pi (exploratory)QQ^\star (optimal)
Safer in executionYes — accounts for ϵ\epsilon noiseNo — may underestimate cliff risk
Reuse of old dataNo — off-policy data is biasedYes — replays are fine
Foundation ofSARSA, Expected SARSADQN, Rainbow, C51

Off-policy methods are more powerful (can learn from any behavior policy, replay buffers, multiple agents) but require importance sampling corrections or bootstrapping tricks when the behavior and target policies diverge sharply.

10. Convergence caveats and practical tips

Three gotchas practitioners encounter:

  • Tabular convergence requires infinite visits. Every (s,a)(s,a) pair must be visited infinitely often. In large state spaces, this is impossible without function approximation — and approximation breaks the convergence proof.
  • Learning rate scheduling matters. The Robbins-Monro conditions (tαt=\sum_t \alpha_t = \infty, tαt2<\sum_t \alpha_t^2 < \infty, e.g. αt=1/t\alpha_t = 1/t) guarantee convergence in theory. In practice, a fixed α=0.001\alpha = 0.001 often beats the schedule once you use replay buffers and mini-batches.
  • Maximisation bias. Q-learning's maxaQ(s,a)\max_{a'} Q(s',a') is an overestimate when QQ is noisy: E[maxaXa]maxaE[Xa]\mathbb{E}[\max_a X_a] \ge \max_a \mathbb{E}[X_a]. Double Q-learning (DQN's key fix) decouples action selection from value estimation to remove this bias.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. The key algorithmic difference between SARSA and Q-learning is:
    • SARSA uses a neural network for function approximation; Q-learning uses a table.
    • SARSA bootstraps from the next action actually taken; Q-learning bootstraps from the greedy maximum.
    • SARSA is model-based; Q-learning is model-free.
    • Q-learning requires episodic tasks; SARSA works in continuing tasks.
  2. Monte Carlo updates are unbiased but have high variance. What is the source of this variance?
    • MC uses a biased estimator of the discount factor $\gamma$.
    • The return $G_t$ is computed from a single trajectory, which may be an atypical sample of the distribution.
    • MC bootstraps from imprecise value estimates, compounding errors over time.
    • The $\epsilon$-greedy exploration adds noise to the action-value estimates.
  3. Why does Q-learning directly approximate $Q^\star$ while SARSA approximates $Q^\pi$?
    • Q-learning uses a larger learning rate, allowing faster convergence to $Q^\star$.
    • Q-learning's target uses $\max_{a'}$ (the greedy policy), so it always evaluates the optimal action regardless of behavior.
    • SARSA has higher variance, which pulls its estimates away from $Q^\star$.
    • Q-learning uses importance sampling to correct for the mismatch between behavior and target policies.
  4. In TD($\lambda$), what happens at $\lambda = 0$ and $\lambda = 1$?
    • $\lambda = 0$ gives the full Monte Carlo return; $\lambda = 1$ gives one-step TD.
    • $\lambda = 0$ gives one-step TD(0); $\lambda = 1$ gives the full Monte Carlo return.
    • $\lambda = 0$ disables learning; $\lambda = 1$ maximizes the bias-variance tradeoff.
    • $\lambda = 0$ and $\lambda = 1$ are both equivalent to SARSA, just with different trace decay.
  5. What is maximisation bias in Q-learning, and how does Double Q-learning fix it?
    • Q-learning overestimates values because $\mathbb{E}[\max_a X_a] \ge \max_a \mathbb{E}[X_a]$; Double Q-learning uses two Q-networks, decoupling action selection from value estimation.
    • Q-learning underestimates values due to the discount factor; Double Q-learning removes discounting.
    • The max operator introduces gradient instability; Double Q-learning clips gradients.
    • Q-learning ignores the behavior policy; Double Q-learning adds importance sampling weights to correct the bias.

Related lessons