Monte Carlo Action Values
Estimating state values alone cannot guide decisions when transition dynamics are unknown. Monte Carlo action-value estimation records the total returns following specific choices in each state, learning the expected payout of every action purely from experience.
Why Does This Exist?
In reinforcement learning, the ultimate objective is finding an optimal policy that maximizes cumulative reward. When an agent possesses a complete environment model—namely the transition probabilities and expected rewards —state values are entirely sufficient to select the best action via a standard one-step lookahead:
However, in model-free reinforcement learning, the environment is an unknown black box. Even if an oracle provides the true state values , the agent cannot act greedily because it has no mathematical model specifying which action leads to which successor state . Knowing that state is worth is useless if you do not know which joystick movement lands you there.
Action values resolve this fundamental dilemma. By estimating the expected return of taking a specific action in state and thereafter following policy , the agent can select actions greedily with a direct maximum:
Monte Carlo estimation evaluates these action values directly from episodic experience. It eliminates the need for transition models or bootstrapping, but it introduces an essential structural requirement: while an agent naturally visits states along a trajectory, estimating all actions requires active exploration so every alternative action from each state is repeatedly sampled.
Think of It Like This
The Restaurant Tasting Menu Pairing
Imagine you are dining through a multi-course chef's tasting menu at a fine restaurant, but the kitchen refuses to give you the recipes or explain the culinary science behind each dish.
When Course 3 arrives (State : pan-seared sea bass), the server offers you a choice between two beverage pairings: Pinot Noir (Action ) or Chardonnay (Action ).
Knowing that Course 3 is generally rated by critics (State Value ) does not help you choose your drink. Because you do not know the chemical interactions between the wine and the sauce (the environment transition model ), you cannot mentally predict the final outcome before tasting it.
To estimate the action values, you must experience the meal directly:
- On night one, you order Chardonnay (). You drink the wine, finish the remaining courses through dessert (the terminal state), and rate your full evening satisfaction score ().
- On night two, you order Pinot Noir () with the same fish course, complete the dinner, and record your evening satisfaction score ().
- Over repeated visits, you average the total satisfaction scores resulting from each specific beverage decision. The resulting averages are your empirical action values: and .
Once you have these averages, choosing your drink next time is effortless: simply select the beverage with the higher empirical score—no sommelier needed.
Where the analogy stops: Human diners evaluate meals using holistic taste memories and sensory fatigue, whereas reinforcement learning computes a mathematically discounted return . Furthermore, a diner can generalize from prior culinary knowledge, whereas tabular Monte Carlo methods require resetting and rerunning dozens of complete episodes from scratch across every state-action combination to eliminate sample variance.
How It Actually Works
Action-Value Formulation and Return Sampling
Given a Markov Decision Process defined by state space , action space , discount factor , and terminal time step , the action-value function under policy is the expected total discounted return starting from state , taking action :
Here:
- represents the state at time step .
- represents the action executed at time step .
- is the numerical reward obtained at step .
- is the discount factor balancing short-term and long-term gains.
- is the actual accumulated discounted return from time step through terminal step .
In First-Visit Monte Carlo estimation of action values, the agent executes complete episodes following policy . For each episode trajectory:
the agent moves from backward to , accumulating returns . For every state-action pair , the return is recorded only if time step is the first occurrence of in that episode.
The tabular value estimate is updated as the arithmetic mean of all recorded returns:
Equivalently, the update can be performed incrementally using a visit counter :
Because a deterministic policy would repeatedly select the exact same action from state , many state-action pairs would never be experienced (). To guarantee convergence across all choices, Monte Carlo prediction relies on Exploring Starts: every episode begins with a state-action pair sampled such that every combination has a non-zero probability:
Worked numerical example
Consider an agent learning action values for starting state with two available actions under discount factor . Initially, tables are empty: and for all .
Three successive episodes are generated:
Episode 1 (Exploring start: )
- Trajectory:
- Return from step 0:
- First visit to :
Episode 2 (Exploring start: )
- Trajectory:
- Return from step 0:
- First visit to :
Episode 3 (Start: )
- Trajectory:
- Return from step 0:
- First visit to in this episode:
Resulting Policy Decision
At state , the agent compares the empirical estimates:
Selecting greedily without needing transition dynamics:
Because Episode 2 enforced an exploring start on , the agent discovered that yielded an expected payout of , outperforming ().
Code
from typing import Dict, List, NamedTuple, Tuple
class Transition(NamedTuple): state: str action: str reward: float
Episode = List[Transition]
def first_visit_mc_action_values( episodes: List[Episode], gamma: float = 0.90) -> Tuple[Dict[Tuple[str, str], float], Dict[Tuple[str, str], int]]: """ Computes Q(s, a) tabular action values using First-Visit Monte Carlo prediction.
Args: episodes: List of completed episodes containing state-action-reward transitions. gamma: Discount factor in range [0, 1].
Returns: q_table: Dictionary mapping (state, action) pairs to their estimated Q-value. counts: Dictionary mapping (state, action) pairs to total first-visit counts. """ q_table: Dict[Tuple[str, str], float] = {} returns_sum: Dict[Tuple[str, str], float] = {} counts: Dict[Tuple[str, str], int] = {}
for episode in episodes: g: float = 0.0 # Step backward from the terminal transition to accumulate discounted returns backward_returns: List[Tuple[str, str, float]] = [] for step in reversed(episode): g = step.reward + gamma * g backward_returns.append((step.state, step.action, g)) # Restore chronological order backward_returns.reverse()
# Track first visits within this specific episode visited_in_episode = set() for state, action, return_val in backward_returns: sa_pair = (state, action) if sa_pair not in visited_in_episode: visited_in_episode.add(sa_pair) if sa_pair not in counts: counts[sa_pair] = 0 returns_sum[sa_pair] = 0.0
counts[sa_pair] += 1 returns_sum[sa_pair] += return_val # Empirical mean of all observed returns q_table[sa_pair] = returns_sum[sa_pair] / counts[sa_pair]
return q_table, counts
# Simulated episodes matching the worked exampleepisodes_dataset: List[Episode] = [ # Episode 1: (s0, a1) -> (s1, a1) -> Terminal [Transition("s0", "a1", 2.0), Transition("s1", "a1", 4.0)], # Episode 2: (s0, a2) -> (s2, a2) -> Terminal (Exploring start) [Transition("s0", "a2", -1.0), Transition("s2", "a2", 8.0)], # Episode 3: (s0, a1) -> (s1, a2) -> Terminal [Transition("s0", "a1", 3.0), Transition("s1", "a2", 1.0)],]
q_values, visit_counts = first_visit_mc_action_values(episodes_dataset, gamma=0.90)
# Evaluate learned action values at state s0print("--- Learned Monte Carlo Action Values at s0 ---")for action in ["a1", "a2"]: pair = ("s0", action) val = q_values.get(pair, 0.0) cnt = visit_counts.get(pair, 0) print(f"Q(s0, {action}) = {val:.3f} | Visits: {cnt}")
greedy_action = max(["a1", "a2"], key=lambda a: q_values.get(("s0", a), float("-inf")))print(f"Greedy Policy Selection: pi*(s0) = {greedy_action}")
# Expected Output:# --- Learned Monte Carlo Action Values at s0 ---# Q(s0, a1) = 4.750 | Visits: 2# Q(s0, a2) = 6.200 | Visits: 1# Greedy Policy Selection: pi*(s0) = a2Watch Out For
Action Starvation: The Greedy Policy Trap
When estimating action values to guide decisions, following a greedy policy creates a destructive feedback loop: actions with higher initial estimates are repeatedly executed, while alternative actions receive zero subsequent visits ().
Symptom: The Q-estimates for untried or lower-rated actions freeze permanently. If a stochastic transition gave an optimal action an unlucky negative reward on its very first trial, the agent will never select it again, locking into a suboptimal policy for the lifetime of the system.
The Fix: You cannot evaluate action values under a purely deterministic greedy policy without active exploration mechanisms:
- In episodic simulation, initialize episodes with Exploring Starts, guaranteeing uniform non-zero probability for every state-action pair .
- In online environments where starting pairs cannot be set arbitrarily, use stochastic exploratory policies such as -greedy exploration (choosing a random uniform action with probability ) or softmax exploration. This guarantees infinite visits to every pair as episode counts approach infinity.
The Quick Version
- Model-free control prerequisite: Unlike state values , action values do not require transition dynamics to select greedy actions.
- Empirical return averaging: Monte Carlo computes by taking the average of observed total returns following the execution of action in state across completed episodes.
- First-visit rule: Updates use only the return from the initial encounter of within each episode, preventing cyclical bias while providing unbiased estimates.
- Mandatory exploration: Because greedy policies starve unchosen actions of updates, reliable estimation requires exploring starts or -greedy exploration to guarantee full state-action coverage.