> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# ε-greedy Monte-Carlo Control

> On-policy Monte Carlo control with ε-greedy policies.

In this section the agent learns an optimal policy when the MDP is *unknown*: the *model-free* control problem. Most of the section is about *on-policy* methods, in which the agent improves the same policy $\pi$ that it uses to act and generate experience. The last part covers *off-policy* methods, which learn about a *target policy* $\pi$ from experience generated by a different *behavior policy* $b$.

## Control with action values

[Monte-Carlo Prediction](https://aegean.ai/aiml-common/lectures/reinforcement-learning/value-based-algorithms/prediction/monte-carlo.md) estimates state values without a model. Greedy policy improvement with respect to $V$,

$\pi^\prime(s) = \arg \max_{a \in \mathcal A} \sum_{s'} p(s' \mid s, a) [ r(s, a) + \gamma V(s') ],$

needs the dynamics $p(s' \mid s, a)$, which a model-free agent does not have. **The way out is to estimate the action values $Q(s,a)$ instead and improve the policy greedily with respect to them:**

$\pi^\prime(s) = \arg \max_{a \in \mathcal A} Q(s,a).$

Alternating the two steps is generalized policy iteration with action values:

![generalized-policy-iteration](https://mintcdn.com/aegeanaiinc/CFTczIUu7w-BdE7V/aiml-common/lectures/reinforcement-learning/value-based-algorithms/control/greedy-monte-carlo/images/generalized-policy-iteration.png?fit=max\&auto=format\&n=CFTczIUu7w-BdE7V\&q=85\&s=5fa301c8c9394376973b5d1444e23f3a)

*Generalized policy iteration with the action-value function: evaluation moves $Q$ toward $q_\pi$, and improvement makes $\pi$ greedy with respect to $Q$.*

## Maintaining exploration

A deterministic policy takes only one action in each state. The agent then sees returns for that action only, and the estimates of the other actions never improve. Choosing among actions needs estimates for all of them, so the agent must keep trying actions it does not currently favor (Sutton & Barto, 2018).

One way to do this is *exploring starts*: every episode starts in a random state-action pair, and every pair has a nonzero probability of being the start. Exploring starts are rarely possible when the agent learns from real interaction, for example on a robot, because the agent cannot choose the state it starts in.

The other way is to keep the policy itself stochastic. A policy is *$\epsilon$-soft* if every action has probability at least $\epsilon/|\mathcal A|$ in every state. The *$\epsilon$-greedy* policy is the $\epsilon$-soft policy closest to greedy. With probability $1-\epsilon$ it takes the greedy action $\arg\max_a Q(s,a)$, and with probability $\epsilon$ it picks an action uniformly at random from all $|\mathcal A|$ actions. The greedy action therefore has probability $1-\epsilon+\epsilon/|\mathcal A|$, and every other action has probability $\epsilon/|\mathcal A|$.

### ε-greedy policy improvement

Policy improvement still works within $\epsilon$-soft policies. Let $\pi$ be $\epsilon$-soft and let $\pi'$ be $\epsilon$-greedy with respect to $q_\pi$. Then, for every state $s$,

$$
\begin{aligned}
\sum_a \pi'(a \mid s)\, q_\pi(s,a) &= \frac{\epsilon}{|\mathcal A|} \sum_a q_\pi(s,a) + (1-\epsilon) \max_a q_\pi(s,a) \\
&\ge \frac{\epsilon}{|\mathcal A|} \sum_a q_\pi(s,a) + (1-\epsilon) \sum_a \frac{\pi(a \mid s) - \epsilon/|\mathcal A|}{1-\epsilon}\, q_\pi(s,a) \\
&= \sum_a \pi(a \mid s)\, q_\pi(s,a) = v_\pi(s).
\end{aligned}
$$

The inequality holds because the weights $\bigl(\pi(a \mid s) - \epsilon/|\mathcal A|\bigr)/(1-\epsilon)$ are nonnegative and sum to 1, and a weighted average is never larger than the maximum. By the policy improvement theorem, $v_{\pi'}(s) \ge v_\pi(s)$ in every state. **Repeating evaluation and $\epsilon$-greedy improvement converges to the best $\epsilon$-soft policy, which is not the optimal policy**: it still takes a random action with probability $\epsilon$.

### GLIE

To reach the optimal policy, exploration has to fade without stopping. A schedule is *greedy in the limit with infinite exploration* (GLIE) if

1. every state-action pair is visited infinitely often, and
2. the policy converges to the greedy policy with respect to $Q$.

A common schedule is $\epsilon_k = 1/k$ in episode $k$. It makes the policy greedy in the limit, but it does not by itself guarantee the first condition. If a state-action pair can be reached only through two exploratory actions in a row, its probability of being visited in episode $k$ can fall like $1/k^2$, and the sum of those probabilities is finite. A schedule is GLIE only if it decays slowly enough for every pair of the task to keep being visited. Monte Carlo control with a GLIE policy converges to $q_*$ and to an optimal policy. The convergence results for [SARSA](https://aegean.ai/aiml-common/lectures/reinforcement-learning/value-based-algorithms/control/sarsa/index.md) and [Q-learning](https://aegean.ai/aiml-common/lectures/reinforcement-learning/value-based-algorithms/control/q-learning/index.md) rest on the same two conditions.

## On-policy MC control

Putting the pieces together gives on-policy first-visit MC control for $\epsilon$-soft policies:

```text theme={null}
Input: a small ε > 0
Initialize Q(s, a) arbitrarily and an empty list Returns(s, a), for every pair (s, a)
Initialize π to an arbitrary ε-soft policy
Loop for each episode:
    Generate an episode with π: S_0, A_0, R_1, ..., S_{T-1}, A_{T-1}, R_T
    G ← 0
    For t = T-1, T-2, ..., 0:
        G ← γ G + R_{t+1}
        If the pair (S_t, A_t) does not occur among (S_0, A_0), ..., (S_{t-1}, A_{t-1}):
            Append G to Returns(S_t, A_t)
            Q(S_t, A_t) ← mean of Returns(S_t, A_t)
            A* ← argmax_a Q(S_t, a)                    (ties broken at random)
            For every action a:
                π(a | S_t) ← 1 − ε + ε/|A|  if a = A*,  else ε/|A|
```

The policy changes after every episode, using the returns of that episode only. For a GLIE schedule, decrease $\epsilon$ between episodes.

## Off-policy MC with importance sampling

An on-policy method compromises: it learns the values of a policy that keeps exploring. An off-policy method separates the two jobs. The behavior policy $b$ explores and generates the episodes, and the target policy $\pi$, often the greedy policy, is the one being evaluated and improved. This requires *coverage*: every action that $\pi$ can take must have a nonzero probability under $b$, so $\pi(a \mid s) > 0$ implies $b(a \mid s) > 0$.

Returns generated by $b$ have the wrong expectation for $\pi$. *Importance sampling* corrects for this by weighting each return with the relative probability of its trajectory under the two policies. Given $S_t$, the probability of the rest of the trajectory under a policy is a product of policy and transition probabilities, and the transition probabilities cancel in the ratio:

$$
\rho_{t:T-1} = \frac{\prod_{k=t}^{T-1} \pi(A_k \mid S_k)\, p(S_{k+1} \mid S_k, A_k)}{\prod_{k=t}^{T-1} b(A_k \mid S_k)\, p(S_{k+1} \mid S_k, A_k)} = \prod_{k=t}^{T-1} \frac{\pi(A_k \mid S_k)}{b(A_k \mid S_k)}.
$$

The ratio depends only on the two policies, not on the unknown dynamics, and it corrects the expectation: $\mathbb{E}_b[\rho_{t:T-1} G_t \mid S_t = s] = v_\pi(s)$.

Let $\mathcal T(s)$ be the set of time steps at which $s$ is visited for the first time in an episode, across all the episodes collected so far. Two estimators follow:

$$
\begin{aligned}
V_{\text{ordinary}}(s) &= \frac{\sum_{t \in \mathcal T(s)} \rho_{t:T(t)-1}\, G_t}{|\mathcal T(s)|}, \\
V_{\text{weighted}}(s) &= \frac{\sum_{t \in \mathcal T(s)} \rho_{t:T(t)-1}\, G_t}{\sum_{t \in \mathcal T(s)} \rho_{t:T(t)-1}},
\end{aligned}
$$

where $T(t)$ is the end of the episode that contains $t$. **Ordinary importance sampling is unbiased, but its variance can be unbounded**, because a single ratio can be very large. Weighted importance sampling is biased, and the bias goes to zero as the number of returns grows. If $\mathcal T(s)$ includes every visit instead of the first, both estimators are biased for a finite number of episodes, and the bias again vanishes as the number of episodes grows (Sutton & Barto, 2018). Its variance is much lower, so it is the usual choice in practice (Sutton & Barto, 2018). Weighted importance sampling also has an incremental form. With $W = \rho_{t:T-1}$ the weight of the new return and $C(s)$ the running sum of weights,

$$
\begin{aligned}
C(s) &\leftarrow C(s) + W, \\
V(s) &\leftarrow V(s) + \frac{W}{C(s)} \bigl[ G - V(s) \bigr].
\end{aligned}
$$

The ratio is a product over the whole rest of the episode, and that causes the main difficulty. If the target policy is greedy, $\pi(A_k \mid S_k) = 0$ for every exploratory action, so the ratio, and with it the weight of the return, is zero as soon as $b$ explores. Only the tail of each episode after the last exploratory action carries information, and learning is slow when episodes are long.

[SARSA](https://aegean.ai/aiml-common/lectures/reinforcement-learning/value-based-algorithms/control/sarsa/index.md) replaces the MC return with a one-step TD target, so the policy improves after every step instead of after every episode. [Q-learning](https://aegean.ai/aiml-common/lectures/reinforcement-learning/value-based-algorithms/control/q-learning/index.md) is an off-policy method whose one-step target needs no importance-sampling ratio at all.

**Key references**: (Sutton & Barto, 2018)

## References

* Sutton, R., Barto, A. (2018). *Reinforcement Learning: An Introduction*. [Link](https://www.andrew.cmu.edu/course/10-703/textbook/BartoSutton.pdf)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/reinforcement-learning/value-based-algorithms/control/greedy-monte-carlo).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.