Tabular Solution Methods/Monte Carlo Methods

Lesson 2.32,454 words

Monte Carlo Methods

Monte Carlo methods learn value functions and optimal policies from complete sampled episodes, with no model of the environment: they simply average the returns that actually followed each state. We build prediction (first-visit and every-visit averaging), see why estimating action values forces the exploration question, and answer it two ways on-policy — exploring starts and epsilon-soft control.

╌╌╌╌

Dynamic programming solves a Markov decision process by leaning hard on the model: every update sweeps the dynamics , expanding the exact expectation in the Bellman equation over all successors. Monte Carlo methods throw that model away. They require only experience — sampled sequences of states, actions, and rewards from actual or simulated interaction — and yet they can still estimate value functions and find optimal policies.1 The trade is exact expectation for sampling: where DP computes from a known distribution, Monte Carlo averages the returns it actually observes.

The idea is the definition of a value function read literally. The value is the expected return from under . An expectation is a long-run average, so the most direct estimate imaginable is: follow , and every time you pass through , record the return that followed; the running average of those returns converges to . Nothing about the dynamics is needed — the environment supplies the samples, and the law of large numbers does the rest.

Because a return only makes sense once an episode has ended, we restrict Monte Carlo to episodic tasks: experience divides into episodes that terminate no matter what actions are chosen, and value estimates change only on the completion of an episode. Monte Carlo is thus incremental episode-by-episode, but not step-by-step.1 Each state acts like a separate bandit problem — sample and average a signal — except the problems are coupled: the return after acting in one state depends on the actions taken in later states of the same episode, so as the policy changes underneath, each state's bandit is nonstationary.

Monte Carlo prediction

Fix a policy and suppose we want from a batch of episodes generated by following . Each occurrence of state in an episode is a visit to . A single episode may visit several times; the first one is the first visit. Two estimators split on which visits to count:2

The two are close cousins but have slightly different theory. First-visit MC is the classic, studied since the 1940s: each first-visit return is an independent, identically distributed, unbiased estimate of with finite variance, so by the law of large numbers the average converges, and the standard deviation of its error falls as in the number of returns . Every-visit MC is biased for finite (returns from repeated visits within one episode are correlated) but its bias also vanishes asymptotically, and it extends more naturally to function approximation and eligibility traces.2

The first-visit algorithm walks each episode backward, which lets it accumulate the return with one multiply-add per step.

Algorithm:First-Visit-MC-Prediction(π)\textsc{First-Visit-MC-Prediction}(\pi) — estimate VvπV \approx v_\pi
  1. 1
    V(s)RV(s) \in \mathbb{R} arbitrarily, Returns(s)Returns(s) \gets empty list, for all sSs \in \mathcal{S}
  2. 2
    for each episode do
  3. 3
    generate an episode following π\pi: S0,A0,R1,,ST1,AT1,RTS_0, A_0, R_1, \ldots, S_{T-1}, A_{T-1}, R_T
  4. 4
    G0G \gets 0
  5. 5
    for t=T1,T2,,0t = T-1, T-2, \ldots, 0 do
  6. 6
    GγG+Rt+1G \gets \gamma G + R_{t+1}
  7. 7
    if St{S0,S1,,St1}S_t \notin \{S_0, S_1, \ldots, S_{t-1}\} then
    first-visit check
  8. 8
    append GG to Returns(St)Returns(S_t)
  9. 9
    V(St)average(Returns(St))V(S_t) \gets \average(Returns(S_t))

Delete the unless appears earlier line and the same loop becomes every-visit MC: it records every step's return, first visit or not.

A worked averaging trace

For example, run the backward loop on one short episode. Take and the observed trajectory

so state is visited twice (at and ). Running the loop from down to accumulates :

First-visit MC records the return only from the earliest occurrence of each state. State 's first visit is , so it contributes ; the later visit at with return is skipped. States and each occur once and contribute and . Every-visit MC instead records both of 's returns, so gets the two-sample average from this single episode. The two estimators already disagree after one episode; the gap is the within-episode correlation that makes every-visit MC biased for finite . Now suppose a second episode gives a first-visit return of for . The running first-visit estimate becomes — a plain average of independent samples, exactly the law-of-large-numbers estimator converging to .

The backup diagram: one trajectory, no bootstrap

The contrast with DP is sharpest in the backup diagram — the picture of which future outcomes an update draws on. A DP backup for roots at a state and branches over every one-step successor, weighting each by the model; it is one level deep and exhaustive. A Monte Carlo backup roots at a state and follows the single sampled trajectory all the way down to the terminal state; it is one path wide and full-episode deep.2

DP versus Monte Carlo backups for . DP (left) expands one full level of the model — every successor weighted by — and bootstraps off the successors' current estimates . MC (right) follows one sampled trajectory to termination, averaging the realized return with no reference to any other state's estimate.

Two facts fall out of that picture. First, Monte Carlo does not bootstrap: the estimate for one state is built from realized returns, never from the current estimate of another state. DP's every update reuses neighbors' estimates; MC's uses none. Second, the estimates for different states are independent — the cost of estimating one state's value is independent of the number of states. If you care about the value of only a handful of states, you can generate episodes starting from just those states and average their returns, ignoring the rest of the state space entirely.2 DP has no such option; it must sweep everything.

Blackjack

The casino game of blackjack makes a clean episodic MDP. The player draws cards to get a hand sum as close to 21 as possible without exceeding it; face cards count 10, and an ace counts 11 unless that would bust, in which case it counts 1 (a usable ace is one still counting as 11). The player hits (draws) or sticks (stops); busting loses. Each game is an episode with reward , , or for win, loss, or draw, all intermediate rewards zero and , so the terminal reward is the return. A state is the triple (current sum , dealer's one showing card, usable ace or not) — 200 states in all.3

Take the policy stick on 20 or 21, otherwise hit. There is no easy way to apply DP here: you would need — for instance the probability of finishing with given the dealer shows a 6 and you stick on 14 — and computing all those distributions in advance is delicate and error-prone. But simulating games is trivial. So we play many episodes under the policy and average the returns following each state. After 500,000 games the value function is well approximated; states with a usable ace stay noisier, because they arise less often.3 This is a real advantage even here, where the dynamics are technically known: Monte Carlo needs only a sample model — something that generates transitions — not the full distribution DP demands.

Estimating action values

Without a model, state values alone are not enough. With a model you can turn into a policy by a one-step lookahead — for each action, combine the reward and the successor's value, pick the best — but that lookahead needs the dynamics. Without them, tells you how good a state is but not which action gets you somewhere good. So the primary target of Monte Carlo control is the action-value function : with in hand, the greedy policy is just , no model required.4

Estimating is the same averaging, indexed by pairs. A state–action pair is visited in an episode if is visited and is taken there; first-visit MC averages returns following the first such visit in each episode, every-visit MC averages all of them. Both converge to as visits to each pair go to infinity.

The complication is exploration. Many state–action pairs may never be visited at all. If is deterministic, then following it you observe returns for only one action per state — the one chooses — and the estimates for the other actions never improve. But comparing alternatives is the whole point of estimating action values: to improve a policy you must know the value of actions it does not currently take.

Why a deterministic policy starves the action-value estimates. Following deterministically, only the chosen action (solid) ever returns data; the alternatives (dashed) are never sampled, so their estimates cannot improve — and policy improvement needs exactly those unseen values.

One way to force coverage is the assumption of exploring starts: episodes begin in a state–action pair chosen so that every pair has nonzero probability of being the start. Over infinitely many episodes every pair is then visited infinitely often.4

Exploring starts is a crutch. It works for simulated episodes but cannot be relied on in general. The two ways to drop it — keep the behaving policy stochastic everywhere (on-policy), or learn about one policy while behaving by another (off-policy) — organize the rest of the lesson.

Monte Carlo control

To find optimal policies, Monte Carlo slots evaluation into generalized policy iteration (GPI): maintain a policy and a value function, repeatedly push the value toward (evaluation) and repeatedly make the policy greedy in the current value (improvement). The two chase each other to a joint fixed point that is optimal.5 The classical version alternates complete evaluations and improvements,

where is a full MC policy evaluation and is greedy improvement. Improvement needs no model: for any action-value function , the greedy policy is . Why does going greedy in help? Because the greedy action is, by definition, the best-scoring action, so switching to it can only raise the value at that state — the same logic as in DP, now with instead of a one-step model lookahead. The policy improvement theorem applied to makes this precise:

so each is uniformly at least as good as , and the process converges to and from sample episodes alone.5

Generalized policy iteration with Monte Carlo. Evaluation drives the estimate toward by averaging returns; improvement makes greedy in . Each step spoils the other's target, yet together they climb to the optimal pair .

Two unrealistic assumptions bought that clean guarantee: exploring starts, and infinitely many episodes per evaluation. The second is easy to relax. Rather than run each evaluation to convergence, we can evaluate toward without finishing — exactly the move value iteration makes for DP. For Monte Carlo the natural rhythm is episode-by-episode: after each episode, average the observed returns to update at the visited pairs, then immediately make the policy greedy at those states. This gives Monte Carlo ES (Exploring Starts).5

Algorithm:Monte-Carlo-ES\textsc{Monte-Carlo-ES} — estimate ππ\pi \approx \pi_\ast
  1. 1
    π(s)A(s)\pi(s) \in \mathcal{A}(s) arbitrarily, Q(s,a)RQ(s,a) \in \mathbb{R} arbitrarily, Returns(s,a)Returns(s,a) \gets empty, for all s,as,a
  2. 2
    for each episode do
  3. 3
    choose S0SS_0 \in \mathcal{S}, A0A(S0)A_0 \in \mathcal{A}(S_0) at random, all pairs with probability >0> 0
  4. 4
    generate an episode from S0,A0S_0, A_0 following π\pi: S0,A0,R1,,ST1,AT1,RTS_0, A_0, R_1, \ldots, S_{T-1}, A_{T-1}, R_T
  5. 5
    G0G \gets 0
  6. 6
    for t=T1,T2,,0t = T-1, T-2, \ldots, 0 do
  7. 7
    GγG+Rt+1G \gets \gamma G + R_{t+1}
  8. 8
    if (St,At){(S0,A0),,(St1,At1)}(S_t, A_t) \notin \{(S_0, A_0), \ldots, (S_{t-1}, A_{t-1})\} then
  9. 9
    append GG to Returns(St,At)Returns(S_t, A_t)
  10. 10
    Q(St,At)average(Returns(St,At))Q(S_t, A_t) \gets \average(Returns(S_t, A_t))
  11. 11
    π(St)argmaxaQ(St,a)\pi(S_t) \gets \arg\max_a Q(S_t, a)

Applied to blackjack — where exploring starts is trivial to arrange, since we simply deal random opening states and pick the first action at random — Monte Carlo ES recovers essentially the known optimal strategy. (That Monte Carlo ES converges at all is intuitively clear: a fixed point requires both policy and value to be mutually consistent, which happens only at the optimum. A formal proof remains one of the open theoretical questions in the field.)5

On-policy control with ε-soft policies

To drop exploring starts on-policy, we keep the behaving policy soft: every action retains some probability everywhere, for all , shifting only gradually toward determinism. The standard choice is -greedy: with probability take the greedy action, and with probability pick uniformly at random among all actions.6 So every nongreedy action keeps probability , and the greedy action gets the rest, .

Now GPI cannot push the policy all the way to greedy — that would kill exploration. Instead, improvement moves the policy toward the -greedy policy for the current . The policy improvement theorem still applies: any -greedy policy with respect to is an improvement over any -soft .

Algorithm:On-Policy-First-Visit-MC-Control\textsc{On-Policy-First-Visit-MC-Control}ε\varepsilon-soft, estimate ππ\pi \approx \pi_\ast
  1. 1
    parameter: small ε>0\varepsilon > 0
  2. 2
    π\pi \gets an arbitrary ε\varepsilon-soft policy; Q(s,a)RQ(s,a) \in \mathbb{R} arbitrarily; Returns(s,a)Returns(s,a) \gets empty
  3. 3
    for each episode do
  4. 4
    generate an episode following π\pi: S0,A0,R1,,ST1,AT1,RTS_0, A_0, R_1, \ldots, S_{T-1}, A_{T-1}, R_T
  5. 5
    G0G \gets 0
  6. 6
    for t=T1,T2,,0t = T-1, T-2, \ldots, 0 do
  7. 7
    GγG+Rt+1G \gets \gamma G + R_{t+1}
  8. 8
    if (St,At){(S0,A0),,(St1,At1)}(S_t, A_t) \notin \{(S_0, A_0), \ldots, (S_{t-1}, A_{t-1})\} then
  9. 9
    append GG to Returns(St,At)Returns(S_t, A_t)
  10. 10
    Q(St,At)average(Returns(St,At))Q(S_t, A_t) \gets \average(Returns(S_t, A_t))
  11. 11
    AargmaxaQ(St,a)A^\ast \gets \arg\max_a Q(S_t, a)
    ties broken arbitrarily
  12. 12
    for each aA(St)a \in \mathcal{A}(S_t) do
  13. 13
    if a=Aa = A^\ast then
  14. 14
    π(aSt)1ε+ε/A(St)\pi(a \mid S_t) \gets 1 - \varepsilon + \varepsilon/|\mathcal{A}(S_t)|
  15. 15
    else
  16. 16
    π(aSt)ε/A(St)\pi(a \mid S_t) \gets \varepsilon/|\mathcal{A}(S_t)|

The catch is that this converges only to the best policy among -soft policies, not to the unconstrained optimum — the price of forcing perpetual exploration into the policy you actually follow. That residual suboptimality is what off-policy learning removes.

This continues in Monte Carlo Methods: Off-Policy Learning, which removes that ceiling: it learns about a greedy target policy from data generated by a soft behavior policy, using importance sampling to correct for the mismatch, and closes by placing Monte Carlo on the model/bootstrap map beside dynamic programming and temporal-difference learning.

Footnotes

  1. Sutton & Barto, Reinforcement Learning: An Introduction (2nd ed.), Ch. 5 — introduction: Monte Carlo methods require only sample experience (actual or simulated), average complete returns rather than partial ones, are defined for episodic tasks, and change estimates only on episode completion. 2
  2. Sutton & Barto, §5.1 — Monte Carlo Prediction: first-visit versus every-visit MC and their convergence (5.1 algorithm box); the Monte Carlo backup diagram (one sampled trajectory to termination) contrasted with the DP backup; that MC does not bootstrap and that per-state estimates are independent. 2 3 4
  3. Sutton & Barto, §5.1, Example 5.1 (Blackjack): the episodic MDP formulation (, terminal reward equals return, 200 states, usable-ace notion), the stick on 20 or 21 policy evaluated by MC (Figure 5.1), and the difficulty of applying DP without the explicit distribution . 2
  4. Sutton & Barto, §5.2 — Monte Carlo Estimation of Action Values: why state values are insufficient without a model, first/every-visit estimation of , the maintaining-exploration problem for deterministic policies, and the exploring-starts assumption. 2
  5. Sutton & Barto, §5.3 — Monte Carlo Control: GPI with MC evaluation, the policy-iteration chain and the policy-improvement inequality for greedy , relaxing the infinite-episodes assumption episode-by-episode, and the Monte Carlo ES algorithm (Example 5.3, Figure 5.2). 2 3 4
  6. Sutton & Barto, §5.4 — Monte Carlo Control without Exploring Starts: -soft and -greedy policies, the on-policy first-visit MC control algorithm, and the policy-improvement argument (5.2) showing convergence to the best -soft policy.

╌╌ END ╌╌