Skip to content
ELECTRONICS ENGINEERINGelectronics-engineering.com
Author's pick Reinforcement and Imitation Learning

The Bellman equations proved: contraction, value iteration and policy iteration

Bellman equation for a policy and optimality equation, the Bellman operator is a contraction (with proof), existence and uniqueness of the optimal value, policy improvement theorem, Python code on the gridworld.

https://www.electronics-engineering.com/en/bellman-equations-contraction-value-and-policy-iteration/

No ratings yet: be the first to rate this page.

The Bellman equations are the mathematical heart of reinforcement learning: they turn the definition of value, an average over infinitely many possible futures, into an equation that links the value of a state to that of the next states. All algorithms come from them, from exact ones (value and policy iteration) to those that learn from experience (Q-learning, DQN, actor-critic). This lesson derives them, proves that they have one and only one solution and that the algorithms converge, and applies them to the gridworld of the previous lesson with Python code.

The Bellman equation for a policy

Theorem. For every policy \pi and every state s:

    \[ V^\pi(s) = \sum_a\pi(a \mid s)\Big[R(s, a) + \gamma\sum_{s'}P(s' \mid s, a)\,V^\pi(s')\Big] \]

Proof. Start from the recursive relation of the return, G_t = r_{t+1} + \gamma G_{t+1}, and take the average conditioned on s_t = s:

    \[ V^\pi(s) = \mathbb E_\pi[r_{t+1} \mid s_t = s] + \gamma\,\mathbb E_\pi[G_{t+1} \mid s_t = s] \]

The first term is the average reward: a is chosen with probability \pi(a \mid s) and on average R(s, a) is received. In the second one also conditions on the next state: by the Markov property, once s_{t+1} = s' is known, the future does not depend on how it was reached, so \mathbb E_\pi[G_{t+1} \mid s_t = s, a_t = a, s_{t+1} = s'] = V^\pi(s'). Weighting with the probabilities \pi(a \mid s)P(s' \mid s, a) gives the equation. ∎

It is a linear system of |\mathcal S| equations in |\mathcal S| unknowns: in vector form V^\pi = R^\pi + \gamma P^\pi V^\pi, with solution V^\pi = (I - \gamma P^\pi)^{-1}R^\pi (the matrix is invertible for \gamma \lt  1, because \gamma P^\pi has norm less than 1). For the gridworld with the random policy this gives the values −14, −20, −22 of the previous lesson.

The optimality equation

For the optimal policy the average over actions becomes a maximum:

    \[ V^*(s) = \max_a\Big[R(s, a) + \gamma\sum_{s'}P(s' \mid s, a)\,V^*(s')\Big],\qquad Q^*(s, a) = R(s, a) + \gamma\sum_{s'}P(s' \mid s, a)\max_{a'}Q^*(s', a') \]

It is no longer linear (because of the maximum), so it is not solved by inverting a matrix: it is solved by iteration. The result that makes this possible is the following.

The Bellman contraction

Define the optimal Bellman operator T, which turns a function V into another: (TV)(s) = \max_a\big[R(s, a) + \gamma\sum_{s'}P(s' \mid s, a)V(s')\big]. The optimality equation says that V^* is a fixed point: TV^* = V^*.

Theorem. T is a contraction of factor \gamma in the max norm: for every U, V, \|TU - TV\|_\infty \le \gamma\|U - V\|_\infty.

Proof. An elementary inequality is used: for two functions f, g of a, |\max_af(a) - \max_ag(a)| \le \max_a|f(a) - g(a)| (if the maximum of f is at a_1, \max f - \max g \le f(a_1) - g(a_1), and symmetrically). Then, for every s:

    \[ |(TU)(s) - (TV)(s)| \le \max_a\gamma\Big|\sum_{s'}P(s' \mid s, a)\big(U(s') - V(s')\big)\Big| \le \gamma\max_a\sum_{s'}P(s' \mid s, a)\,\|U - V\|_\infty = \gamma\|U - V\|_\infty \]

because the probabilities P(s' \mid s, a) sum to 1. ∎

Consequences (Banach fixed-point theorem):

  • the fixed point exists and is unique: V^* is well defined;
  • starting from any V_0, the sequence V_{k+1} = TV_k converges to V^*, and the error shrinks at least by the factor \gamma at each step: \|V_k - V^*\|_\infty \le \gamma^k\|V_0 - V^*\|_\infty.

This is value iteration. On the gridworld with \gamma = 0.9 and a deliberately wrong initial estimate (50 in every cell) the maximum error goes from 46.7 to 41.3, 36.5, 32.1, …: ratios between 0.87 and 0.88, always below 0.9 as guaranteed by the theorem.

Convergence of value iteration
The maximum error, on a logarithmic scale, decreases along a straight line: at each sweep it shrinks by about 0.88, a little better than the factor 0.9 guaranteed by the theorem, the dashed grey line.

Policy improvement

Theorem (policy improvement). Given a policy \pi, let \pi' be the greedy policy with respect to Q^\pi: \pi'(s) = \arg\max_aQ^\pi(s, a). Then V^{\pi'}(s) \ge V^\pi(s) for every s.

Proof. By construction Q^\pi(s, \pi'(s)) \ge \sum_a\pi(a \mid s)Q^\pi(s, a) = V^\pi(s). Expand Q^\pi(s, \pi'(s)) = \mathbb E[r_{t+1} + \gamma V^\pi(s_{t+1})] taking \pi' at the first step, and apply the same inequality to V^\pi(s_{t+1}):

    \[ V^\pi(s) \le \mathbb E_{\pi'}[r_{t+1} + \gamma V^\pi(s_{t+1})] \le \mathbb E_{\pi'}[r_{t+1} + \gamma r_{t+2} + \gamma^2V^\pi(s_{t+2})] \le \dots \le V^{\pi'}(s) \]

repeating to infinity (the residual terms \gamma^kV^\pi tend to zero). ∎

Alternating evaluation (computing V^\pi with the linear equation) and improvement (making the policy greedy) gives policy iteration: every step improves or leaves the policy unchanged, deterministic policies are finite in number, so in a finite number of steps one reaches a policy that no longer improves, i.e. that satisfies the optimality equation. This also proves that a deterministic optimal policy always exists. The “evaluate, then improve” scheme returns in all modern algorithms: in actor-critic the critic evaluates and the actor improves.

The code

import numpy as np

N = 4                                         # 4x4 gridworld, exits at 0 and 15, -1 per step
MOVES = [(-1, 0), (1, 0), (0, -1), (0, 1)]    # up, down, left, right
EXITS = {0, 15}

def step(s, a):
    if s in EXITS:
        return s, 0.0
    r, c = divmod(s, N)
    r = min(max(r + MOVES[a][0], 0), N - 1)
    c = min(max(c + MOVES[a][1], 0), N - 1)
    return r * N + c, -1.0

def bellman_optimal(V, gamma):
    """Optimal Bellman operator T: (TV)(s) = max_a [ r + gamma V(s') ]."""
    return np.array([0.0 if s in EXITS else
                     max(r + gamma * V[s2] for s2, r in (step(s, a) for a in range(4)))
                     for s in range(N * N)])

# value iteration with gamma = 1
V = np.zeros(N * N)
for k in range(100):
    V_new = bellman_optimal(V, 1.0)
    if np.max(abs(V_new - V)) < 1e-10:
        break
    V = V_new
print("V* after", k, "sweeps:\n", V.reshape(N, N))

# evaluation of the random policy: average over the four actions instead of the maximum
Vr = np.zeros(N * N)
for _ in range(5000):
    Vr = np.array([0.0 if s in EXITS else
                   np.mean([r + Vr[s2] for s2, r in (step(s, a) for a in range(4))])
                   for s in range(N * N)])
print("random policy:\n", np.round(Vr.reshape(N, N), 1))

# greedy policy with respect to V*: the best arrow in each cell
ARROWS = "↑↓←→"
pol = [" " if s in EXITS else ARROWS[int(np.argmax([r + V[s2] for s2, r in (step(s, a) for a in range(4))]))]
       for s in range(N * N)]
print("\n".join(" ".join(pol[i * N:(i + 1) * N]) for i in range(N)))

# contraction: with gamma = 0.9 the error shrinks at least by 0.9 per sweep
Vs = np.zeros(N * N)
for _ in range(200):
    Vs = bellman_optimal(Vs, 0.9)
U = np.where(np.isin(np.arange(N * N), list(EXITS)), 0.0, 50.0)
errors = []
for _ in range(6):
    U = bellman_optimal(U, 0.9)
    errors.append(np.max(abs(U - Vs)))
print("errors:", np.round(errors, 2), "ratios:", np.round(np.array(errors[1:]) / np.array(errors[:-1]), 3))

Running it prints V^* after 3 sweeps plus the checking one (the values 0, −1, −2, −3), the values of the random policy (−14, −18, −20, −22), the grid of arrows towards the nearest exit and the errors 46.71, 41.31, 36.45, … with ratios 0.884, 0.882, 0.880, … On large problems the table V(s) does not fit in memory and P is unknown: the next lessons replace the sum over s' with experience (Q-learning) and the table with a neural network (DQN).

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
1
0
Would love your thoughts, please comment.x
()
x