Notes on Chapter 5 of Shiyu Zhao's Mathematical Foundations of Reinforcement Learning [1].
The algorithms of the last post 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.
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 1).
- 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 [3].
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.
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 1: 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 2 (\(\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 3 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.
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 2: 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. 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 4 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 5 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. Chapter 5.
[2] Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction, 2nd edition. MIT Press, 2018. Chapter 5.
[3] Rick Durrett. Probability: Theory and Examples, 5th edition. Cambridge University Press, 2019. Sections 2.2–2.4.