---
title: Reinforcement learning
heading: Learning to act from rewards, Markov decision processes with discounted returns, Bellman's equations, value and policy iteration, Q-learning, exploration in bandit problems with upper confidence bounds, and policy gradients
eyebrow: S14 · Lesson 46 · Reinforcement learning
xp: 50
---

::: hook
Every model so far learned from examples labeled with the right answer. A battery-powered sensor deciding when to transmit, a controller tuning a power converter or a program playing a game gets no labels, only rewards, often long after the action that earned them. Reinforcement learning turns that into an optimization over policies. Its central equation, Bellman's, also underlies the optimal control of S9: the linear–quadratic regulator is a reinforcement learning problem whose answer happens to have a closed form.
:::

::: play
- An agent discounts a reward t steps away by $\gamma^t$. The solid curve is the share of a steady reward stream's total discounted value collected within the first T steps, $1 - \gamma^T$.
- The dashed curve is $\gamma^T$, the factor by which T sweeps of value iteration shrink the error in a value estimate: the same discount sets both how far ahead the agent looks and how fast planning converges.
- With γ = 0.99 the agent effectively plans about 100 steps ahead, and value iteration needs hundreds of sweeps.
:::

```sim plot
view: graph
x: T = 0..500
y: f = 0..1
slider: g = 0.5..0.999 = 0.95
plot: 1 - g^T | label: share of value within T steps
plot: g^T | dashed | label: value-iteration error left after T sweeps
```

::: predict
## An agent's discount factor is 0.99. Roughly how far ahead does it effectively plan?

- [ ] 1 step
- [ ] 10 steps
- [x] 100 steps
- [ ] 10,000 steps

::: reveal
A steady reward r is worth $r/(1 - \gamma)$ = 100r in total, as if the agent counted the next $1/(1 - \gamma)$ = 100 steps fully and ignored the rest; 63% of that value comes within the first 100 steps. The discount is a horizon setting: 0.9 looks about 10 steps ahead, 0.999 about 1000.
:::
:::

::: nameit
## Markov decision processes

At each step the agent sees a state s, takes an action a, receives a reward r and moves to a new state with probability $P(s'|s, a)$. It seeks a policy π, a rule for choosing actions, that maximizes the expected **return** $G = \sum_t\gamma^tr_t$, with discount 0 ≤ γ < 1.

## Values and Bellman's equations

A policy's **value** $V^\pi(s)$ is its expected return from s; the **action value** $Q^\pi(s, a)$ is the return from taking a first and following π afterward. Values satisfy
$$V^\pi(s) = \sum_a\pi(a|s)\Big[R(s, a) + \gamma\sum_{s'}P(s'|s, a)V^\pi(s')\Big]$$
a linear system, $V = (I - \gamma P_\pi)^{-1}R_\pi$, for a fixed policy. The optimal values satisfy **Bellman's optimality equation**
$$V^*(s) = \max_a\Big[R(s, a) + \gamma\sum_{s'}P(s'|s, a)V^*(s')\Big]$$
and acting greedily with respect to $V^*$ is optimal.

## Planning with a model

**Value iteration** applies the optimality equation as an update. Each sweep shrinks the largest error by at least γ, so reaching a fraction ε of the starting error takes $\ln\epsilon/\ln\gamma$ sweeps. **Policy iteration** alternates solving for $V^\pi$ exactly and making π greedy; it usually converges in a handful of iterations.

## Learning without a model

**Q-learning** updates after every step from what actually happened:
$$Q(s, a) \leftarrow Q(s, a) + \alpha\Big[r + \gamma\max_{a'}Q(s', a') - Q(s, a)\Big]$$
It converges to $Q^*$ if every state–action pair keeps being tried, which needs **exploration**: the ε-greedy rule takes a random action a fraction ε of the time. With a neural network in place of the table, this is deep Q-learning.

## Exploration in bandits

With one state and K actions of unknown mean reward (a **bandit**), the UCB1 rule picks the action maximizing
$$\bar x_a + \sqrt{\frac{2\ln t}{n_a}}$$
where $n_a$ is how often a has been tried in t steps. The bonus shrinks as an action is tried, so poorly known actions get tested, and the total shortfall against always choosing the best action (the **regret**) grows only as ln t.

## Policy gradients

A parameterized policy $\pi_\theta$ can be improved directly by gradient ascent on its expected return: $\nabla J = \mathbb E[G\,\nabla\ln\pi_\theta(a|s)]$, estimated from sampled episodes (REINFORCE). Subtracting a baseline, such as an estimate of V(s), from G reduces the estimate's variance without biasing it.
:::

::: example
## A sensor earns a reward of 1 per step while charged, and goes low with probability 0.2 per step; while low it earns nothing and recharges with probability 0.5. With γ = 0.9, what is each state worth?

::: solution
1. **Bellman equations.**
   $$\begin{aligned} V_c &= 1 + 0.9(0.8V_c + 0.2V_l) \\ V_l &= 0.9(0.5V_c + 0.5V_l) \end{aligned}$$
2. **Solve.** The second gives $V_l = 0.818V_c$; put that in the first:
   $$\begin{aligned} V_c &= \frac{1}{1 - 0.72 - 0.18 \times 0.818} \\ &= 7.53 \\ V_l &= 0.818 \times 7.53 \\ &= 6.16 \end{aligned}$$
3. **Read it.** The low state is worth almost as much as the charged one because it recharges quickly.
4. **Check.** Over the long run the sensor is charged 0.5/0.7 = 71% of the time, and
   $$0.71/(1 - 0.9) = 7.1$$
   is the average of the two values, weighted by that share.

**Answer:** the charged state is worth 7.53 and the low state 6.16.
:::
:::

::: example
## Q(s, a) = 2.0. The agent takes a, receives r = 1 and lands where the best action value is 3.0. With γ = 0.9 and α = 0.1, what is the update? And how many value-iteration sweeps shrink an initial error of 10 below 0.001?

::: solution
1. **Target.**
   $$\begin{aligned} \text{target} &= 1 + 0.9 \times 3.0 \\ &= 3.7 \end{aligned}$$
2. **Update.** The error is 1.7, so
   $$\begin{aligned} Q &= 2.0 + 0.17 \\ &= 2.17 \end{aligned}$$
3. **Value-iteration sweeps.** $0.9^k \le 10^{-4}$ needs
   $$\begin{aligned} k &\ge \ln 10^{-4}/\ln 0.9 \\ &= 87.4 \end{aligned}$$
   so 88 sweeps.
4. **Compare.** Each Q-learning step moves only one entry a tenth of the way, which is why model-free learning needs far more experience than planning with a known model needs sweeps.

**Answer:** Q becomes 2.17, and value iteration needs 88 sweeps.
:::
:::

::: example
## After 1000 pulls of a bandit, action A has averaged 0.60 over 100 pulls and action B 0.50 over 10. Which does UCB1 pick next?

::: solution
1. **Bonuses.**
   $$\begin{aligned} b_A &= \sqrt{2\ln 1000/100} \\ &= 0.37 \\ b_B &= \sqrt{2\ln 1000/10} \\ &= 1.18 \end{aligned}$$
2. **Indices.**
   $$\begin{aligned} 0.60 + 0.37 &= 0.97 \\ 0.50 + 1.18 &= 1.68 \end{aligned}$$
   so UCB1 tries B again: with only 10 pulls, B's true mean could well exceed A's.
3. **Later on.** As B's count grows its bonus falls, and if B really is worse, it gets tried only about ln t times more.

**Answer:** UCB1 picks B, whose index of 1.68 beats A's 0.97.
:::
:::

::: check
kind: parts
given: g = 0.9 | 0.95 | 0.99 | 0.999; r = 1 | 5

## An agent with discount {g} receives a steady reward of {r} per step.

::: part
answer: r/(1 - g)
tolerance: 0.5%

### What is the stream's discounted value?

::: misses
- [r/g] The geometric series sums to $1/(1 - \gamma)$.
- [any] $r/(1 - \gamma)$.
:::
:::

::: part
answer: 1/(1 - g)
unit: steps
tolerance: 0.5%

### What is its effective horizon?

::: misses
- [any] $1/(1 - \gamma)$.
:::
:::
:::

::: check
kind: parts
given: g = 0.8 | 0.95 | 0.99; e = 0.01 | 0.000001

## Value iteration runs with discount {g}.

::: part
answer: ln(e)/ln(g)
unit: sweeps
tolerance: 0.5%

### How many sweeps shrink the error by a factor of {e}?

::: misses
- [-log(e)/(1 - g)] Close for γ near 1; the exact count is $\ln\epsilon/\ln\gamma$.
- [any] $\gamma^k = \epsilon$.
:::
:::
:::

::: check
kind: parts
given: Q = 0 | 1.5; r = -1 | 2; g = 0.9 | 0.99; M = 3 | 10; a = 0.05 | 0.5

## Q(s, a) = {Q}. The agent receives r = {r} and lands where the best action value is {M}; γ = {g} and the learning rate is {a}.

::: part
answer: r + g*M - Q
tolerance: 0.5%

### What is the temporal-difference error?

::: misses
- [r + M - Q] Discount the next state's value.
- [any] $r + \gamma\max Q' - Q$.
:::
:::

::: part
answer: Q + a*(r + g*M - Q)
tolerance: 0.5%

### What does Q(s, a) become?

::: misses
- [r + g*M] That's the target; Q moves only a fraction α toward it.
- [any] $Q + \alpha\delta$.
:::
:::
:::

::: check
kind: parts
given: r = 1 | 3; u = 0 | -1; a = 0.1 | 0.3; b = 0.2 | 0.6; g = 0.8 | 0.95

## A fixed policy earns {r} per step in state 1 and {u} in state 2. It moves from state 1 to 2 with probability {a} and from 2 to 1 with probability {b}; γ = {g}.

::: part
answer: (r*(1 - g + g*b) + g*a*u)/((1 - g + g*a)*(1 - g + g*b) - g^2*a*b)
tolerance: 0.5%

### What is state 1 worth?

::: misses
- [r/(1 - g)] That assumes it stays in state 1 forever.
- [any] Solve $V = R + \gamma PV$ for the two states.
:::
:::

::: part
answer: (u*(1 - g + g*a) + g*b*r)/((1 - g + g*a)*(1 - g + g*b) - g^2*a*b)
tolerance: 0.5%

### And state 2?

::: misses
- [any] The second row of the same system.
:::
:::
:::

::: check
kind: parts
given: x = 0.3 | 0.7; t = 100 | 10000; n = 5 | 50 | 500

## A bandit action has averaged {x} over {n} of {t} pulls.

::: part
answer: x + sqrt(2*ln(t)/n)
tolerance: 0.5%

### What is its UCB1 index?

::: misses
- [x + sqrt(2*log(t)/n)] UCB1 uses the natural log.
- [x + sqrt(2*ln(t))/n] The square root covers the whole ratio.
- [any] $\bar x + \sqrt{2\ln t/n}$.
:::
:::
:::

::: check
kind: parts
given: e = 0.05 | 0.1 | 0.3; K = 2 | 4 | 10

## An ε-greedy agent with ε = {e} chooses among {K} actions.

::: part
answer: 1 - e + e/K
tolerance: 0.5%

### How often does it take the greedy action?

::: misses
- [1 - e] The random choice also lands on the greedy action a fraction 1/K of the time.
- [any] $1 - \epsilon + \epsilon/K$.
:::
:::
:::

::: check
kind: choice

## Why does Q-learning need exploration even though it learns the value of the greedy policy?

- [ ] Exploration makes the updates converge faster for the actions already tried
- [x] Q values change only for actions actually taken, so an action that looks poor early is never corrected unless it keeps being tried
- [ ] The discount factor requires random actions
- [ ] Random actions reduce the variance of the rewards

::: misses
- [1] Exploring spends steps on other actions, slowing the tried ones.
- [3] Discounting has nothing to do with it.
- [4] Exploration adds variance to the returns, if anything.
:::
:::

::: check
kind: derivation
vars: r = -2..5, u = -2..5, a = 0.05..0.95, b = 0.05..0.95, g = 0.5..0.99

## A fixed policy earns r in state 1 and u in state 2, moving 1 → 2 with probability a and 2 → 1 with probability b; discount γ.

::: step
answer: (r*(1 - g + g*b) + g*a*u)/((1 - g + g*a)*(1 - g + g*b) - g^2*a*b)

### What is $V_1$?
:::

::: step
answer: (u*(1 - g + g*a) + g*b*r)/((1 - g + g*a)*(1 - g + g*b) - g^2*a*b)

### What is $V_2$?
:::

::: right
Right. Policy evaluation is a linear solve, $V = (I - \gamma P)^{-1}R$.
:::
:::

::: check
kind: python

## Write `value_iteration(P, R, gamma, tol)` for a finite MDP: `P[s][a]` is a list of (probability, next state) pairs and `R[s][a]` the reward. Iterate until no value changes by more than tol, and return (values, greedy policy) as lists.

```python starter
def value_iteration(P, R, gamma, tol):
    return [0.0] * len(P), [0] * len(P)
```

```python solution
def value_iteration(P, R, gamma, tol):
    n = len(P)
    V = [0.0] * n
    while True:
        Q = [[R[s][a] + gamma * sum(p * V[t] for p, t in P[s][a]) for a in range(len(P[s]))] for s in range(n)]
        V2 = [max(q) for q in Q]
        done = max(abs(V2[s] - V[s]) for s in range(n)) < tol
        V = V2
        if done:
            pol = [max(range(len(Q[s])), key=lambda a: Q[s][a]) for s in range(n)]
            return V, pol
```

```python tests
P = [[[(0.7, 0), (0.3, 1)], [(1.0, 0)]], [[(1.0, 1)], [(0.6, 0), (0.4, 1)]]]
R = [[1.0, 0.0], [0.5, 0.0]]
V, pol = value_iteration(P, R, 0.9, 1e-10)
assert pol == [0, 1], "Transmit when charged, sleep when low."
assert abs(V[0] - 7.032967) < 1e-5 and abs(V[1] - 5.934066) < 1e-5, "V* = (7.033, 5.934)."
V2, pol2 = value_iteration(P, R, 0.5, 1e-10)
assert pol2 == [0, 0], "A short-sighted agent transmits weakly rather than waiting to recharge."
```

::: right
Right. A sensor that transmits when charged and sleeps when low: with γ = 0.9 waiting is worth it; with γ = 0.5 it isn't.
:::
:::

::: explain
## Why does every action's value depend on what the agent will do afterward?

::: model
An action's worth isn't just its immediate reward: it also moves the agent to a new state, from which future rewards depend on the actions taken there. So its value is the reward plus the discounted value of where it leads, under whatever policy follows, which is Bellman's equation. That recursion is what lets a reward earned much later be credited to the early action that made it possible: values propagate backward through the states, one step per sweep of value iteration or per visit in Q-learning, until every state's value reflects the best reachable future.
:::
:::

::: practice
::: check
given: g = 0.9 | 0.98; r = 2 | 10
answer: r/(1 - g)
tolerance: 0.5%

## Discounted value of {r} per step at γ = {g}?

::: misses
- [any] $r/(1 - \gamma)$.
:::
:::

::: check
given: Q = 1 | 4; r = 0 | 1; M = 2 | 5; a = 0.1 | 0.2
answer: Q + a*(r + 0.9*M - Q)
tolerance: 0.5%

## Q-learning: Q = {Q}, r = {r}, max Q′ = {M}, α = {a}, γ = 0.9?

::: misses
- [any] $Q + \alpha(r + \gamma\max Q' - Q)$.
:::
:::

::: check
given: x = 0.4 | 0.8; t = 500 | 50000; n = 20 | 200
answer: x + sqrt(2*ln(t)/n)
tolerance: 0.5%

## UCB1 index: mean {x}, {n} of {t} pulls?

::: misses
- [any] $\bar x + \sqrt{2\ln t/n}$.
:::
:::
:::
