Chapter 01 · Part 1: Estimating from experience
Returns are random variables
A reinforcement learning problem is a data-generating process; the return is a random variable, value is its mean, and the Bellman equation is the law of total expectation.
Most of what you already know about statistics starts from a fixed distribution and a sample drawn from it. You estimate the mean, attach a standard error, test a hypothesis. This chapter sets up the one change that defines reinforcement learning (RL): the distribution you sample from depends on what you do, and what you want to estimate is the long-run payoff of a way of behaving. Everything is defined from scratch, with the statistician's names attached, and then checked against a simulation you can run.
What is an MDP, seen as a data-generating process?
An environment is something you interact with over discrete time steps . At each step it is in a state drawn from a set . You choose an action from a set . The environment then emits a reward (a real number) and a next state . The reward that follows is , which is Sutton and Barto's convention (Sutton and Barto, 2018) and the one used in this course.
A Markov decision process says how the environment generates : through a fixed conditional distribution
called the dynamics. The word "Markov" is the conditional-independence assumption: given , the pair is independent of everything earlier. The state is whatever you need to condition on to make that true.
If you remove the actions, this is a Markov chain with rewards attached to transitions. With actions, it is a family of Markov chains indexed by how you choose them. That is the first statistical reading: an MDP is a generative model with a design variable. For each choice of design (the policy, below) it defines a joint distribution over sequences, and everything in RL is a functional of that distribution.
An MDP is fully specified by , , and a discount factor that we meet below. In RL proper, is unknown to the learner. It can only draw samples from it by acting.
What are a policy, a trajectory and a return?
A policy is a conditional distribution over actions given the current state. It is a randomised decision rule in the sense of decision theory, restricted to depend on the present state only. A deterministic policy puts all its mass on one action per state. Fixing fixes the sampling distribution completely: the pair determines the law of the whole sequence
called a trajectory (or episode, when it ends). Its probability factorises as a product of policy terms and dynamics terms,
where is the distribution of the start state. The two kinds of factor are different in kind: the factors are chosen by you and known exactly, the factors are given by nature and (in RL) unknown. Chapter 6 on off-policy evaluation is built entirely on this split.
Many tasks end: the agent reaches a goal or falls into a pit. We handle that by adding terminal states that are absorbing and pay reward zero forever. Then every trajectory is formally infinite, and the sums below are well defined.
The return from step is the discounted sum of everything that happens after :
The discount factor down-weights rewards that arrive later. It has two readings. As a modelling choice, it says a reward now is worth more than a reward later. As a technical device, it makes the series converge when rewards are bounded: if then . With near the agent is short-sighted, with near it counts the far future almost fully.
The return satisfies a recursion that does all the work in this chapter:
The key sentence of this chapter: is a function of the trajectory, and the trajectory is random, so is a random variable. It has a distribution, and that distribution has a mean, a variance, a skewness, quantiles. Different starting states and different policies give different distributions. RL's usual objective, the mean of that distribution, is a choice, not a necessity. Chapter 9 on uncertainty and distributions returns to the whole distribution.
What are the value and the q-value?
The state value of is the conditional mean of the return, starting from and following :
The subscript says the expectation is over trajectories generated by and . Because the dynamics are time-homogeneous, this does not depend on .
The action value (q-value) conditions additionally on the first action, which is then not drawn from ; later actions are:
So is a regression function of the return on the start state, and is the regression function on the start state and first action. The learning problems of chapters 4 to 7 are all of the form "estimate this regression function from sampled trajectories".
Why is the Bellman equation the law of total expectation?
Take the recursion (1) and condition on :
Now apply the law of total expectation, conditioning first on the action and then on the pair . The probability of the action is , and the probability of the pair is . By the Markov property, once we know the future return no longer depends on , or , so . Therefore
This is the Bellman expectation equation. In terms of it reads , with .
Nothing in the derivation is specific to RL. It is with and the first step. The only RL content is the observation that the inner expectation of the tail of the return is the same function evaluated at the next state. That self-reference is what makes the equation a fixed-point equation.
When is finite, collect into a vector, let be the state-to-state transition matrix under , and let be the expected one-step reward. Then (2) is the linear system
The inverse exists because is a stochastic matrix, so all its eigenvalues have modulus at most 1, and puts all eigenvalues of strictly inside the unit disc. Equivalently, , the discounted expected number of visits. For small problems, this is the answer key: when you know , no sampling is needed, and we can use it to check what sampling does.
Worked example by hand
Take two transient states and and a terminal state , a fixed policy (so we only need the induced chain) and . The induced dynamics, with rewards attached to transitions, are:
- From : with probability go to with reward ; with probability go to with reward .
- From : with probability go to with reward ; with probability go to with reward .
Write (2) at each state, with :
Substituting the second into the first gives , so
Check against the definition: from the immediate payoff is half the time, and otherwise you land in and expect of discounted return. Then . ✓.
The return from is not . It is with probability (end immediately), and otherwise some random value built from how many times the chain bounces between and . The mean is a summary, and a poor description of any one trajectory. A small piece of the variance can be read off at once: conditional on the first step, has conditional mean (go to ) or (go to ), each with probability . The variance between those two groups is . The rest of the variance of lives within the groups, and the next section accounts for it.
Is there a Bellman equation for the variance?
Yes, and it is the law of total variance. Let . Condition on the first step . Given that triple, has conditional mean and conditional variance . The law of total variance, , gives
The first term is the between part, the variance of the one-step "target" around its mean . The second is the within part: the variance still to come, shrunk by . In vector form , which is another linear system, solved the same way. This recursion for the variance (and for higher moments) of the discounted reward of a Markov decision process is due to Sobel (1982), and is the starting point of the risk-sensitive RL literature, which optimises a trade-off between mean and variance. The same recursion is what makes TD learning's targets lower-variance than Monte Carlo's in chapter 5: the term is exactly the variance that a one-step bootstrapped target does not have to pay for.
Why is RL "estimation plus decision under feedback"?
If is fixed and we only want , the problem is estimation, and a statistician would find it familiar. Draw trajectories, average returns, report an interval. This is policy evaluation, the subject of Part 2.
But RL's actual goal is to find a policy with high value, and that adds three things that textbook estimation does not have.
- The design is chosen by the analyst, sequentially, using the data so far. Which state-action pairs you observe depends on your policy. A policy that never visits state yields no data about .
- The samples are dependent. Consecutive states along one trajectory are correlated (the Markov chain's autocorrelation), and, when the policy is adapted to the data, the choice of design depends on earlier outcomes. Standard i.i.d. results do not apply, and we should say which assumptions we still have. A fresh trajectory started from under a fixed gives an i.i.d. draw of ; that is what the experiment below uses.
- The target is a functional of the control. We estimate , but we are also trying to change to make it larger. What we are estimating moves while we estimate it.
The learner therefore faces two coupled problems: estimating values from the data it has, and deciding which data to collect next. When there is a single state, so no future to worry about, the problem reduces to the multi-armed bandit, which is the subject of the next chapter: bandits as sequential experiments. The full RL problem adds consequences: an action changes not only today's reward but the state you will be in tomorrow.
Experiment: the return distribution of a slippery corridor
The companion code, ch01_returns.py, builds a tiny MDP and does what this chapter describes. The corridor has six states in a row. States and are terminal. From any other state the agent chooses left or right; the chosen move happens with probability , and with probability the agent slips and moves the other way. Every move costs , landing on pays a bonus of , and landing on (a pit) costs an extra . The policy goes right with probability and left with probability , in every state. The start state is .
The script (1) solves the linear system exactly for and for the return variance via (3); (2) simulates independent episodes and compares; (3) prints a histogram; (4) checks the Bellman identity and the within/between split numerically; (5) checks that a t-interval from sampled returns covers about of the time; and (6) varies the policy.
Here is what it prints, verbatim.
MDP: corridor of 6 states (0 and 5 terminal), start state 2, slip prob 0.2
Policy pi: right with prob 0.6, left with prob 0.4, in every state
1. Return from state 2: Monte Carlo vs exact (N = 200000 episodes)
gamma v exact MC mean MC se sd exact MC sd skew
0.99 -2.8648 -2.8539 0.0170 7.5883 7.5971 -0.290
0.90 -2.6077 -2.6026 0.0114 5.1094 5.1141 0.411
0.50 -1.8540 -1.8558 0.0033 1.4731 1.4713 0.371
2. Empirical distribution of G_0 from state 2, gamma = 0.9 (proportion of episodes)
[ -9.99, -8.89) 0.031 ######
[ -8.89, -7.79) 0.083 ##################
[ -7.79, -6.69) 0.165 ###################################
[ -6.69, -5.59) 0.217 ##############################################
[ -5.59, -4.50) 0.023 #####
[ -4.50, -3.40) 0.000
[ -3.40, -2.30) 0.035 ########
[ -2.30, -1.20) 0.055 ############
[ -1.20, -0.10) 0.000
[ -0.10, 1.00) 0.084 ##################
[ 1.00, 2.09) 0.000
[ 2.09, 3.19) 0.129 ###########################
[ 3.19, 4.29) 0.000
[ 4.29, 5.39) 0.177 ######################################
mean -2.604 (v_pi = -2.608), median -4.634
3. Exact v_pi and sd of the return by start state (gamma = 0.9)
state v_pi sd(G)
1 -4.5143 3.6846
2 -2.6077 5.1094
3 0.3570 6.0370
4 4.7414 6.0059
4. Bellman expectation equation as the law of total expectation, state 2
q(2,left) = -4.1860 q(2,right) = -1.5555
sum_a pi(a|2) q(2,a) = -2.6077 v_pi(2) = -2.6077
rbar(2) + gamma * sum_s' P(s'|2) v(s') = -2.6077
Var(G_0) = within 21.3703 + between 4.7360 = 26.1063 (exact 26.1063)
5. Coverage of a 95% t-interval for v_pi(2) from n sampled returns (2000 repetitions)
n coverage mean width
10 0.938 7.177
30 0.952 3.811
200 0.949 1.426
6. The data distribution depends on the policy (gamma = 0.9, start state 2)
P(right) v_pi(2) sd(G) P(reach 5)
0.1 -6.5252 2.0468 0.039
0.4 -4.9791 4.2861 0.266
0.6 -2.6077 5.1094 0.540
0.9 1.5703 4.2363 0.882The Monte Carlo mean matches the exact solution. In table 1, at each the sampled mean is within about one standard error of computed by solving . For the difference is against a standard error of . That is the law of large numbers doing what it should, and it confirms that the equation we solved and the process we simulated are the same object. The sampled standard deviations match the square root of the solution to (3) as well.
The mean is not a typical outcome. The histogram is bimodal. There is a large mass of returns below , mostly episodes that slide into the pit quickly, and a second cluster between and from episodes that reach the goal quickly; long wanderings that end at the goal land in between. The value sits in the valley, where only about of episodes fall (the bins from to ), and the median () is far from the mean. A policy evaluated only by its mean tells you nothing about this shape. Two caveats on reading the histogram: the return takes only countably many values (it is determined by the path length and the end state), so the empty bins are real gaps and not sampling noise, and the bin edges split those atoms somewhat arbitrarily.
The discount factor changes the distribution, not just its scale. Moving from to multiplies the standard deviation by about five, because a longer effective horizon accumulates more randomness, and the skewness changes sign. A single "value" number hides this. Looking ahead to chapter 5, a larger also means higher-variance return samples, which is why acts as a bias-variance knob when you bootstrap.
The Bellman identity holds exactly. Table 4 shows the law of total expectation twice: , and the one-step expansion gives the same number. It also splits into within and between. Most of the variance is still to come after the first step, which is why long horizons are expensive in return variance.
The returns are i.i.d., so the usual interval works. Each episode restarts from state under a fixed , so the returns are i.i.d. draws from a skewed, bimodal distribution with finite variance. The t-interval covers in of repetitions at (a small undercoverage, as one expects with skew), and , at and . Everything you know about sample means applies, with one qualifier: this holds because the policy is fixed and the episodes are independent. Chapter 4 on Monte Carlo evaluation covers what happens when we reuse several visits to the same state within one trajectory.
The policy is part of the data-generating process. In table 6, changing from to moves the value from to , and the probability of ever reaching the goal from to . The spread also changes (the standard deviation of the return is largest at the middle policy). A learner that alters its policy while it collects data is sampling from a moving distribution: the first two chapters of the course are about the consequences.
Exercises
- (Pen and paper.) In the two-state example, compute exactly, using (3). You need too, so write both equations in the unknowns and and solve the pair. Check that your "between" term at matches the computed above.
- (Pen and paper.) Show that is invertible for by writing the Neumann series and bounding its entries. What changes at in the corridor, where terminal states are absorbing?
- (Change the code and predict.) Set the slip probability to . What is the distribution of from state for the 0.6 policy? Predict whether the skewness stays positive, then run it. Does the Monte Carlo variance estimate stay equal to the exact one?
- (Change the code and predict.) Raise the pit penalty from to (change
- 5.0 * (s_next == 0)). Predict, for , the direction of change in the mean, the standard deviation, and the coverage of the interval. Then run it. - (Think.) The policy in table 6 has a higher value than the policy but is not necessarily the best policy. Why can't we conclude from four rows that going right with certainty is optimal, and what would we need to compute?
Sources
- Richard S. Sutton and Andrew G. Barto (2018). Reinforcement Learning: An Introduction, 2nd edition. MIT Press. Chapter 3 (finite MDPs, returns, value functions, Bellman equation).
- Matthew J. Sobel (1982). The variance of discounted Markov decision processes. Journal of Applied Probability 19(4), 794–802.
- Tor Lattimore and Csaba Szepesvári (2020). Bandit Algorithms. Cambridge University Press. Background for the bandit special case.