Estimate state values with first-visit Monte Carlo
Why it matters Monte Carlo returns are the targets behind REINFORCE and the reward-to-go used in RLHF.
Monte Carlo prediction waits until an episode ends, computes the actual return from each time step, and averages those returns per state.
Write first_visit_mc(episodes, gamma, n_states). Each episode is a list of (state, reward) pairs, where reward is what was received right after leaving that state. For each episode compute the discounted return G_t from every step. Only the FIRST occurrence of a state in an episode contributes its G_t. Return a length n_states numpy array of the average first-visit return per state, with 0.0 for states never visited.
def first_visit_mc(episodes, gamma, n_states)Example
first_visit_mc([[(0, 1), (1, 0), (0, 2)]], 1.0, 2) gives array([3., 2.]).
Understand the idea
Monte Carlo methods learn from complete experience: play a whole episode, then look back and see what actually happened after each state. The average of those real outcomes estimates the state's value, with no model of the world needed.
Example episode with gamma 1: state 0 (reward 1), state 1 (reward 0), state 0 again (reward 2). Returns from each step are 3, 2 and 2. First-visit MC credits state 0 only with its first return 3, and state 1 with 2. Every-visit MC would average 3 and 2 for state 0, giving 2.5.
Rule: G_t = r_t + gamma * G_(t+1); V(s) = mean of G_t over the first time t each episode visits s.
Both versions converge to the true value, but first-visit gives independent samples per episode. Policy gradient methods use the same returns as their training signal.