These are my notes on Chapters 1–5 of Shiyu Zhao's Mathematical Foundations of Reinforcement Learning [1], which cover the foundations of reinforcement learning: from the Bellman equation, through dynamic programming, to the first model-free algorithms. The skeleton and the derivations are mine; the examples follow the book, and I recomputed every number in the figures.
The post follows my handwritten notes (PDF, 28 pages), with a few mistakes in them corrected here.
Prerequisites are Linear Algebra and Probability Theory.
Reinforcement learning studies an agent that learns how to act by interacting with an environment. This post builds up the basic theory in four steps:
- The Bellman equation: how good is a given policy?
- The Bellman optimality equation: what is the best policy, and does it exist?
- Value iteration and policy iteration: how do we compute it when the model is known?
- Monte Carlo methods: how do we learn it when the model is unknown?
1. Basic Concepts and the Bellman Equation
This section sets up the language (Markov decision processes), defines how good a policy is (state values), and derives the equation that computes it (the Bellman equation).
1.1 Basic concepts
The running example is a robot (the agent) in a grid. Orange cells are forbidden (the agent may enter them but is punished) and the blue cell is the target.
Everything is packed into a Markov decision process (MDP):
- Sets: states \(\mathcal{S}\) (here the cells), actions \(\mathcal{A}(s)\) (here up, right, down, left, stay) and rewards \(\mathcal{R}(s,a)\).
- Model: the transition probabilities \(p(s'\,|\,s,a)\) and reward probabilities \(p(r\,|\,s,a)\). In the grid, moving into the boundary bounces the agent back, and the rewards are \(r_{\text{boundary}} = r_{\text{forbidden}} = -1\), \(r_{\text{target}} = 1\) (including staying at the target), and \(0\) otherwise.
- Policy: \(\pi(a\,|\,s)\), the probability of taking \(a\) in \(s\). We draw policies as arrows (a circle means "stay").
- Markov property: the next state and reward depend only on the current state and action, \(p(s_{t+1}\,|\,s_t, a_t, s_{t-1}, \dots, s_0, a_0) = p(s_{t+1}\,|\,s_t, a_t)\), and likewise for \(r_{t+1}\).
Following a policy produces a trajectory of states, actions and rewards. Its quality is not the immediate reward but the rewards collected in the long run. Since an agent that stays at the target collects \(+1\) forever, we sum the rewards with a discount rate \(\gamma \in (0,1)\):
The discounted return is always finite (at most \(r_{\max}/(1-\gamma)\)), and \(\gamma\) sets how far the agent looks ahead: a small \(\gamma\) makes it short-sighted, a \(\gamma\) close to \(1\) far-sighted. Policy 1 has the larger return, which agrees with the intuition that it is the better policy.
A trajectory that stops at a terminal state is an episode. We never really stop: the target is treated as an ordinary state with all five actions, and the agent learns by itself that staying there is best. This way episodic and continuing tasks are handled in the same framework.
1.2 State values
With time steps \(t = 0, 1, 2, \dots\), the agent in state \(S_t\) takes \(A_t\), then receives \(R_{t+1}\) and moves to \(S_{t+1}\). The discounted return from time \(t\) is the random variable
\[ \begin{equation} G_t \doteq R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = R_{t+1} + \gamma\, G_{t+1}. \label{eq:Gt} \end{equation} \]When the policy or the model is random, a state leads to many trajectories, so we judge a policy by the expected return. This is the state value:
\[ \begin{equation} v_\pi(s) \doteq \mathbb{E}\,[\,G_t \,|\, S_t = s\,]. \label{eq:v} \end{equation} \]It depends on the starting state and on the policy, but not on \(t\), because the model and the policy do not change over time. If the policy and the model are deterministic, there is one trajectory per state and the state value is its return; otherwise it is the mean of the returns. A policy with larger state values is a better policy.
1.3 The Bellman equation
1.3.1 Derivation
Insert \(\eqref{eq:Gt}\) into \(\eqref{eq:v}\):
\[ v_\pi(s) = \underbrace{\mathbb{E}[R_{t+1}\,|\,S_t = s]}_{\text{immediate reward}} + \gamma\,\underbrace{\mathbb{E}[G_{t+1}\,|\,S_t = s]}_{\text{future rewards}} . \]The first term is computed by conditioning on the action:
\[ \mathbb{E}[R_{t+1}\,|\,S_t = s] = \sum_a \pi(a\,|\,s)\,\mathbb{E}[R_{t+1}\,|\,S_t = s, A_t = a] = \sum_a \pi(a\,|\,s) \sum_r p(r\,|\,s,a)\, r . \]The second by conditioning on the next state:
\[ \begin{aligned} \mathbb{E}[G_{t+1}\,|\,S_t = s] &= \sum_{s'} \mathbb{E}[G_{t+1}\,|\,S_t = s, S_{t+1} = s']\; p(s'\,|\,s) = \sum_{s'} \mathbb{E}[G_{t+1}\,|\,S_{t+1} = s']\; p(s'\,|\,s) && \text{(Markov property)} \\ &= \sum_{s'} v_\pi(s')\, p(s'\,|\,s) = \sum_{s'} v_\pi(s') \sum_a \pi(a\,|\,s)\, p(s'\,|\,s, a). \end{aligned} \]Together they give the Bellman equation:
\[ \begin{equation} v_\pi(s) = \sum_a \pi(a\,|\,s) \Big[ \sum_r p(r\,|\,s,a)\, r + \gamma \sum_{s'} p(s'\,|\,s,a)\, v_\pi(s') \Big] = \mathop{\mathbb{E}}_{a \sim \pi(\cdot|s)} \mathop{\mathbb{E}}_{r, s'}\big[\, r + \gamma\, v_\pi(s') \,\big], \qquad s \in \mathcal{S}. \label{eq:bellman} \end{equation} \]The first form uses the marginals \(p(r|s,a)\) and \(p(s'|s,a)\), the second the joint \(p(r, s'|s,a)\). They agree by linearity of expectation, whether or not \(r\) and \(s'\) are independent.
It is a system of \(|\mathcal{S}|\) equations in which the value of a state is expressed through the values of other states (bootstrapping). Solving it for a given \(\pi\) is called policy evaluation.
Example. On the \(2\times 2\) grid of Figure 3 (\(s_2\) forbidden, \(s_4\) target), take the policy that at \(s_1\) goes right or down with probability \(0.5\) each:
Solving from the bottom up gives \(v_\pi(s_2) = v_\pi(s_3) = v_\pi(s_4) = \frac{1}{1-\gamma}\) and \(v_\pi(s_1) = -0.5 + \frac{\gamma}{1-\gamma}\); with \(\gamma = 0.9\), \(v_\pi = (8.5, 10, 10, 10)\).
1.3.2 Matrix–vector form
Define the policy-averaged reward and transition probability
\[ r_\pi(s) \doteq \sum_a \pi(a\,|\,s) \sum_r p(r\,|\,s,a)\, r, \qquad p_\pi(s'\,|\,s) \doteq \sum_a \pi(a\,|\,s)\, p(s'\,|\,s,a). \]Stacking the equations of all \(n = |\mathcal{S}|\) states, with \([P_\pi]_{ij} = p_\pi(s_j\,|\,s_i)\),
\[ \begin{equation} v_\pi = r_\pi + \gamma P_\pi v_\pi \qquad\Longleftrightarrow\qquad (I - \gamma P_\pi)\, v_\pi = r_\pi . \label{eq:bellman-matrix} \end{equation} \]For the example above,
\[ \begin{bmatrix} v_\pi(s_1) \\ v_\pi(s_2) \\ v_\pi(s_3) \\ v_\pi(s_4) \end{bmatrix} = \begin{bmatrix} -0.5 \\ 1 \\ 1 \\ 1 \end{bmatrix} + \gamma \begin{bmatrix} 0 & 0.5 & 0.5 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} v_\pi(s_1) \\ v_\pi(s_2) \\ v_\pi(s_3) \\ v_\pi(s_4) \end{bmatrix}. \]\(P_\pi\) is nonnegative and each row sums to one (\(P_\pi \mathbf{1} = \mathbf{1}\)). Throughout the series, \(\ge\) between vectors or matrices is elementwise.
1.4 Solving the Bellman equation
1.4.1 \(I - \gamma P_\pi\) is invertible
A matrix is invertible if and only if \(0\) is not an eigenvalue, since \(\det A = \lambda_1 \lambda_2 \cdots \lambda_n\). To locate the eigenvalues we use the following theorem.
Gershgorin circle theorem [3]
Every eigenvalue of \(A \in \mathbb{C}^{n\times n}\) lies in at least one disc \(D_i = \big\{ z : |z - a_{ii}| \le \sum_{j\neq i} |a_{ij}| \big\}\).
Proof. Let \(A\mathbf{x} = \lambda\mathbf{x}\), \(\mathbf{x} \neq \mathbf{0}\), and pick \(i\) with \(|x_i| = \max_j |x_j|\). Row \(i\) gives \((\lambda - a_{ii})\, x_i = \sum_{j \neq i} a_{ij}\, x_j\), so \(|\lambda - a_{ii}|\,|x_i| \le \sum_{j\neq i} |a_{ij}|\,|x_i|\). Divide by \(|x_i| > 0\). \(\square\)
For \(I - \gamma P_\pi\), row \(i\) has diagonal entry \(1 - \gamma p_{ii}\), and its off-diagonal entries sum in absolute value to \(\gamma(1 - p_{ii})\). If \(0\) were an eigenvalue, then for some \(i\),
\[ 1 - \gamma p_{ii} \le \gamma (1 - p_{ii}) \quad\Longrightarrow\quad 1 \le \gamma , \]a contradiction. In fact, every disc lies to the right of \(\operatorname{Re} z = 1 - \gamma > 0\) (Figure 4).
1.4.2 The closed-form solution
Hence \(v_\pi = (I - \gamma P_\pi)^{-1} r_\pi\), and the inverse expands as a Neumann series:
\[ \begin{equation} (I - \gamma P_\pi)^{-1} = I + \gamma P_\pi + \gamma^2 P_\pi^2 + \cdots \label{eq:neumann} \end{equation} \]Proof. With \(A = \gamma P_\pi\) and \(S_n = I + A + \cdots + A^n\), we have \((I - A)S_n = I - A^{n+1}\). Diagonalizing \(A\) to show \(A^n \to 0\) does not work in general, since \(P_\pi\) need not be diagonalizable. Use the max-row-sum norm \(\|A\|_\infty = \max_i \sum_j |a_{ij}|\) instead: it is submultiplicative and \(\|P_\pi\|_\infty = 1\), so \(\|A^{n}\|_\infty \le \gamma^{n} \to 0\). \(\square\)
Every term of \(\eqref{eq:neumann}\) is nonnegative, so \((I - \gamma P_\pi)^{-1} \ge I \ge 0\). In particular, it preserves order: if \(r_1 \ge r_2\) then \((I - \gamma P_\pi)^{-1} r_1 \ge (I - \gamma P_\pi)^{-1} r_2\). This is used again and again in Sections 2 and 3.
The series also has a direct meaning. \([P_\pi^k]_{ij}\) is the probability of being in \(s_j\) exactly \(k\) steps after \(s_i\), so \([P_\pi^k r_\pi]_i = \mathbb{E}[R_{t+k+1}\,|\,S_t = s_i]\), and \(v_\pi = \sum_k \gamma^k P_\pi^k r_\pi\) is just \(\mathbb{E}[R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots]\), term by term.
1.4.3 The iterative solution
Inverting an \(n\times n\) matrix costs \(O(n^3)\). In practice we iterate from any \(v_0\):
\[ v_{k+1} = r_\pi + \gamma P_\pi v_k, \qquad k = 0, 1, 2, \dots \]The error \(\delta_k = v_k - v_\pi\) satisfies \(\delta_{k+1} = \gamma P_\pi \delta_k\), so \(\delta_k = (\gamma P_\pi)^k \delta_0\) and \(\|v_k - v_\pi\|_\infty \le \gamma^k \|v_0 - v_\pi\|_\infty \to 0\). The error shrinks by a factor \(\gamma\) per step from any start. From \(v_0 = 0\), \(v_k\) is the expected discounted sum of the first \(k\) rewards, a truncation of the Neumann series. This pattern, iterating a map that shrinks distances, returns in Section 2.2 as the contraction mapping theorem.
Figure 5 evaluates two policies on a \(5\times 5\) grid world (\(\gamma = 0.9\)). Under the good policy, the target is worth \(1/(1-\gamma) = 10\), and a state \(d \ge 1\) steps away is worth \(10\gamma^{d-1}\). Under "always move right", every value is negative.
1.5 Action values
To improve a policy we need to know how good each action is. The action value is the expected return after taking \(a\) in \(s\) and following \(\pi\) afterwards:
\[ q_\pi(s, a) \doteq \mathbb{E}\,[\,G_t \,|\, S_t = s, A_t = a\,]. \]Conditioning on the action, and comparing with the bracket in \(\eqref{eq:bellman}\), gives the two relations
\[ \begin{equation} v_\pi(s) = \sum_a \pi(a\,|\,s)\, q_\pi(s, a), \qquad q_\pi(s, a) = \sum_r p(r\,|\,s,a)\, r + \gamma \sum_{s'} p(s'\,|\,s,a)\, v_\pi(s'). \label{eq:q-v} \end{equation} \]For the example above (\(v_\pi = (8.5, 10, 10, 10)\)), the action values at \(s_1\) are \(6.65, 8, 9, 6.65, 7.65\) for up, right, down, left, stay, e.g. \(q_\pi(s_1, \text{down}) = 0 + \gamma v_\pi(s_3) = 9\), and indeed \(v_\pi(s_1) = 0.5 \cdot 8 + 0.5 \cdot 9 = 8.5\). Actions that the policy never takes still have values: take the action once, then follow \(\pi\). It is tempting to skip them or set them to zero, but that is wrong, because not being selected does not mean being bad; maybe the policy is the bad one. Here "down" is the best action at \(s_1\), which suggests changing the policy. This is the idea of Section 2.
Substituting the first relation (at \(s'\)) into the second gives the Bellman equation for action values:
\[ q_\pi(s,a) = \sum_r p(r\,|\,s,a)\,r + \gamma \sum_{s'} p(s'\,|\,s,a) \sum_{a'} \pi(a'\,|\,s')\, q_\pi(s', a'). \]In matrix form, stacking the \(nm\) pairs \((s_1,a_1), \dots, (s_n, a_m)\),
\[ q_\pi = \tilde r + \gamma\, P\, \Pi\, q_\pi, \qquad [\tilde r]_{(s,a)} = \sum_r p(r|s,a)\,r, \quad [P]_{(s,a),s'} = p(s'|s,a), \quad [\Pi]_{s,(s,a)} = \pi(a|s), \]where \(\Pi \in \mathbb{R}^{n\times nm}\) is block diagonal. \(P\Pi\) is the transition matrix between state–action pairs, again nonnegative with unit row sums, so \(q_\pi\) is unique by the same argument. The model sits in \(\tilde r\) and \(P\), the policy only in \(\Pi\), and \(v_\pi = \Pi q_\pi\), \(q_\pi = \tilde r + \gamma P v_\pi\).
2. The Bellman Optimality Equation
Section 1 evaluated a given policy. This section asks which policy is best. The answer is the Bellman optimality equation (BOE), and the tool to analyse it is the contraction mapping theorem.
2.1 Optimal policies and the BOE
In the \(2\times 2\) example of Section 1.5, the action values at \(s_1\) were largest for "down". Switching the policy at \(s_1\) to that action makes it better. This idea, select the action with the greatest action value, is behind most RL algorithms. To make it rigorous we first need to say what "best" means.
Definition (optimal policy)
A policy \(\pi^*\) is optimal if \(v_{\pi^*}(s) \ge v_\pi(s)\) for every state \(s\) and every policy \(\pi\). Its state values are the optimal state values.
This is a strong requirement: a single policy must win at every state simultaneously, and it is not obvious that one exists. Does such a policy exist? Is it unique? Is it deterministic? How do we find it? Intuitively, an optimal policy cannot be improved at any state, so its values should satisfy the Bellman equation with the policy chosen to maximize the right-hand side:
\[ \begin{equation} v(s) = \max_{\pi(\cdot|s)} \sum_a \pi(a\,|\,s)\, q(s,a), \qquad q(s,a) = \sum_r p(r\,|\,s,a)\, r + \gamma \sum_{s'} p(s'\,|\,s,a)\, v(s'). \label{eq:boe} \end{equation} \]This is the BOE. So far it is only a guess; the rest of this section shows that it is exactly right. Unlike the Bellman equation, it has two unknowns, \(v\) and \(\pi\). The trick is to solve for them one at a time. As a toy example, find \(x, y\) with \(x = \max_y (2x - 1 - y^2)\). Whatever \(x\) is, the maximum is at \(y = 0\) and equals \(2x - 1\), so \(x = 2x - 1\) and \(x = 1\).
In the BOE, likewise, hold \(v\) fixed. Then the \(q(s,a)\) are fixed numbers, and we maximize a weighted average of them. The best weights put everything on the largest number: since \(\sum_a \pi(a|s) = 1\),
\[ \sum_a \pi(a\,|\,s)\, q(s,a) \le \sum_a \pi(a\,|\,s) \max_{a'} q(s, a') = \max_{a} q(s,a), \]with equality for the greedy policy
\[ \begin{equation} \pi(a\,|\,s) = \begin{cases} 1, & a = a^*(s), \\ 0, & a \neq a^*(s), \end{cases} \qquad a^*(s) = \arg\max_a q(s,a). \label{eq:greedy} \end{equation} \]After this inner maximization, the right-hand side depends on \(v\) only. In matrix form, with \(r_\pi, P_\pi\) as in Section 1.3.2,
\[ v = f(v), \qquad f(v) \doteq \max_{\pi}\, (r_\pi + \gamma P_\pi v), \]where the maximum is elementwise; it is attained by a single policy (the greedy one), because row \(i\) depends only on \(\pi(\cdot|s_i)\). The BOE is a nonlinear equation \(v = f(v)\).
2.2 The contraction mapping theorem
A point with \(f(x^*) = x^*\) is a fixed point. The map \(f\) is a contraction if, for some \(\gamma \in (0,1)\),
\[ \|f(x_1) - f(x_2)\| \le \gamma\, \|x_1 - x_2\| \qquad \text{for all } x_1, x_2 . \]Any vector norm works; for the BOE we use \(\|x\|_\infty = \max_i |x_i|\). A vector norm induces the matrix norm \(\|A\| = \max_{x \neq 0} \|Ax\|/\|x\|\), so that \(\|Ax\| \le \|A\|\,\|x\|\). For the max norm it is the largest absolute row sum, \(\|A\|_\infty = \max_i \sum_j |a_{ij}|\). Some examples of contractions:
- \(f(x) = Ax\) with \(\|A\| \le \gamma < 1\), since \(\|Ax_1 - Ax_2\| \le \|A\|\,\|x_1 - x_2\|\);
- \(f(x) = 0.5\sin x\), since by the mean value theorem \(|0.5\sin x_1 - 0.5\sin x_2| = |0.5\cos\xi|\,|x_1 - x_2| \le 0.5|x_1 - x_2|\).
Theorem (contraction mapping theorem)
If \(f : \mathbb{R}^d \to \mathbb{R}^d\) is a contraction, then \(x = f(x)\) has a unique solution \(x^*\), and for any \(x_0\) the iteration \(x_{k+1} = f(x_k)\) converges to it, with \(\|x_k - x^*\| \le \frac{\gamma^k}{1-\gamma}\,\|x_1 - x_0\|\).
The theorem gives existence, uniqueness and an algorithm at once. In Figure 6, each step of the iteration goes up to the curve and across to the diagonal, and the staircase closes in on the intersection.
Proof. Since \(x^*\) is not known in advance, we show that \(\{x_k\}\) is a Cauchy sequence: for every \(\varepsilon > 0\) there is an \(N\) with \(\|x_m - x_n\| < \varepsilon\) for all \(m, n > N\). In \(\mathbb{R}^d\) every Cauchy sequence converges. Two remarks:
- The condition must hold for all pairs \(m, n > N\), not only for neighbours: \(\|x_{k+1} - x_k\| \to 0\) alone is not enough, since \(\sqrt{k}\) and \(\ln(k+1)\) have shrinking steps but diverge.
- "Cauchy implies convergent" is a property of the space, called completeness. \(\mathbb{R}^d\) is complete, but the rationals are not: \(3, 3.1, 3.14, 3.141, \dots\) is a Cauchy sequence of rationals whose limit \(\pi\) is irrational.
Convergence. By contraction, \(\|x_{k+1} - x_k\| \le \gamma\|x_k - x_{k-1}\| \le \cdots \le \gamma^k \|x_1 - x_0\|\). For \(m > n\), the triangle inequality gives
\[ \|x_m - x_n\| \le \sum_{k=n}^{m-1} \|x_{k+1} - x_k\| \le (\gamma^n + \cdots + \gamma^{m-1})\,\|x_1 - x_0\| \le \frac{\gamma^n}{1-\gamma}\,\|x_1 - x_0\| \longrightarrow 0, \]so the sequence is Cauchy and converges to some \(x^*\). Letting \(m \to \infty\) gives the error bound. In practice it says that the error falls below \(\varepsilon\) after about \(\log\big(\|x_1 - x_0\| / (\varepsilon(1-\gamma))\big) / \log(1/\gamma)\) steps. For the BOE, \(\gamma\) is the discount rate, so a far-sighted agent (\(\gamma\) close to \(1\)) needs many more iterations: with \(\gamma = 0.99\), each step only removes \(1\%\) of the error.
Fixed point. A contraction is continuous (\(\|f(x_k) - f(x^*)\| \le \gamma\|x_k - x^*\| \to 0\)), so \(f(x^*) = \lim f(x_k) = \lim x_{k+1} = x^*\).
Uniqueness. If \(x'\) is another fixed point, \(\|x' - x^*\| = \|f(x') - f(x^*)\| \le \gamma\|x' - x^*\|\), so \(x' = x^*\). \(\square\)
2.3 The BOE is a contraction
Theorem
\(\|f(v_1) - f(v_2)\|_\infty \le \gamma\, \|v_1 - v_2\|_\infty\), where \(\|x\|_\infty = \max_i |x_i|\).
Proof. Let \(\pi_1^*, \pi_2^*\) be the greedy policies for \(v_1, v_2\). Each maximizes its own right-hand side, so \(f(v_2) \ge r_{\pi_1^*} + \gamma P_{\pi_1^*} v_2\) and \(f(v_1) \ge r_{\pi_2^*} + \gamma P_{\pi_2^*} v_1\). Hence
\[ \gamma P_{\pi_2^*}(v_1 - v_2) \;\le\; f(v_1) - f(v_2) \;\le\; \gamma P_{\pi_1^*}(v_1 - v_2). \](For the upper bound, \(f(v_1) - f(v_2) \le (r_{\pi_1^*} + \gamma P_{\pi_1^*} v_1) - (r_{\pi_1^*} + \gamma P_{\pi_1^*} v_2)\); the lower bound is symmetric.) Let \(p_i^\top\) be row \(i\) of \(P_{\pi_1^*}\). It is a probability vector, so \(p_i^\top(v_1 - v_2)\) is a weighted average of the entries of \(v_1 - v_2\):
\[ |p_i^\top(v_1 - v_2)| \le p_i^\top |v_1 - v_2| \le \|v_1 - v_2\|_\infty , \]and the same holds for the rows of \(P_{\pi_2^*}\). So every entry of \(f(v_1) - f(v_2)\) is squeezed between two numbers in \([-\gamma\|v_1 - v_2\|_\infty, \gamma\|v_1 - v_2\|_\infty]\). \(\square\)
The discount rate is exactly the contraction factor, and \(\gamma < 1\) really matters. With \(\gamma = 1\), \(P_\pi \mathbf{1} = \mathbf{1}\) gives \(f(v + c\mathbf{1}) = f(v) + c\mathbf{1}\), so if \(v\) solved the BOE, so would \(v + c\mathbf{1}\) for every constant \(c\), and uniqueness would be lost.
2.4 Solving the BOE
By the contraction mapping theorem, the BOE has a unique solution \(v^*\), and \(v_{k+1} = \max_\pi (r_\pi + \gamma P_\pi v_k)\) converges to it from any \(v_0\). This algorithm is value iteration, studied in Section 3.1. Let \(\pi^* = \arg\max_\pi (r_\pi + \gamma P_\pi v^*)\). Then
\[ v^* = r_{\pi^*} + \gamma P_{\pi^*} v^*, \]which is the Bellman equation of \(\pi^*\), so \(v^* = v_{\pi^*}\): the BOE is the Bellman equation of a special policy. In the \(2\times 2\) example, \(v^* = (9, 10, 10, 10)\) for \(\gamma = 0.9\), and the greedy policy goes down at \(s_1\), down at \(s_2\), right at \(s_3\) and stays at \(s_4\), exactly the improvement suggested by the action values at the start of this section.
Theorem (optimality)
For every policy \(\pi\), \(v^* = v_{\pi^*} \ge v_\pi\). So \(v^*\) is the optimal state value and \(\pi^*\) is an optimal policy.
Proof. Since \(\pi^*\) attains the maximum, \(v^* \ge r_\pi + \gamma P_\pi v^*\). Subtracting \(v_\pi = r_\pi + \gamma P_\pi v_\pi\),
\[ v^* - v_\pi \ge \gamma P_\pi (v^* - v_\pi) \ge \gamma^2 P_\pi^2 (v^* - v_\pi) \ge \cdots \ge \gamma^n P_\pi^n (v^* - v_\pi) \to 0, \]using \(P_\pi \ge 0\) at each step, and \(\|\gamma^n P_\pi^n\|_\infty = \gamma^n \to 0\). (Equivalently, \((I - \gamma P_\pi)(v^* - v_\pi) \ge 0\), and \((I - \gamma P_\pi)^{-1} \ge 0\) from Section 1.4.2.) \(\square\)
With \(q^*(s,a) = \sum_r p(r|s,a)\, r + \gamma \sum_{s'} p(s'|s,a)\, v^*(s')\), the greedy policy \(a^*(s) = \arg\max_a q^*(s,a)\) is optimal. This answers the questions above:
- Existence: an optimal policy always exists: the greedy policy for the unique solution \(v^*\).
- Stochastic or deterministic: it can be either, but a deterministic optimal policy always exists.
- Algorithm: solve the BOE by value iteration, then act greedily with respect to \(q^*\).
- Uniqueness: \(v^*\) is unique, but the optimal policy need not be. If two actions tie for the maximum of \(q^*(s,\cdot)\), any split between them is optimal, including stochastic ones.
2.5 What shapes the optimal policy
The BOE depends on the model, the rewards and \(\gamma\). The model is fixed by the environment, so let us vary the other two (Figure 7).
- Discount rate. With \(\gamma = 0.9\) (a), the agent walks straight through a forbidden cell next to the target: paying \(-1\) once beats a long detour that delays all future \(+1\)'s. With \(\gamma = 0.5\) (b) it is more short-sighted and avoids every forbidden cell. With \(\gamma = 0\) (c) it only maximizes the immediate reward, so away from the target all zero-reward actions tie and the policy does not lead to the target. In all panels the values decrease with the distance to the target, since a longer path means more discounting.
- Reward values. With \(r_{\text{forbidden}} = -10\) (d), the agent avoids all forbidden cells.
Only the relative values of rewards matter:
Theorem (invariance)
Replacing every reward \(r\) by \(\alpha r + \beta\) with \(\alpha > 0\) gives the optimal value \(\alpha v^* + \frac{\beta}{1-\gamma}\mathbf{1}\), and the same optimal policies.
Proof. Now \(r_\pi \to \alpha r_\pi + \beta \mathbf{1}\). Plug \(v' = \alpha v^* + c\mathbf{1}\) into the new BOE and use \(P_\pi \mathbf{1} = \mathbf{1}\): \(\max_\pi(\alpha r_\pi + \beta\mathbf{1} + \gamma P_\pi v') = \alpha v^* + (\beta + \gamma c)\mathbf{1}\), which equals \(v'\) when \(c = \beta/(1-\gamma)\). By uniqueness this is the solution. The new action values are \(\alpha q^*(s,a) + \beta/(1-\gamma)\), which have the same maximizing actions. \(\square\)
The condition \(\alpha > 0\) matters: a negative \(\alpha\) turns rewards into costs and the maximum into a minimum. A practical consequence is that making all rewards negative by subtracting a constant does not change what the agent learns.
Finally, since ordinary steps cost nothing, would an optimal agent wander around before reaching the target? Should we add a reward of \(-1\) per step to make it hurry? Neither is needed. On a \(2\times 2\) grid with the target at \(s_4\), compare two ways to leave \(s_2\):
\[ \text{direct } (s_2 \to s_4)\text{: } 1 + \gamma + \gamma^2 + \cdots = \frac{1}{1-\gamma} = 10, \qquad \text{detour } (s_2 \to s_1 \to s_3 \to s_4)\text{: } 0 + 0 + \gamma^2 + \gamma^3 + \cdots = \frac{\gamma^2}{1-\gamma} = 8.1 . \]The detour is worse although none of its steps is punished: every step of delay multiplies all future rewards by \(\gamma\). And a \(-1\) per step is an affine change of the rewards, so by the invariance theorem it would not change the optimal policy anyway.
3. Value Iteration and Policy Iteration
Section 2 showed that the BOE \(v = \max_\pi (r_\pi + \gamma P_\pi v)\) has a unique solution. This section turns that into three algorithms. They all need the model \(p(r|s,a), p(s'|s,a)\), so they are dynamic programming algorithms, and they are the basis of the model-free methods of Section 4.
3.1 Value iteration
Value iteration is the fixed-point iteration \(v_{k+1} = \max_\pi (r_\pi + \gamma P_\pi v_k)\). By the contraction mapping theorem it converges from any \(v_0\), with \(\|v_k - v^*\|_\infty \le \frac{\gamma^k}{1-\gamma}\|v_1 - v_0\|_\infty\). Each step has two parts:
- Policy update: \(\pi_{k+1} = \arg\max_\pi\,(r_\pi + \gamma P_\pi v_k)\).
- Value update: \(v_{k+1} = r_{\pi_{k+1}} + \gamma P_{\pi_{k+1}} v_k\).
Elementwise, the policy update maximizes \(\sum_a \pi(a|s)\, q_k(s,a)\) with \(q_k(s,a) = \sum_r p(r|s,a)\,r + \gamma \sum_{s'} p(s'|s,a)\, v_k(s')\). As shown in Section 2.1, the solution is the greedy policy, which puts all its probability on \(\arg\max_a q_k(s,a)\) (ties can be broken arbitrarily). Plugging it into the value update gives \(v_{k+1}(s) = \max_a q_k(s,a)\). One iteration is therefore \(v_k \to q_k \to \pi_{k+1} \to v_{k+1}\):
Algorithm 1: Value iteration
From an initial \(v_0\), until \(\|v_{k+1} - v_k\|_\infty\) is small, for every state \(s\):
- \(q_k(s,a) = \sum_r p(r|s,a)\,r + \gamma \sum_{s'} p(s'|s,a)\, v_k(s')\) for every action \(a\)
- policy update: \(\pi_{k+1}(a|s) = 1\) if \(a = \arg\max_a q_k(s,a)\), and \(0\) otherwise
- value update: \(v_{k+1}(s) = \max_a q_k(s,a)\)
Note that \(v_k\) is not a state value. It converges to \(v^*\), but along the way it need not satisfy the Bellman equation of any policy; it is only an intermediate vector of a numerical method. In the example below, \(v_1 = (0, 1, 1, 1)\), while the policy \(\pi_1\) it produces has the state value \((0, 10, 10, 10)\).
Example. On the \(2\times 2\) grid (\(s_2\) forbidden, \(s_4\) target, \(r_{\text{boundary}} = r_{\text{forbidden}} = -1\), \(r_{\text{target}} = 1\), \(\gamma = 0.9\)), the q-table as a function of \(v\) is
| \(q(s,a)\) | up | right | down | left | stay |
|---|---|---|---|---|---|
| \(s_1\) | \(-1 + \gamma v(s_1)\) | \(-1 + \gamma v(s_2)\) | \(0 + \gamma v(s_3)\) | \(-1 + \gamma v(s_1)\) | \(0 + \gamma v(s_1)\) |
| \(s_2\) | \(-1 + \gamma v(s_2)\) | \(-1 + \gamma v(s_2)\) | \(1 + \gamma v(s_4)\) | \(0 + \gamma v(s_1)\) | \(-1 + \gamma v(s_2)\) |
| \(s_3\) | \(0 + \gamma v(s_1)\) | \(1 + \gamma v(s_4)\) | \(-1 + \gamma v(s_3)\) | \(-1 + \gamma v(s_3)\) | \(0 + \gamma v(s_3)\) |
| \(s_4\) | \(-1 + \gamma v(s_2)\) | \(-1 + \gamma v(s_4)\) | \(-1 + \gamma v(s_4)\) | \(0 + \gamma v(s_3)\) | \(1 + \gamma v(s_4)\) |
Starting from \(v_0 = (0, 0, 0, 0)\) and then using \(v_1\), the first two q-tables are (row maxima in bold):
| \(q_0(s,a)\), from \(v_0 = (0,0,0,0)\) | \(q_1(s,a)\), from \(v_1 = (0,1,1,1)\) | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| \(s_1\) | \(-1\) | \(-1\) | \(\mathbf{0}\) | \(-1\) | \(\mathbf{0}\) | \(-1\) | \(-0.1\) | \(\mathbf{0.9}\) | \(-1\) | \(0\) |
| \(s_2\) | \(-1\) | \(-1\) | \(\mathbf{1}\) | \(0\) | \(-1\) | \(-0.1\) | \(-0.1\) | \(\mathbf{1.9}\) | \(0\) | \(-0.1\) |
| \(s_3\) | \(0\) | \(\mathbf{1}\) | \(-1\) | \(-1\) | \(0\) | \(0\) | \(\mathbf{1.9}\) | \(-0.1\) | \(-0.1\) | \(0.9\) |
| \(s_4\) | \(-1\) | \(-1\) | \(-1\) | \(0\) | \(\mathbf{1}\) | \(-0.1\) | \(-0.1\) | \(-0.1\) | \(0.9\) | \(\mathbf{1.9}\) |
(Columns: up, right, down, left, stay.) At \(k = 0\), "down" and "stay" tie at \(s_1\); picking "stay", \(\pi_1\) is not yet optimal. At \(k = 1\), "down" wins at \(s_1\), so \(\pi_2\) is already optimal (Figure 8), while \(v_2 = (0.9, 1.9, 1.9, 1.9)\) is still far from \(v^* = (9, 10, 10, 10)\). In larger problems more iterations are needed, and we stop when \(\|v_{k+1} - v_k\|\) is small.
3.2 Policy iteration
Policy iteration starts from a policy \(\pi_0\) and repeats
- Policy evaluation: solve \(v_{\pi_k} = r_{\pi_k} + \gamma P_{\pi_k} v_{\pi_k}\).
- Policy improvement: \(\pi_{k+1} = \arg\max_\pi\,(r_\pi + \gamma P_\pi v_{\pi_k})\).
The evaluation is the problem of Section 1.4: either the closed form \((I - \gamma P_{\pi_k})^{-1} r_{\pi_k}\), or the inner iteration \(v^{(j+1)} = r_{\pi_k} + \gamma P_{\pi_k} v^{(j)}\). So policy iteration has an iterative algorithm nested inside it. In theory the inner loop needs infinitely many steps; in practice it is stopped when \(\|v^{(j+1)} - v^{(j)}\|\) is small. Whether stopping early is harmful is the question of Section 3.3. First, why does the outer loop work?
Lemma (policy improvement)
\(v_{\pi_{k+1}} \ge v_{\pi_k}\).
Proof. Since \(\pi_{k+1}\) maximizes \(r_\pi + \gamma P_\pi v_{\pi_k}\), it does at least as well as \(\pi_k\): \(v_{\pi_k} = r_{\pi_k} + \gamma P_{\pi_k} v_{\pi_k} \le r_{\pi_{k+1}} + \gamma P_{\pi_{k+1}} v_{\pi_k}\). Subtracting this from \(v_{\pi_{k+1}} = r_{\pi_{k+1}} + \gamma P_{\pi_{k+1}} v_{\pi_{k+1}}\),
\[ (I - \gamma P_{\pi_{k+1}})(v_{\pi_{k+1}} - v_{\pi_k}) \ge 0, \]and multiplying by \((I - \gamma P_{\pi_{k+1}})^{-1} \ge 0\) (Section 1.4.2) gives the claim. \(\square\) This is the trick at \(s_1\) from Section 2.1, "switch to the action with the largest action value", now applied at all states at once and proven to work.
Theorem (convergence)
Let \(v_k\) be value iteration started from \(v_0 = v_{\pi_0}\). Then \(v_k \le v_{\pi_k} \le v^*\) for all \(k\), so \(v_{\pi_k} \to v^*\).
Proof by induction. Assume \(v_{\pi_k} \ge v_k\), and let \(\pi'\) be the greedy policy for \(v_k\), so \(v_{k+1} = r_{\pi'} + \gamma P_{\pi'} v_k\). Then
\[ v_{\pi_{k+1}} = r_{\pi_{k+1}} + \gamma P_{\pi_{k+1}} v_{\pi_{k+1}} \ge r_{\pi_{k+1}} + \gamma P_{\pi_{k+1}} v_{\pi_k} \ge r_{\pi'} + \gamma P_{\pi'} v_{\pi_k} \ge r_{\pi'} + \gamma P_{\pi'} v_k = v_{k+1}, \]using the lemma, the maximality of \(\pi_{k+1}\), and the induction hypothesis (each time with \(P \ge 0\)). \(\square\)
So policy iteration is never behind value iteration: \(\|v^* - v_{\pi_k}\|_\infty \le \|v^* - v_k\|_\infty \le \gamma^k \|v^* - v_0\|_\infty\). In a finite MDP it even stops after finitely many steps. If an improvement step does not increase the value, \(v_{\pi_{k+1}} = v_{\pi_k}\), then \(v_{\pi_k} = r_{\pi_{k+1}} + \gamma P_{\pi_{k+1}} v_{\pi_k} = \max_\pi (r_\pi + \gamma P_\pi v_{\pi_k})\) solves the BOE, so it is \(v^*\). Until then the value strictly increases, so no deterministic policy is visited twice, and there are only finitely many of them.
Algorithm 2: Policy iteration
From an initial policy \(\pi_0\), until \(v_{\pi_k}\) converges:
- Policy evaluation: iterate \(v^{(j+1)}(s) = \sum_a \pi_k(a|s)\big[\sum_r p(r|s,a)\,r + \gamma\sum_{s'} p(s'|s,a)\, v^{(j)}(s')\big]\) until convergence; this is \(v_{\pi_k}\).
- Policy improvement: \(q_{\pi_k}(s,a) = \sum_r p(r|s,a)\,r + \gamma\sum_{s'} p(s'|s,a)\, v_{\pi_k}(s')\), and \(\pi_{k+1}\) is greedy in \(q_{\pi_k}\).
The state value is only an intermediate step: we compute \(v_{\pi_k}\) to get \(q_{\pi_k}\), and \(q_{\pi_k}\) to update the policy. This observation is the key to Section 4.
Under \(\pi_0\), a free cell is worth \(0\), a forbidden cell \(-10/(1-\gamma) = -100\), and only the target \(10\). Two patterns are visible. States close to the target find their optimal action first, and the correct region grows outwards: a far state can only find a good path once the states along it already know how to reach the target. And values grow with proximity to the target, because from far away the first positive reward is discounted heavily.
3.3 Truncated policy iteration
The two algorithms look alike (PE: policy evaluation, PI: policy improvement, PU: policy update, VU: value update):
\[ \begin{aligned} \text{policy iteration:}\quad & \pi_0 \xrightarrow{\text{PE}} v_{\pi_0} \xrightarrow{\text{PI}} \pi_1 \xrightarrow{\text{PE}} v_{\pi_1} \xrightarrow{\text{PI}} \pi_2 \xrightarrow{\text{PE}} \cdots \\ \text{value iteration:}\quad & \phantom{\pi_0 \xrightarrow{\text{PE}}}\ \ v_0 \xrightarrow{\text{PU}} \pi_1' \xrightarrow{\text{VU}} v_1 \xrightarrow{\text{PU}} \pi_2' \xrightarrow{\text{VU}} \cdots \end{aligned} \]Start both from \(v_0 = v_{\pi_0}\) and compare:
| Policy iteration | Value iteration | |
|---|---|---|
| policy | \(\pi_1 = \arg\max_\pi (r_\pi + \gamma P_\pi v_{\pi_0})\) | \(\pi_1 = \arg\max_\pi (r_\pi + \gamma P_\pi v_0)\), the same |
| value | \(v_{\pi_1} = (I - \gamma P_{\pi_1})^{-1} r_{\pi_1}\) | \(v_1 = r_{\pi_1} + \gamma P_{\pi_1} v_0\) |
| policy | \(\pi_2 = \arg\max_\pi (r_\pi + \gamma P_\pi v_{\pi_1})\) | \(\pi_2' = \arg\max_\pi (r_\pi + \gamma P_\pi v_1)\) |
They differ only in the value step. Write the evaluation of \(\pi_1\) as the inner iteration started from \(v_0\):
\[ \begin{aligned} v^{(1)} &= r_{\pi_1} + \gamma P_{\pi_1} v_0 = v_1 && \longleftarrow \text{value iteration} \\ v^{(j)} &= r_{\pi_1} + \gamma P_{\pi_1} v^{(j-1)} && \longleftarrow \text{truncated policy iteration} \\ v^{(\infty)} &= v_{\pi_1} && \longleftarrow \text{policy iteration} \end{aligned} \]Value iteration does one inner step and policy iteration infinitely many. Stopping after \(j\) steps, and starting the next evaluation from the last estimate, gives truncated policy iteration. (This step-by-step comparison only works because both start from \(v_0 = v_{\pi_0}\).) Its values are not state values, so does it still converge? A first hint is that the inner steps never decrease the value:
Proposition (value improvement)
If the inner iteration \(v^{(j+1)} = r_{\pi_k} + \gamma P_{\pi_k} v^{(j)}\) starts from \(v^{(0)} = v_{\pi_{k-1}}\), then \(v^{(j+1)} \ge v^{(j)}\) for all \(j\).
Proof. \(v^{(j+1)} - v^{(j)} = \gamma P_{\pi_k}(v^{(j)} - v^{(j-1)}) = \cdots = (\gamma P_{\pi_k})^j (v^{(1)} - v^{(0)})\), and \(v^{(1)} = r_{\pi_k} + \gamma P_{\pi_k} v_{\pi_{k-1}} \ge r_{\pi_{k-1}} + \gamma P_{\pi_{k-1}} v_{\pi_{k-1}} = v^{(0)}\) because \(\pi_k\) is greedy for \(v_{\pi_{k-1}}\). \(\square\)
But truncated policy iteration never computes \(v_{\pi_{k-1}}\) exactly, so this is not yet a proof. The fix is to carry the property the proof actually used along with the algorithm. This is short with the Bellman operators \(T_\pi v = r_\pi + \gamma P_\pi v\) and \(T v = \max_\pi T_\pi v\). Both are monotone: \(u \le w\) implies \(T_\pi u \le T_\pi w\) and \(T u \le T w\).
Theorem (convergence of truncated policy iteration)
Start from \(v_0\) with \(v_0 \le T v_0\) (e.g. \(v_0 = v_{\pi_0}\)). Let \(\pi_{k+1}\) be greedy for \(v_k\) and \(v_{k+1} = T_{\pi_{k+1}}^{\,j} v_k\) with any \(j \ge 1\). Then \(T^k v_0 \le v_k \le v^*\), so \(v_k \to v^*\), at least as fast as value iteration.
Proof. Suppose \(v_k \le T v_k\). Let \(u_i = T_{\pi_{k+1}}^{\,i} v_k\); then \(u_1 = T v_k \ge v_k = u_0\).
- The inner iterates increase: if \(u_i \ge u_{i-1}\) then \(u_{i+1} = T_{\pi_{k+1}} u_i \ge T_{\pi_{k+1}} u_{i-1} = u_i\). So \(v_{k+1} = u_j \ge u_1 = T v_k\).
- The assumption is kept: \(T v_{k+1} \ge T_{\pi_{k+1}} u_j = u_{j+1} \ge u_j = v_{k+1}\).
- Lower bound: by induction, \(v_{k+1} \ge T v_k \ge T(T^k v_0) = T^{k+1} v_0\).
- Upper bound: \(v \le T v\) implies \(v \le T v \le T^2 v \le \cdots \to v^*\).
Since \(T^k v_0\) is value iteration, which converges to \(v^*\), so does \(v_k\). \(\square\)
The proof also explains why truncation helps. Value iteration applies the greedy policy's update once and moves on; truncated policy iteration applies it \(j\) times, and the bullets above show that each extra application can only raise the estimate towards \(v_{\pi_{k+1}}\), and never past \(v^*\). So more evaluation is never wasted, it only costs time.
With \(j = 1\) this is value iteration, and with \(j \to \infty\) policy iteration. (Truncated policy iteration converges from any \(v_0\); the assumption \(v_0 \le Tv_0\) only keeps the proof short. See Puterman [4, Section 6.5].)
Algorithm 3: Truncated policy iteration
From an initial policy \(\pi_0\) and \(v_0 = v_{\pi_0}\), with a number of inner steps \(j\), until \(v_k\) converges:
- Policy improvement: \(\pi_{k+1}\) is greedy in \(q_k(s,a) = \sum_r p(r|s,a)\,r + \gamma\sum_{s'} p(s'|s,a)\, v_k(s')\).
- Truncated evaluation: starting from \(v_k\), apply \(v \leftarrow r_{\pi_{k+1}} + \gamma P_{\pi_{k+1}} v\) \(j\) times; the result is \(v_{k+1}\).
Each inner step costs about as much as one value-iteration step. Policy iteration needs fewer outer iterations but more work per iteration, and a few inner steps already capture most of the benefit. That is why truncated policy iteration with a small \(j\) is often the most efficient choice.
All three algorithms alternate a value step and a policy step without doing either exactly. This pattern is called generalized policy iteration [2], and most of RL fits into it. What they all still need is the model. Algorithms that work without it are called model-free. (Model-based RL, by contrast, does not mean "given the model"; it means learning a model from data and then planning with it.)
4. Monte Carlo Methods
The algorithms of Section 3 need the model \(p(r|s,a), p(s'|s,a)\). Usually we do not have it; we can only act and observe. Without a model we need data, and the simplest way to turn data into values is to average. That is the Monte Carlo (MC) idea: estimate a deterministic quantity by statistics of random samples.
4.1 Why averaging works
Markov's inequality. For \(X \ge 0\) and \(a > 0\), \(\mathbb{P}(X \ge a) \le \mathbb{E}[X]/a\), because
\[ \mathbb{E}[X] = \int_0^{\infty} x f_X(x)\,dx \;\ge\; \int_a^{\infty} x f_X(x)\,dx \;\ge\; a \int_a^{\infty} f_X(x)\,dx = a\,\mathbb{P}(X \ge a). \]Chebyshev's inequality. If \(X\) has mean \(\mu\) and variance \(\sigma^2\), applying Markov's inequality to \(Y = |X - \mu|^2\) gives
\[ \mathbb{P}(|X - \mu| \ge \varepsilon) = \mathbb{P}(Y \ge \varepsilon^2) \le \frac{\sigma^2}{\varepsilon^2}. \]Weak law of large numbers. Let \(X_1, X_2, \dots\) be i.i.d. with mean \(\mu\) and variance \(\sigma^2\), and \(\bar X_n = \frac1n \sum_{i=1}^n X_i\). By independence,
\[ \mathbb{E}[\bar X_n] = \mu, \qquad \operatorname{Var}(\bar X_n) = \frac{1}{n^2}\sum_{i=1}^n \operatorname{Var}(X_i) = \frac{\sigma^2}{n}, \]so by Chebyshev, for every \(\varepsilon > 0\),
\[ \mathbb{P}\big(|\bar X_n - \mu| < \varepsilon\big) \ge 1 - \frac{\sigma^2}{n\varepsilon^2} \xrightarrow{\,n\to\infty\,} 1. \]This also gives a rate: \(n \ge \sigma^2/(\delta\varepsilon^2)\) samples put \(\bar X_n\) within \(\varepsilon\) of \(\mu\) with probability at least \(1 - \delta\). Note the variance is \(\sigma^2/n\), not \(\sigma^2/n^2\): the \(1/n^2\) from the constant is partly cancelled by the \(n\) variances in the sum.
Strong law of large numbers. \(\mathbb{P}\big(\lim_{n\to\infty} \bar X_n = \mu\big) = 1\). The difference is where the limit sits. Think of each run as one path \(\bar X_1, \bar X_2, \dots\) (Figure 11).
- Weak law (limit of probabilities): at a single large time \(n\), only a small fraction of paths is outside the \(\pm\varepsilon\) band. It does not forbid a path from leaving the band again and again, as long as this becomes rarer.
- Strong law (probability of a limit): almost every path converges; it leaves the band only finitely many times and then stays inside forever.
The strong law implies the weak one. If \(\mathbb{E}[X^4] < \infty\) (true for bounded rewards), it has a short proof. Expanding \(S_n = \sum_i (X_i - \mu)\) gives \(\mathbb{E}[S_n^4] \le C n^2\), so Markov's inequality on \(S_n^4\) gives \(\mathbb{P}(|\bar X_n - \mu| \ge \varepsilon) \le C/(\varepsilon^4 n^2)\). This is summable in \(n\), so by the Borel–Cantelli lemma only finitely many of these events happen, with probability one. The general proof is in [5].
This is all we need for mean estimation. For a coin with \(X = +1\) (heads) or \(-1\) (tails), knowing the distribution \(\mathbb{P}(X = \pm 1) = 0.5\) gives \(\mathbb{E}[X] = \sum_x x\, p(x) = 0\) exactly (model-based). Without it, flip the coin \(n\) times and average (model-free); by the laws of large numbers the average converges to \(0\), as long as the flips are i.i.d. State and action values are expectations of returns, so they can be estimated by averaging returns.
4.2 MC Basic
Take policy iteration and replace the part that uses the model. The model enters only in the formula for \(q_{\pi_k}(s,a)\), which the improvement step needs. But the action value is also a mean,
\[ q_{\pi_k}(s,a) = \mathbb{E}\big[G_t \,\big|\, S_t = s, A_t = a\big] \approx \frac1n \sum_{i=1}^n g^{(i)}(s,a), \]where \(g^{(i)}(s,a)\) are the returns of \(n\) episodes that start from \((s,a)\) and then follow \(\pi_k\). We must estimate \(q\) directly: estimating \(v\) instead would still need the model to get \(q\).
Algorithm 4: MC Basic
From an initial policy \(\pi_0\), for \(k = 0, 1, 2, \dots\) and every state \(s\):
- Policy evaluation: for every action \(a\), collect sufficiently many episodes starting from \((s,a)\) and following \(\pi_k\); \(q_k(s,a)\) = their average return.
- Policy improvement: \(\pi_{k+1}(a|s) = 1\) if \(a = \arg\max_a q_k(s,a)\), and \(0\) otherwise.
If the estimates are accurate, this is policy iteration and converges. With finitely many episodes they are only approximate, but, as in truncated policy iteration, the algorithm usually still works. MC Basic is far too wasteful for practice; it shows the core idea in its cleanest form. With a deterministic policy and environment, a single episode per pair is exact. In the \(3\times 3\) grid with the initial policy of Figure 12 (\(\gamma = 0.9\)), the episodes from \(s_1\) give
"Up" and "left" bounce off the wall at every step, since \(\pi_0\) keeps going up. "Right" leads \(s_1 \to s_2 \to s_5 \to s_8 \to s_9\) and then stays: three zero rewards, then \(+1\) forever. "Down" goes \(s_1 \to s_4 \to s_5 \to s_8 \to s_9\) with the same return. "Stay" earns \(0\) once and then follows \(\pi_0\) into the wall. The maximum \(\gamma^3/(1-\gamma) > 0\) is attained by right and down, so \(\pi_1\) takes one of them at \(s_1\), which is optimal. Since \(\pi_0\) was optimal elsewhere except at \(s_3\), which the same computation fixes, one iteration suffices here.
Real episodes are finite. An episode of length \(L\) estimates the return up to an error of at most \(\gamma^L \max|r|/(1-\gamma)\), and, more importantly, it only sees rewards within \(L\) steps of its start. Figure 13 runs MC Basic on the \(5\times 5\) grid with episodes of different lengths. With length 1, only the target and its neighbours see a positive reward. By length 15, every state reaches the target and the policy is optimal, but the values are still too small. This is the problem of sparse rewards: far from the goal there is no signal at all. A common remedy is reward shaping: adding intermediate rewards that lead the agent towards the goal.
4.3 MC Exploring Starts
MC Basic wastes data in two ways, and fixing them gives a better algorithm.
Use each episode more fully. Each appearance of a pair \((s,a)\) in an episode is a visit. MC Basic uses only the initial visit. But by the Markov property, the tail of an episode after any visit is a sample of the return from that pair:
\[ \begin{aligned} s_1 \xrightarrow{a_2} s_2 \xrightarrow{a_4} s_1 \xrightarrow{a_2} s_2 \xrightarrow{a_3} s_5 \xrightarrow{a_1} \cdots \quad &[\text{original episode}] \\ s_2 \xrightarrow{a_4} s_1 \xrightarrow{a_2} s_2 \xrightarrow{a_3} s_5 \xrightarrow{a_1} \cdots \quad &[\text{subepisode from } (s_2, a_4)] \\ s_1 \xrightarrow{a_2} s_2 \xrightarrow{a_3} s_5 \xrightarrow{a_1} \cdots \quad &[\text{subepisode from } (s_1, a_2)] \\ s_2 \xrightarrow{a_3} s_5 \xrightarrow{a_1} \cdots \quad &[\text{subepisode from } (s_2, a_3)] \end{aligned} \]So one episode estimates all the pairs it visits. If a pair is visited twice, first-visit MC uses only the first, and every-visit MC uses all. Every-visit is the usual choice because it uses more data. Its returns are correlated, since the subepisodes of one episode overlap, so the every-visit average is biased for a finite number of episodes, while the first-visit average is unbiased. Both converge to \(q_\pi(s,a)\) as the number of episodes grows [2, Section 5.1].
Update the policy sooner. Instead of waiting for all episodes of all pairs, update the estimates and the policy after every episode. The estimates are then rough, but, as in truncated policy iteration, this still works. It is an instance of generalized policy iteration.
Algorithm 5: MC Exploring Starts
Initialize \(\pi_0\), \(q(s,a)\), \(\text{Returns}(s,a) = 0\) and \(\text{Num}(s,a) = 0\). For each episode:
- Episode generation: choose a starting pair \((s_0, a_0)\) so that every pair can be chosen (exploring starts), then follow the current policy: \(s_0, a_0, r_1, \dots, s_{T-1}, a_{T-1}, r_T\).
- \(g \leftarrow 0\). For \(t = T-1, \dots, 0\):
- \(g \leftarrow \gamma g + r_{t+1}\); \(\text{Returns}(s_t, a_t) \mathrel{+}= g\); \(\text{Num}(s_t, a_t) \mathrel{+}= 1\)
- Policy evaluation: \(q(s_t, a_t) \leftarrow \text{Returns}(s_t, a_t) / \text{Num}(s_t, a_t)\)
- Policy improvement: \(\pi(\cdot|s_t)\) greedy in \(q(s_t, \cdot)\)
Going backwards computes each return in \(O(1)\). The evaluation and improvement can also be moved out of the loop over \(t\) and done once per episode, with the same result. The policy is not used inside the loop (the episode is already generated). And because the loop runs backwards, \(q(s,\cdot)\) is final once the earliest visit of \(s\) is processed. This saves work when the episode is much longer than the number of pairs it visits.
Exploring starts are needed because a greedy policy takes only one action per state, so other actions are only estimated if episodes start from them. If the optimal action is never tried, it is never found. In practice, starting from every pair is hard (think of a real robot).
4.4 MC \(\varepsilon\)-greedy
The fix is to keep randomness in the policy itself. The \(\varepsilon\)-greedy policy with greedy action \(a^*\) is
\[ \pi(a\,|\,s) = \begin{cases} 1 - \varepsilon + \dfrac{\varepsilon}{|\mathcal{A}(s)|}, & a = a^*, \\[2mm] \dfrac{\varepsilon}{|\mathcal{A}(s)|}, & \text{each of the other } |\mathcal{A}(s)| - 1 \text{ actions}, \end{cases} \qquad \varepsilon \in [0, 1]. \]To sample it, draw \(u \sim \text{Uniform}[0,1]\). If \(u \ge \varepsilon\), take \(a^*\); otherwise pick one of all \(|\mathcal{A}(s)|\) actions uniformly, which is why \(a^*\) gets the extra \(\varepsilon/|\mathcal{A}|\). \(\varepsilon = 0\) is greedy and \(\varepsilon = 1\) is uniformly random. For example, with five actions and \(\varepsilon = 0.2\), the greedy action has probability \(0.84\) and each other action \(0.04\). Since \(1 - \varepsilon + \varepsilon/|\mathcal{A}| \ge \varepsilon/|\mathcal{A}|\), the greedy action is always the most likely one, and every action has positive probability (a soft policy).
MC \(\varepsilon\)-greedy is MC Exploring Starts without the exploring-starts condition, with an \(\varepsilon\)-greedy instead of a greedy policy improvement:
\[ \pi_{k+1}(\cdot|s) = \arg\max_{\pi \in \Pi_\varepsilon} \sum_a \pi(a|s)\, q_{\pi_k}(s,a), \]where \(\Pi_\varepsilon\) is the set of \(\varepsilon\)-greedy policies; the solution puts \(1 - \varepsilon + \varepsilon/|\mathcal{A}(s)|\) on \(\arg\max_a q_{\pi_k}(s,a)\). A long enough episode now visits every pair. The price is optimality: the algorithm finds the best policy within \(\Pi_\varepsilon\), not among all policies, because it keeps taking bad actions with probability \(\varepsilon\). We hope that its greedy action is still optimal, so that \(\varepsilon\) can be set to \(0\) at the end.
A large \(\varepsilon\) means more exploration, a small one more exploitation. Figure 14 shows the exploration side: with \(\varepsilon = 1\), one episode of a million steps visits each of the 125 pairs about 8000 times. With \(\varepsilon = 0.5\) the counts range from a few hundred to about 200,000.
Figure 15 shows the exploitation side, the best \(\varepsilon\)-greedy policies (greedy actions shown). For \(\varepsilon = 0.1\), the greedy actions are the optimal ones (the policy is consistent with the optimal greedy policy), though the values are much lower: the target is worth \(3.3\) instead of \(10\), since even there the agent steps away with probability \(0.08\). For \(\varepsilon = 0.2\) and \(0.5\), random steps into the forbidden cells around the target are so costly that the policy changes, and setting \(\varepsilon = 0\) would no longer give an optimal policy.
So \(\varepsilon\) should be large early on to explore, and decay over time to exploit.
References
[1] Shiyu Zhao. Mathematical Foundations of Reinforcement Learning. Springer Nature Press and Tsinghua University Press, 2025. Chapters 1–5.
[2] Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction, 2nd edition. MIT Press, 2018. Chapters 3–5.
[3] Roger A. Horn and Charles R. Johnson. Matrix Analysis, 2nd edition. Cambridge University Press, 2013. Section 6.1.
[4] Martin L. Puterman. Markov Decision Processes: Discrete Stochastic Dynamic Programming. Wiley, 1994. Sections 6.2–6.5.
[5] Rick Durrett. Probability: Theory and Examples, 5th edition. Cambridge University Press, 2019. Sections 2.2–2.4.