RLS RL, Read as Statistics

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 t=0,1,2,…t = 0, 1, 2, \dots. At each step it is in a state StS_t drawn from a set S\mathcal{S}. You choose an action AtA_t from a set A\mathcal{A}. The environment then emits a reward Rt+1R_{t+1} (a real number) and a next state St+1S_{t+1}. The reward that follows AtA_t is Rt+1R_{t+1}, 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 (St+1,Rt+1)(S_{t+1}, R_{t+1}): through a fixed conditional distribution

p(s′,r∣s,a)=Pr⁡(St+1=s′, Rt+1=r∣St=s, At=a),p(s', r \mid s, a) = \Pr(S_{t+1} = s',\, R_{t+1} = r \mid S_t = s,\, A_t = a),

called the dynamics. The word "Markov" is the conditional-independence assumption: given (St,At)(S_t, A_t), the pair (St+1,Rt+1)(S_{t+1}, R_{t+1}) 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 S\mathcal{S}, A\mathcal{A}, pp and a discount factor γ∈[0,1)\gamma \in [0, 1) that we meet below. In RL proper, pp 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 π(a∣s)\pi(a \mid s) 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 π\pi fixes the sampling distribution completely: the pair (π,p)(\pi, p) determines the law of the whole sequence

τ=(S0,A0,R1,S1,A1,R2,… ),\tau = (S_0, A_0, R_1, S_1, A_1, R_2, \dots),

called a trajectory (or episode, when it ends). Its probability factorises as a product of policy terms and dynamics terms,

Pr⁡(τ)=μ0(S0)∏t≥0π(At∣St) p(St+1,Rt+1∣St,At),\Pr(\tau) = \mu_0(S_0) \prod_{t \ge 0} \pi(A_t \mid S_t)\, p(S_{t+1}, R_{t+1} \mid S_t, A_t),

where μ0\mu_0 is the distribution of the start state. The two kinds of factor are different in kind: the π\pi factors are chosen by you and known exactly, the pp 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 tt is the discounted sum of everything that happens after tt:

Gt=∑k=0∞γkRt+k+1=Rt+1+γRt+2+γ2Rt+3+⋯ .G_t = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1} = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots .

The discount factor γ∈[0,1)\gamma \in [0,1) 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 ∣R∣≤Rmax⁡\lvert R \rvert \le R_{\max} then ∣Gt∣≤Rmax⁡/(1−γ)\lvert G_t \rvert \le R_{\max}/(1-\gamma). With γ\gamma near 00 the agent is short-sighted, with γ\gamma near 11 it counts the far future almost fully.

The return satisfies a recursion that does all the work in this chapter:

Gt=Rt+1+γ Gt+1.(1)G_t = R_{t+1} + \gamma\, G_{t+1}. \tag{1}

The key sentence of this chapter: GtG_t is a function of the trajectory, and the trajectory is random, so GtG_t 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 π\pi is the conditional mean of the return, starting from ss and following π\pi:

vπ(s)=Eπ[Gt∣St=s].v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s].

The subscript π\pi says the expectation is over trajectories generated by π\pi and pp. Because the dynamics are time-homogeneous, this does not depend on tt.

The action value (q-value) conditions additionally on the first action, which is then not drawn from π\pi; later actions are:

qπ(s,a)=Eπ[Gt∣St=s,At=a].q_\pi(s, a) = \mathbb{E}_\pi[G_t \mid S_t = s, A_t = a].

So vπ(s)v_\pi(s) is a regression function of the return on the start state, and qπ(s,a)q_\pi(s,a) 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 St=sS_t = s:

vπ(s)=Eπ[Rt+1+γGt+1∣St=s].v_\pi(s) = \mathbb{E}_\pi[R_{t+1} + \gamma G_{t+1} \mid S_t = s].

Now apply the law of total expectation, conditioning first on the action AtA_t and then on the pair (St+1,Rt+1)(S_{t+1}, R_{t+1}). The probability of the action is π(a∣s)\pi(a \mid s), and the probability of the pair is p(s′,r∣s,a)p(s', r \mid s, a). By the Markov property, once we know St+1=s′S_{t+1} = s' the future return no longer depends on ss, aa or rr, so E[Gt+1∣St+1=s′,St=s,At=a,Rt+1=r]=vπ(s′)\mathbb{E}[G_{t+1} \mid S_{t+1} = s', S_t = s, A_t = a, R_{t+1} = r] = v_\pi(s'). Therefore

vπ(s)=∑aπ(a∣s)∑s′,rp(s′,r∣s,a) [r+γ vπ(s′)].(2)v_\pi(s) = \sum_{a} \pi(a \mid s) \sum_{s', r} p(s', r \mid s, a)\,\big[r + \gamma\, v_\pi(s')\big]. \tag{2}

This is the Bellman expectation equation. In terms of qπq_\pi it reads vπ(s)=∑aπ(a∣s) qπ(s,a)v_\pi(s) = \sum_a \pi(a \mid s)\, q_\pi(s, a), with qπ(s,a)=∑s′,rp(s′,r∣s,a)[r+γvπ(s′)]q_\pi(s,a) = \sum_{s', r} p(s', r \mid s, a)[r + \gamma v_\pi(s')].

Nothing in the derivation is specific to RL. It is E[Y]=E[E[Y∣X]]\mathbb{E}[Y] = \mathbb{E}[\mathbb{E}[Y \mid X]] with Y=Rt+1+γGt+1Y = R_{t+1} + \gamma G_{t+1} and XX the first step. The only RL content is the observation that the inner expectation of the tail of the return is the same function vπv_\pi evaluated at the next state. That self-reference is what makes the equation a fixed-point equation.

When S\mathcal{S} is finite, collect vπv_\pi into a vector, let Pπ[s,s′]=∑aπ(a∣s)∑rp(s′,r∣s,a)P_\pi[s, s'] = \sum_a \pi(a \mid s) \sum_r p(s', r \mid s, a) be the state-to-state transition matrix under π\pi, and let rπ[s]=∑aπ(a∣s)∑s′,rr p(s′,r∣s,a)r_\pi[s] = \sum_a \pi(a \mid s)\sum_{s', r} r\, p(s', r \mid s, a) be the expected one-step reward. Then (2) is the linear system

vπ=rπ+γPπvπ⟺vπ=(I−γPπ)−1rπ.v_\pi = r_\pi + \gamma P_\pi v_\pi \quad\Longleftrightarrow\quad v_\pi = (I - \gamma P_\pi)^{-1} r_\pi .

The inverse exists because PπP_\pi is a stochastic matrix, so all its eigenvalues have modulus at most 1, and γ<1\gamma < 1 puts all eigenvalues of γPπ\gamma P_\pi strictly inside the unit disc. Equivalently, (I−γPπ)−1=∑kγkPπk(I-\gamma P_\pi)^{-1} = \sum_k \gamma^k P_\pi^k, the discounted expected number of visits. For small problems, this is the answer key: when you know pp, no sampling is needed, and we can use it to check what sampling does.

Worked example by hand

Take two transient states AA and BB and a terminal state TT, a fixed policy (so we only need the induced chain) and γ=0.9\gamma = 0.9. The induced dynamics, with rewards attached to transitions, are:

  • From AA: with probability 0.50.5 go to BB with reward 00; with probability 0.50.5 go to TT with reward 22.
  • From BB: with probability 0.60.6 go to AA with reward 11; with probability 0.40.4 go to TT with reward 00.

Write (2) at each state, with v(T)=0v(T) = 0:

v(A)=0.5 (0+0.9 v(B))+0.5 (2+0)=1+0.45 v(B),v(B)=0.6 (1+0.9 v(A))+0.4 (0+0)=0.6+0.54 v(A).\begin{aligned} v(A) &= 0.5\,(0 + 0.9\, v(B)) + 0.5\,(2 + 0) = 1 + 0.45\, v(B),\\ v(B) &= 0.6\,(1 + 0.9\, v(A)) + 0.4\,(0 + 0) = 0.6 + 0.54\, v(A). \end{aligned}

Substituting the second into the first gives v(A)=1+0.45(0.6+0.54 v(A))=1.27+0.243 v(A)v(A) = 1 + 0.45(0.6 + 0.54\, v(A)) = 1.27 + 0.243\, v(A), so

v(A)=1.270.757≈1.678,v(B)=0.6+0.54×1.678≈1.506.v(A) = \frac{1.27}{0.757} \approx 1.678, \qquad v(B) = 0.6 + 0.54 \times 1.678 \approx 1.506 .

Check against the definition: from AA the immediate payoff is 22 half the time, and otherwise you land in BB and expect 0.9×1.506≈1.3550.9 \times 1.506 \approx 1.355 of discounted return. Then 0.5×2+0.5×1.355≈1.6780.5 \times 2 + 0.5 \times 1.355 \approx 1.678. ✓.

The return from AA is not 1.6781.678. It is 22 with probability 0.50.5 (end immediately), and otherwise some random value built from how many times the chain bounces between AA and BB. 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, G0G_0 has conditional mean 22 (go to TT) or 0.9×1.506≈1.3550.9 \times 1.506 \approx 1.355 (go to BB), each with probability 0.50.5. The variance between those two groups is 0.25×(2−1.355)2≈0.1040.25 \times (2 - 1.355)^2 \approx 0.104. The rest of the variance of G0G_0 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 Vπ(s)=Var⁡π(Gt∣St=s)V_\pi(s) = \operatorname{Var}_\pi(G_t \mid S_t = s). Condition on the first step (At,St+1,Rt+1)(A_t, S_{t+1}, R_{t+1}). Given that triple, Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1} has conditional mean Rt+1+γvπ(St+1)R_{t+1} + \gamma v_\pi(S_{t+1}) and conditional variance γ2Vπ(St+1)\gamma^2 V_\pi(S_{t+1}). The law of total variance, Var⁡(Y)=E[Var⁡(Y∣X)]+Var⁡(E[Y∣X])\operatorname{Var}(Y) = \mathbb{E}[\operatorname{Var}(Y \mid X)] + \operatorname{Var}(\mathbb{E}[Y \mid X]), gives

Vπ(s)=Eπ ⁣[(Rt+1+γvπ(St+1)−vπ(s))2∣St=s]⏟variance of the one-step target  +  γ2 Eπ ⁣[Vπ(St+1)∣St=s].(3)V_\pi(s) = \underbrace{\mathbb{E}_\pi\!\big[(R_{t+1} + \gamma v_\pi(S_{t+1}) - v_\pi(s))^2 \mid S_t = s\big]}_{\text{variance of the one-step target}} \;+\; \gamma^2\, \mathbb{E}_\pi\!\big[V_\pi(S_{t+1}) \mid S_t = s\big]. \tag{3}

The first term is the between part, the variance of the one-step "target" Rt+1+γvπ(St+1)R_{t+1} + \gamma v_\pi(S_{t+1}) around its mean vπ(s)v_\pi(s). The second is the within part: the variance still to come, shrunk by γ2\gamma^2. In vector form Vπ=σπ+γ2PπVπV_\pi = \sigma_\pi + \gamma^2 P_\pi V_\pi, 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 γ2E[Vπ(St+1)]\gamma^2 \mathbb{E}[V_\pi(S_{t+1})] 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 π\pi is fixed and we only want vπv_\pi, 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.

  1. 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 ss yields no data about vπ(s)v_\pi(s).
  2. 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 ss under a fixed π\pi gives an i.i.d. draw of GtG_t; that is what the experiment below uses.
  3. The target is a functional of the control. We estimate vπv_\pi, but we are also trying to change π\pi 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 00 and 55 are terminal. From any other state the agent chooses left or right; the chosen move happens with probability 0.80.8, and with probability 0.20.2 the agent slips and moves the other way. Every move costs 11, landing on 55 pays a bonus of 1010, and landing on 00 (a pit) costs an extra 55. The policy π\pi goes right with probability 0.60.6 and left with probability 0.40.4, in every state. The start state is 22.

The script (1) solves the linear system exactly for vπv_\pi and for the return variance via (3); (2) simulates 200,000200{,}000 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 nn sampled returns covers vπ(2)v_\pi(2) about 95%95\% of the time; and (6) varies the policy.

Here is what it prints, verbatim.

Output
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.882

The Monte Carlo mean matches the exact solution. In table 1, at each γ\gamma the sampled mean is within about one standard error of vπ(2)v_\pi(2) computed by solving (I−γPπ)v=rπ(I - \gamma P_\pi)v = r_\pi. For γ=0.9\gamma = 0.9 the difference is 0.0050.005 against a standard error of 0.0110.011. 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 −5.5-5.5, mostly episodes that slide into the pit quickly, and a second cluster between 22 and 5.45.4 from episodes that reach the goal quickly; long wanderings that end at the goal land in between. The value −2.6-2.6 sits in the valley, where only about 9%9\% of episodes fall (the bins from −3.4-3.4 to −1.2-1.2), and the median (−4.63-4.63) 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 γ=0.5\gamma = 0.5 to 0.990.99 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 γ\gamma also means higher-variance return samples, which is why γ\gamma acts as a bias-variance knob when you bootstrap.

The Bellman identity holds exactly. Table 4 shows the law of total expectation twice: ∑aπ(a∣2) qπ(2,a)=vπ(2)\sum_a \pi(a \mid 2)\, q_\pi(2, a) = v_\pi(2), and the one-step expansion rˉ(2)+γ∑s′Pπ(s′∣2) vπ(s′)\bar r(2) + \gamma\sum_{s'} P_\pi(s' \mid 2)\, v_\pi(s') gives the same number. It also splits Var⁡(G0)=26.11\operatorname{Var}(G_0) = 26.11 into 21.3721.37 within and 4.744.74 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 22 under a fixed π\pi, so the returns are i.i.d. draws from a skewed, bimodal distribution with finite variance. The 95%95\% t-interval covers vπ(2)v_\pi(2) in 93.8%93.8\% of repetitions at n=10n = 10 (a small undercoverage, as one expects with skew), and 95.2%95.2\%, 94.9%94.9\% at n=30n = 30 and 200200. 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 P(right)P(\text{right}) from 0.10.1 to 0.90.9 moves the value from −6.5-6.5 to +1.6+1.6, and the probability of ever reaching the goal from 4%4\% to 88%88\%. 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

  1. (Pen and paper.) In the two-state example, compute Var⁡(G0∣S0=A)\operatorname{Var}(G_0 \mid S_0 = A) exactly, using (3). You need V(B)V(B) too, so write both equations in the unknowns V(A)V(A) and V(B)V(B) and solve the pair. Check that your "between" term at AA matches the 0.1040.104 computed above.
  2. (Pen and paper.) Show that (I−γPπ)(I - \gamma P_\pi) is invertible for γ<1\gamma < 1 by writing the Neumann series ∑kγkPπk\sum_k \gamma^k P_\pi^k and bounding its entries. What changes at γ=1\gamma = 1 in the corridor, where terminal states are absorbing?
  3. (Change the code and predict.) Set the slip probability to 00. What is the distribution of G0G_0 from state 22 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?
  4. (Change the code and predict.) Raise the pit penalty from −5-5 to −20-20 (change - 5.0 * (s_next == 0)). Predict, for γ=0.9\gamma = 0.9, the direction of change in the mean, the standard deviation, and the coverage of the n=10n = 10 interval. Then run it.
  5. (Think.) The P(right)=0.9P(\text{right}) = 0.9 policy in table 6 has a higher value than the 0.60.6 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