5.1.10Reinforcement Learning Foundations

Monte Carlo methods

3,065 words14 min readdifficulty · medium6 backlinks
Figure — Monte Carlo methods

What Makes Monte Carlo Different?

Why model-free matters: In real-world problems (robotics, game playing, resource allocation), we rarely have accurate models of how the environment responds to actions. MC methods let us learn directly from interaction.

The Return: What We're Averaging

Derivation of recursive form: Starting from the definition: Gt=Rt+1+γRt+2+γ2Rt+3+γ3Rt+4+G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \gamma^3 R_{t+4} + \cdots

Factor out γ\gamma from all terms except the first: Gt=Rt+1+γ(Rt+2+γRt+3+γ2Rt+4+)G_t = R_{t+1} + \gamma(R_{t+2} + \gamma R_{t+3} + \gamma^2 R_{t+4} + \cdots)

The expression in parentheses is exactly Gt+1G_{t+1}: Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}

First-Visit vs Every-Visit MC

Why the distinction? In some episodes, you might visit the same state multiple times (e.g., in a maze, you might return to the same room). Should we count each visit separately or only the first?

Monte Carlo Policy Evaluation

Why incremental update? Instead of storing all returns and recomputing mean: NewMean=1ni=1nxi=1n[(n1)OldMean+xn]=OldMean+1n(xnOldMean)\text{NewMean} = \frac{1}{n}\sum_{i=1}^n x_i = \frac{1}{n}\left[(n-1)\cdot\text{OldMean} + x_n\right] = \text{OldMean} + \frac{1}{n}(x_n - \text{OldMean})

This is memory-efficient and mathematically equivalent.

Monte Carlo Control: Learning Optimal Policy

Policy evaluation tells us how good a policy is. Monte Carlo control finds the optimal policy through generalized policy iteration: alternate between evaluation and improvement.

Why learn Q(s,a)Q(s,a) instead of V(s)V(s)? For policy improvement, we need: π(s)=argmaxa[r(s,a)+γsP(ss,a)V(s)]\pi'(s) = \arg\max_a \left[r(s,a) + \gamma \sum_{s'} P(s'|s,a) V(s') \right]

But we don't know PP or rr (model-free)! With Q(s,a)Q(s,a), improvement is simple: π(s)=argmaxaQ(s,a)\pi'(s) = \arg\max_a Q(s,a) No model needed—QQ already encapsulates the expected future.

Importance Sampling for Off-Policy Learning

Derivation of importance sampling correction: We want: vπ(s)=Eπ[GtSt=s]v_\pi(s) = \mathbb{E}_\pi[G_t | S_t = s]

But we sample from bb, giving: Eb[GtSt=s]\mathbb{E}_b[G_t | S_t = s]

Trick: multiply and divide by Pb(τ)P_b(\tau), i.e. insert the factor 1=Pb(τs)Pb(τs)1 = \dfrac{P_b(\tau|s)}{P_b(\tau|s)} and rewrite the numerator as Pπ(τs)P_\pi(\tau|s), where τ\tau is the trajectory following ss: Eπ[GS0=s]=τPπ(τs)G(τ)=τPb(τs)Pπ(τs)Pb(τs)G(τ)=Eb ⁣[Pπ(τs)Pb(τs)G  |  S0=s]\mathbb{E}_\pi[G | S_0=s] = \sum_\tau P_\pi(\tau|s)\, G(\tau) = \sum_\tau P_b(\tau|s)\,\frac{P_\pi(\tau|s)}{P_b(\tau|s)}\, G(\tau) = \mathbb{E}_b\!\left[\frac{P_\pi(\tau|s)}{P_b(\tau|s)}\, G \;\middle|\; S_0=s\right]

The ratio Pπ(τ)Pb(τ)=t=0T1π(AtSt)b(AtSt)\dfrac{P_\pi(\tau)}{P_b(\tau)} = \prod_{t=0}^{T-1} \dfrac{\pi(A_t|S_t)}{b(A_t|S_t)} because the state-transition probabilities P(St+1St,At)P(S_{t+1}|S_t,A_t) appear identically in both numerator and denominator (same environment) and cancel.

MC vs Temporal Difference (TD)

Advantages of MC:

  • Unbiased estimates (converges to true value)
  • No bootstrapping → no error propagation from incorrect value estimates
  • Simple to implement and understand
  • Can learn from incomplete knowledge of environment (as long as episodes terminate)

Disadvantages of MC:

  • High variance: Single episode's return can vary wildly due to stochasticity
  • Requires episodic tasks (must reach terminal state)
  • Slow convergence: Need many episodes before estimates stabilize
  • Delayed learning: Can't update until episode completes (bad for long episodes)
Recall Explain to a 12-Year-Old

Imagine you're learning to play a video game and trying to figure out how good each level is. Monte Carlo way: You play the entire game from that level to the end, see your final score, and say "Okay, starting from level 3, I got 50 points on average." You do this over and over—play complete games, write down what happened, and average the results. It's like doing a science experiment where you run the full test every time and record the final result. Super accurate, but takes a long time because you have to finish each game!

Why it's cool: You don't need to know the game rules! You just play and see what happens. Even if the game is random (sometimes enemies appear, sometimes they don't), if you play enough times, your average is really close to the truth.

The tricky part: If the game is really long or never ends (like Minecraft), you can't use this method because you never get to the "final score"!

Connections

Concept Map

learns from

yields

weighted by

expands to

requires no model

estimates via

of

produces

has variant

has variant

averages

averages

property

property

Monte Carlo Methods

Complete Episodes

Return Gt

Discount Factor gamma

Model-Free

Average Sample Returns

Value Function Estimate

First-Visit MC

Every-Visit MC

Unbiased

High Variance

Recursive Form

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, Monte Carlo methods ka core idea bahut simple aur khoobsurat hai. Socho tum chess seekh rahe ho by playing poore-poore games, aur game khatam hone ke baad tum peeche mudke dekhte ho — "jab main is position mein tha, tab mera average final score kitna raha across saare games?" Bas yehi hai MC methods ka funda. Yeh algorithms complete episodes se seekhte hain aur jo actual returns milte hain unka average nikalte hain. Koi model nahi chahiye, koi guessing (bootstrapping) nahi — sirf raw experience start se end tak. Naam "Monte Carlo" isliye kyunki jaise casino mein random sampling hoti hai, waise hi yahan bhi tum jitne zyada episodes play karoge, tumhare estimates utne hi true values ke kareeb converge karte jaayenge.

Ab yeh important kyun hai? Real-world problems mein — jaise robotics, gaming, ya resource allocation — humein aksar pata hi nahi hota ki environment action ke response mein kaise behave karega. Yani hamare paas transition dynamics ya reward ka accurate model nahi hota. MC methods ka beauty yehi hai ki yeh model-free hain — seedhe interaction se seekhte hain bina kisi model ke. Jo cheez tum average karte ho woh hai return GtG_t, matlab us time step se aage ka total discounted reward: Gt=Rt+1+γRt+2+G_t = R_{t+1} + \gamma R_{t+2} + \cdots. Yeh discount factor γ\gamma isliye hai kyunki immediate rewards zyada certain hote hain distant future ke rewards se, aur yeh ensure karta hai ki returns bounded rahein.

Ek chhoti si important detail hai — first-visit vs every-visit. Kabhi ek hi episode mein tum same state ko multiple baar visit kar sakte ho (jaise maze mein ghoomte hue same room mein wapas aa gaye). Toh sawaal yeh hai ki us state ka return count karte waqt sirf pehli visit lo (first-visit) ya har visit lo (every-visit). Dono hi methods sahi answer vπ(s)v_\pi(s) tak converge karte hain jab visits infinite ho jayein, bas first-visit theoretically analyze karna easy hai kyunki har episode ek independent sample deta hai. Practically MC methods thode high-variance hote hain kyunki har return ek single random path hai stochastic environment ke through — lekin yeh unbiased hote hain, matlab lambe run mein bilkul sahi jagah pahunchte hain. Yehi trade-off aage TD learning samajhne ke liye base banata hai.

Go deeper — visual, from zero

Test yourself — Reinforcement Learning Foundations

Connections