Monte Carlo methods
Learn values and policies from complete sampled episodes, with no model of the environment.
Animated explanation
The idea
Dynamic programming needs the rules of the world. Usually we don't have them: we can only play. Monte Carlo methods learn from experience in the most direct way possible: play an episode to the end, look at the return that actually followed each state, and average those returns over many episodes. By the law of large numbers the averages converge to the true values.
For control, estimate action values the same way, make the policy greedy with respect to them, but keep a little randomness (ε-greedy) so that every action keeps being tried. Monte Carlo is unbiased and simple, but it must wait until an episode ends and its estimates can be noisy.
First-visit and every-visit
If a state appears several times in one episode, first-visit MC uses only the return after its first appearance; every-visit MC uses all of them. Both converge; first-visit gives independent samples and is easier to analyse.
The exploration problem
A deterministic greedy policy never tries some actions, so their values are never learned. Fixes: exploring starts (start episodes from random state–action pairs), ε-soft policies (on-policy control), or off-policy learning with importance sampling, where a behaviour policy explores and the greedy target policy is evaluated by reweighting returns by .
The algorithm, step by step
- 1Initialise Q(s, a) = 0 and counts N(s, a) = 0; policy ε-greedy in Q.
- 2Generate an episode with the current policy.
- 3Walk backwards with ; at the first visit of each , update and .
- 4The policy improves automatically (ε-greedy in the new Q); repeat for many episodes.
The maths
Return
Incremental average
Importance sampling ratio (off-policy)
Strengths and weaknesses
Strengths
- No model needed; learns from experience
- Unbiased estimates of returns
- Simple; works for non-Markov features
Weaknesses
- Only for episodic tasks; must wait for episodes to finish
- High variance; needs many episodes
- Exploration must be handled explicitly
Reach for it when…
Check your understanding
Lambdian Lab
Monte Carlo prediction and control
Using the provided gridworld and env_step:
- run_episode(policy_fn, rng, max_steps): a list of (state, action, reward) from START; policy_fn(state, rng) returns an action.
- mc_prediction(policy, episodes, gamma, seed): first-visit MC estimate of V for a deterministic policy dict.
- mc_control(episodes, eps, gamma, seed): on-policy first-visit MC control with an ε-greedy policy; return Q as a dict state → array of 4.