05 / 27 · Reinforcement Learning
Q-learning and temporal-difference learning
Learning values from experience: exploration, Monte Carlo and TD targets, SARSA and Q-learning, convergence conditions, and finite-episode λ-returns. Exact fictional examples separate target noise from the cost of exploration.
On this page 10
A service can observe the result of a decision without knowing the probabilities of every possible result. The MDP note assumed those probabilities were available to a Bellman backup. Here the learner receives a transition, updates an estimate, and decides what to try next. Two choices matter: which experience to collect and how much of its future outcome to wait for.
We use three small, fictional cases: binary feedback for four alternatives, a two-stage processing job, and a continuing service with a rechargeable resource. Their inputs, figures and exact calculations were specified for this note with AI assistance. They are teaching examples, not measurements of a deployed system. The code enumerates their outcomes without downloading data or running a simulator.
At time the learner sees state , chooses action , then observes reward and state . A policy describes action probabilities. The discount is , the return is for a finite episode, and . Current tables and are estimates; superscripts and denote the policy’s true values and optimal values. Our continuing example has ; terminal states in episodic examples have value zero.
For a finite-horizon task, include time or the remaining horizon in the state whenever it affects future returns; otherwise the value also needs a time index. The notation here uses that state convention.
Baseline: value iteration needs the model#
A known model permits an exact expectation over possible successors. For optimal action values,
A learner without the model cannot evaluate that expectation directly. It can observe one reward and successor, form a sample target, and adjust its current estimate. The arithmetic is the same as an incremental mean:
The first equality exactly averages observations; the second replaces the averaging weight by a chosen step size. A constant discounts older observations. This can track a changing target, but it does not satisfy the diminishing-step conditions used later for convergence. A further complication is that the target contains another value estimate, which also changes during learning.
Exploration first: the multi-armed bandit#
Before considering future states, suppose there are four alternatives with stationary, independent reward streams. Each reward is 0 or 1. The learner does not know their means and chooses which stream to observe next. Greedy selection can stop trying a good alternative after unlucky early observations. Fixed ε-greedy selection instead chooses uniformly with probability , and otherwise uses a largest sample mean.
For this stationary bandit, every alternative is sampled infinitely often almost surely under fixed ε-greedy exploration. Its sample mean then converges. If some alternatives are suboptimal, random selection still incurs an expected loss on every future decision. Writing , the expected regret is
Fixed uniform exploration alone contributes . Thus constant ε generally leaves linear regret; this is not a statement about a schedule that reduces ε.
UCB1 gives rarely sampled alternatives an uncertainty bonus. After trying every alternative once, choose at decision
where counts and means use decisions before . The bonus follows a bounded-reward concentration argument; it is not an empirical standard deviation. For independent stationary rewards in , Auer, Cesa-Bianchi and Fischer (2002), Theorem 1 prove a gap-dependent logarithmic expected-regret bound. The coefficient and assumptions matter: arbitrary bonuses or dependent, drifting feedback do not inherit that theorem.
Our snapshot contains 40 observations. At the next decision, , it gives:
| Alternative | Trials | Successes | Mean | UCB1 score |
|---|---|---|---|---|
| 1 | 18 | 11 | 0.611111 | 1.253465 |
| 2 | 12 | 5 | 0.416667 | 1.203387 |
| 3 | 6 | 2 | 0.333333 | 1.445924 |
| 4 | 4 | 1 | 0.250000 | 1.612639 |
Greedy chooses alternative 1, while UCB1 chooses 4. Its large score expresses uncertainty, not a probability of success above one. These counts are constructed inputs: there is no hidden true mean or claim that alternative 4 is actually best. In an MDP, exploration must also reach states; randomizing actions in a state never reached cannot provide its data.
Monte Carlo prediction#
Prediction holds the policy fixed and estimates its values. In the processing example there is no action choice. Intake gives reward and leads to stage with probability , or stage with probability . Stage terminates with reward 0 or 4, equally likely; stage terminates with reward 1 or 3, equally likely. All episodes take two transitions, and .
Both successor stages have expected reward 2. Therefore
A Monte Carlo target waits for the full return. From intake, the four possible returns and probabilities are
Updating uses an unbiased target for . This says nothing about whether one sampled target is close to the value. Full-return prediction must wait for termination; continuing tasks require another construction, such as a finite horizon with a tail estimate. Longer episodes do not universally have larger return variance: reward correlations, discounting and the reward distribution matter.
TD(0): learning a guess from a guess#
The Bellman expectation equation replaces the random future after the next state by its conditional mean. TD(0) substitutes the current value table for that mean and updates immediately:
Using a learned estimate within a target is bootstrapping. Sutton (1988), §§2.2–2.3 and 5.1 develops temporal-difference prediction and the cumulative-reward extension. A terminal successor contributes zero. An artificial time limit is different from a true terminal state if the intended process would continue beyond it.
For one observed episode, intake goes to , then terminates with reward 4. Suppose initially , and . TD can update intake after the first transition:
Monte Carlo waits for reward 4, obtains , and would instead update the same initial intake estimate to . Neither one-sample update equals the true value . TD is early because it uses the estimate 3; Monte Carlo is late because it uses the observed final reward 4.
Which target is better: bias against variance#
Treat as fixed when comparing the distributions of the next targets. In a Markov process under a fixed policy, its conditional TD bias is
The exact next-state values remove this bias. Indeed, the exact-value TD target is the conditional expectation of the return given the first reward and successor. The law of total variance then gives variance no larger than the return’s variance, provided those variances exist. Replacing those values with arbitrary estimates removes this guarantee.
In our example the Monte Carlo mean is and variance . With exact successor values, TD is always , so its variance is zero. Now deliberately use and . TD targets become 7 and , with probabilities and . Their mean is , bias , and variance .
Variance depends on the continuation estimate
The experiment compares target distributions, not learning curves. A shorter sampled horizon alone does not ensure lower variance or smaller mean-squared error. Step size, approximation error and available experience also affect the learned table.
A useful exact identity holds with a frozen value table and terminal value zero. Expanding each cancels intermediate values:
This is an identity between errors, not equality of ordinary Monte Carlo and online TD(0) parameter updates. Online updates can change the table between terms; repeated states can make this difference visible. Eligibility traces below specify how later errors contribute back to earlier states. The policy-gradient note uses a related weighted sum to estimate advantages.
On a fixed dataset, the zero of the sum of tabular TD residual updates solves an empirical Bellman system, whereas averaging full returns gives empirical Monte Carlo values. With a discounted, fully specified empirical transition model, the former system has a unique solution. Replaying individual samples with a constant step need not reach that zero exactly, and neither empirical estimate is guaranteed better on an unknown true process.
From prediction to control: SARSA and Q-learning#
Action values let the agent compare actions without querying a transition model. Both methods update , but use different targets:
SARSA uses the next action actually selected by the behaviour policy, including its exploration. The five quantities in its name are state, action, reward, next state, next action. It is on-policy. With expected SARSA, averaging over the policy removes the randomness of this next-action draw, while environment randomness remains. Q-learning uses a greedy target even when the actual next action is exploratory: this is the off-policy distinction, not a promise that arbitrary data coverage suffices. See Singh et al. (2000), §2.1 and Watkins and Dayan (1992), §2.
For a local arithmetic check, let a transition give reward 2, with next-state action estimates 3 and , current updated entry 1, , and . Q-learning uses target 4.4 and updates the entry to 1.85. If SARSA’s next action is the one valued at , it uses target 0.4 and updates to 0.85. With ε-greedy , the next-action probabilities are 0.9 and 0.1; expected SARSA uses target 4 and updates to 1.75. These are stipulated current estimates, not converged values.
An implementation chooses the next action before the SARSA update and executes that same choice. For a true terminal transition every method uses only the immediate reward. Otherwise interaction continues; changing the target does not change which reward was observed.
A rechargeable resource: what on-policy and off-policy learn#
Consider a continuing service with resource level . Action 0 charges; action 1 runs a job. The full model is provided here only so that we can calculate an exact reference for learning:
| State | Charge: next state, reward | Run: next state, reward |
|---|---|---|
| 0 | 1, −1/5 | 0, −6 |
| 1 | 2, −1/5 | 0, 2 |
| 2 | 2, −1/5 | 1, 5/2 |
Rewards are utility units. Running with no resource incurs a penalty; charging at capacity still costs time. There is no terminal state or reset, and . A deterministic skeleton chooses one action per state. Uniform ε-greedy mixing around it gives
There are eight skeletons. For each, calculate its transition matrix and expected rewards, then solve
The discounted system is invertible. The code compares all states and checks the Bellman residuals; it does not infer a best policy from one possibly unreachable starting state.
With no exploration, the optimal skeleton is : charge at zero, run otherwise. Its values are . But under permanent , each non-skeleton action still occurs with probability . The best skeleton becomes , which also charges at level 1. Its values are
Compare under the same exploration
From level 1, exploring around the no-exploration optimum gives . Choosing the best skeleton for that same exploration rate gives . Charging earlier changes the future state distribution and reduces exposure to running at zero. If exploration is switched off, the original optimum has value there; comparing that number directly with an exploring policy would change the evaluation condition.
These are exact policy evaluations, not a finite-run SARSA benchmark. They show why evaluating persistent behaviour can favour a different action from optimizing a policy intended for greedy deployment. SARSA does not automatically converge to the best exploring policy for every arbitrary exploration rule; Singh et al. (2000), §3.2 gives conditions for persistent rank-based randomization. With vanishing exploration, convergence to the unrestricted optimum still needs the conditions below.
When the estimates converge#
Keep the statement to finite tabular, stationary MDPs with bounded rewards and . For every updated state or state–action entry, the step sizes must obey
Here counts that entry’s updates, not all global environment steps. A schedule satisfies these sums. The first sum prevents learning from stopping too early; the second controls accumulated sampling noise.
- Fixed-policy tabular TD(0) converges to the policy value when every relevant state continues to be sampled and the stochastic-approximation conditions hold. This is a fixed-policy contraction problem, not a result for an arbitrarily changing policy.
- Tabular Q-learning converges almost surely to optimal action values with infinitely many valid samples of every state–action pair and those step-size conditions. The behaviour may differ from the target policy, but must provide the required coverage.
- For SARSA’s convergence to optimal values, exploration must additionally be greedy in the limit with infinite exploration (GLIE). Merely writing is insufficient: exploration may disappear before needed actions or states receive enough visits.
The precise results are Watkins and Dayan (1992), Jaakkola, Jordan and Singh (1993), and Singh et al. (2000), Theorem 1. We do not extend the discounted statement to every undiscounted episodic problem by assuming termination alone. Properness and other hypotheses need separate checking.
A constant positive step violates the square-summability condition and generally leaves noise; deterministic special cases can still converge. These theorems provide neither a useful finite-sample budget nor a universal horizon-dependent rate. Replacing the table by a neural network also changes the mathematical problem.
Between one step and the whole episode: n-step returns and eligibility traces#
For a frozen value function, an n-step target uses observed rewards until the chosen horizon, then bootstraps if the episode is still running:
Once the horizon reaches the terminal time, use the full return . Longer horizons replace some value-estimation error by additional sampled rewards. Bias and variance need not change monotonically with the horizon.
For a finite remaining length , the λ-return can include the terminal case explicitly:
The last term holds the remaining probability mass. At this is the one-step target, and at it is the full return. With one transition left, the expression is just . In the continuing infinite-series formula, geometric weights sum to one only for ; substituting 1 into that series does not define its endpoint.
A separate three-transition trace has rewards , frozen values , and . The targets for horizons 1, 2 and 3 are , and . For , their weights are , giving .
Eligibility traces accumulate how strongly a later TD error should affect previously visited states. Start each episode with zero traces; accumulating tabular traces use
For frozen values, . In our trace the TD errors are ; their weighted sum is , exactly . Accumulating these corrections and applying them after the episode yields the corresponding forward-view update. Ordinary online TD(λ) changes immediately, so finite-step equality with this frozen forward view is not automatic. Sutton (1988), §§2.2–2.3 and 5.2 distinguishes sequence-end and within-sequence updates.
What changed#
| Choice | What it uses | What must be checked |
|---|---|---|
| Exact Bellman backup | Known transition probabilities and expected rewards | Correct model |
| Monte Carlo target | Observed return to termination | Fixed evaluation policy, finite moments |
| TD target | Next reward and estimated successor value | Bootstrap error and coverage |
| SARSA target | The next action actually selected | Behaviour and target agree |
| Q-learning target | A greedy next-state action value | Off-policy coverage and convergence conditions |
Limitations#
The finite cases isolate mechanisms. They do not predict performance on text, images or continuous state spaces. Our exact evaluator uses a known model for validation, while the learner would only see sampled transitions. Tabular values cannot generalize to unvisited states, and ε-greedy exploration can waste actions on known poor choices. A transition may be stored and reused; neither TD nor Q-learning requires throwing it away after one update.
No learning curve in this note establishes a universal ranking of algorithms. Bootstrapping, noisy maximization, changing policies and function approximation introduce distinct errors. In particular, maximizing unbiased noisy action estimates can create upward bias; the next note discusses methods that separate selection from evaluation.
What you should remember#
- A sample target replaces an unavailable Bellman expectation; the learner must still collect useful experience.
- Monte Carlo waits for the return. TD updates sooner using another estimate; its variance advantage requires conditions.
- SARSA evaluates the next action actually taken. Q-learning targets a greedy continuation even during exploration.
- Permanent exploration can change the optimal behaviour, as the resource example shows under identical evaluation conditions.
- Convergence needs coverage, appropriate step sizes and, for optimal SARSA, GLIE. Finite-episode λ-returns retain a terminal tail weight.
Code#
This standalone Python example uses only the standard library. It solves the eight skeletons at each of two exploration rates with exact fractions, checks the prediction target moments, and computes the UCB snapshot. Floating-point logarithms affect only the displayed UCB scores. It does not train an agent or require a third-party dataset.
from fractions import Fraction as F
from itertools import product
from math import log, sqrt
def solve(matrix, rhs):
rows = [list(row) + [b] for row, b in zip(matrix, rhs)]
n = len(rows)
for col in range(n):
pivot = next(i for i in range(col, n) if rows[i][col])
rows[col], rows[pivot] = rows[pivot], rows[col]
divisor = rows[col][col]
rows[col] = [x / divisor for x in rows[col]]
for i in range(n):
if i != col:
multiplier = rows[i][col]
rows[i] = [x - multiplier * y for x, y in zip(rows[i], rows[col])]
return [row[-1] for row in rows]
def step(state, action):
if action == 0: # charge
return min(2, state + 1), -F(1, 5)
return max(0, state - 1), [-F(6), F(2), F(5, 2)][state]
def evaluate(skeleton, epsilon):
gamma = F(4, 5)
matrix = [[F(i == j) for j in range(3)] for i in range(3)]
reward = [F(0) for _ in range(3)]
for s in range(3):
for a in range(2):
probability = epsilon / 2 + (1 - epsilon) * (a == skeleton[s])
nxt, r = step(s, a)
matrix[s][nxt] -= gamma * probability
reward[s] += probability * r
return solve(matrix, reward)
def best(epsilon):
candidates = [(p, evaluate(p, epsilon)) for p in product(range(2), repeat=3)]
return max(candidates, key=lambda item: sum(item[1]))
def moments(outcomes):
mean = sum(p * x for p, x in outcomes)
return mean, sum(p * (x - mean) ** 2 for p, x in outcomes)
def demo():
for epsilon in (F(0), F(1, 5)):
policy, values = best(epsilon)
print('epsilon', epsilon, 'skeleton', policy, 'V', [str(x) for x in values])
print('exploring optimal skeleton: V(1)', evaluate((0, 1, 1), F(1, 5))[1])
mc = [(F(3, 8), -F(1)), (F(3, 8), F(11, 5)),
(F(1, 8), -F(1, 5)), (F(1, 8), F(7, 5))]
print('MC mean, variance', [str(x) for x in moments(mc)])
print('wrong TD mean, variance', [str(x) for x in moments([(F(3, 4), F(7)), (F(1, 4), -F(29, 5))])])
scores = [hits / n + sqrt(2 * log(41) / n) for n, hits in zip([18, 12, 6, 4], [11, 5, 2, 1])]
print('UCB1 scores', [round(x, 6) for x in scores])
demo()
epsilon 0 skeleton (0, 1, 1) V ['35/9', '46/9', '593/90']
epsilon 1/5 skeleton (0, 0, 1) V ['26751/9890', '976/215', '118217/19780']
exploring optimal skeleton: V(1) 784/215
MC mean, variance ['3/5', '52/25']
wrong TD mean, variance ['19/5', '768/25']
UCB1 scores [1.253465, 1.203387, 1.445924, 1.612639]
The full verifier also checks all policy Bellman residuals, the finite λ-mixture endpoints and a repeated-state counterexample to applying the frozen identity to online updates. Saved results contain the exact fractions.
Next#
The deep Q-network note replaces separate table entries by a function of the state. This can transfer experience to related inputs, but it also changes stability and coverage questions. Keep the distinction between the behaviour that generates data and the target used in an update when reading about replay and target networks.
References#
The sources below support definitions and mathematical conditions. No source task, figure, code, dataset or reported experiment is used as the numerical case in this note.
- P. Auer, N. Cesa-Bianchi, P. Fischer. Finite-time Analysis of the Multiarmed Bandit Problem. Machine Learning 47, 235–256, 2002. §2, Theorem 1: UCB1 for bounded independent stationary rewards.
- R. S. Sutton. Learning to Predict by the Methods of Temporal Differences. Machine Learning 3, 9–44, 1988. §§2.2–2.3 and 5.1–5.2: temporal differences, traces, cumulative rewards and within-sequence updates.
- C. J. C. H. Watkins, P. Dayan. Q-learning. Machine Learning 8, 279–292, 1992. §2 and the theorem on p. 282: finite discounted tabular convergence.
- T. Jaakkola, M. I. Jordan, S. P. Singh. Convergence of Stochastic Iterative Dynamic Programming Algorithms. Advances in Neural Information Processing Systems 6, 703–710, 1993. Stochastic-approximation conditions and TD prediction.
- S. Singh, T. Jaakkola, M. L. Littman, C. Szepesvári. Convergence Results for Single-Step On-Policy Reinforcement-Learning Algorithms. Machine Learning 39, 287–308, 2000. §2 and §3: GLIE and persistent rank-based exploration; Theorems 1–2.