Velamuvi AIAcademy

Lesson 4 of 12 · Foundations

Value Functions

Value functions V and Q explained: the Bellman expectation and optimality equations, policy evaluation, and value iteration on a grid world in NumPy.

  • 16 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Explain what the value functions V and Q measure, and how they relate
  • Write the Bellman expectation and optimality equations, and say what each one means
  • Evaluate a policy with iterative policy evaluation
  • Find the optimal values of a grid world with value iteration
  • Extract the greedy policy from the values

The idea in plain words

A sat-nav shows "12 minutes to go" wherever you are on the route. That one number sums up the whole rest of the drive from here, as long as you follow its directions. A value function does the same for an agent: for every state, it gives the return the agent can expect from that state onwards, if it follows a given policy.

Values make good decisions easy. If you know how good every state is, you choose the action that leads to the best one, just as a driver at a junction takes the road with the shortest time to go. That's why almost every RL method, from Q-learning to the actor-critic methods at the end of this course, is built around estimating values. This lesson computes them exactly, for problems where the MDP is fully known.

V and Q

There are two kinds of value function. Both depend on the policy π the agent follows, which is why they carry a small π:

V_π(s)    = the expected return when starting in state s and following π
Q_π(s, a) = the expected return when starting in state s, taking action a first, then following π

In Markov Decision Processes, simulation estimated that a new machine under the policy "repair when worn" was worth about 58.1 ± 0.8. That number was an estimate of V_π(new). Q answers a more specific question: how much is it worth to repair a worn machine today, and then carry on with the policy? The two are linked. V averages Q over the actions the policy would take, and Q is the reward of one step plus the discounted V of wherever that step leads:

V_π(s)    = Σ over a of  π(a | s) × Q_π(s, a)
Q_π(s, a) = R(s, a) + γ × Σ over s′ of  P(s′ | s, a) × V_π(s′)

The Bellman expectation equation

Put the two lines together and you get the most important equation in RL, named after Richard Bellman, who studied it in the 1950s:

V_π(s) = Σ over a of π(a | s) × [ R(s, a) + γ × Σ over s′ of P(s′ | s, a) × V_π(s′) ]

in words: the value of a state = the average, over the policy's actions and the possible
          outcomes, of (the reward now + γ × the value of the next state)

A value is a promise about the future, and the Bellman equation says that promise must agree with itself one step later. If the sat-nav says 12 minutes here, and the next stretch takes 2 minutes, it had better say 10 minutes at the next junction. For a deterministic policy the sum over actions has only one term, the action π(s), so V_π(s) = R(s, π(s)) + γ × Σ P(s′ | s, π(s)) × V_π(s′).

Iterative policy evaluation

The equation defines V_π, but V_π appears on both sides. Iterative policy evaluation solves it by repetition: start with V = 0 everywhere, then use the right-hand side to compute a new V for every state, and repeat. Each repetition is a sweep. Here it is on the machine MDP:

Try it yourselfPython
import numpy as np

# The machine MDP from Markov Decision Processes: states new, worn, broken; actions run, repair
P = np.zeros((3, 2, 3))
P[0, 0] = [0.7, 0.3, 0.0]
P[1, 0] = [0.0, 0.6, 0.4]
P[2, 0] = [0.0, 0.0, 1.0]
P[:, 1] = [1.0, 0.0, 0.0]
R = np.array([[10.0, -10.0], [6.0, -10.0], [0.0, -20.0]])
gamma = 0.9

def evaluate(policy, show=False):
    """Iterative policy evaluation: sweep the Bellman expectation equation until V stops changing."""
    V = np.zeros(3)
    for sweep in range(1, 1000):
        V_new = np.array([R[s, policy[s]] + gamma * P[s, policy[s]] @ V for s in range(3)])
        change = np.max(np.abs(V_new - V))
        V = V_new
        if show and (sweep <= 3 or sweep % 50 == 0 or change < 1e-6):
            print(f"sweep {sweep:>3}: V(new) {V[0]:6.2f}   V(worn) {V[1]:6.2f}   V(broken) {V[2]:6.2f}")
        if change < 1e-6:
            return V

print('Policy "repair when broken":')
evaluate([0, 0, 1], show=True)
print()
for name, policy in [("never repair", [0, 0, 0]), ("repair when broken", [0, 0, 1]), ("repair when worn", [0, 1, 1])]:
    print(f"{name:<19} V(new) = {evaluate(policy)[0]:.2f}")
Output
Policy "repair when broken":
sweep   1: V(new)  10.00   V(worn)   6.00   V(broken) -20.00
sweep   2: V(new)  17.92   V(worn)   2.04   V(broken) -11.00
sweep   3: V(new)  21.84   V(worn)   3.14   V(broken)  -3.87
sweep  50: V(new)  51.48   V(worn)  33.59   V(broken)  26.31
sweep 100: V(new)  51.69   V(worn)  33.80   V(broken)  26.52
sweep 146: V(new)  51.69   V(worn)  33.80   V(broken)  26.52

never repair        V(new) = 36.55
repair when broken  V(new) = 51.69
repair when worn    V(new) = 57.48

Each sweep looks one step further into the future. After sweep 1, V is just the reward of the first day: 10, 6 and −20. After sweep 2 it includes the discounted second day, and so on, until the values stop changing. The exact values agree with the simulation in Markov Decision Processes, which estimated 36.3 ± 0.9, 51.9 ± 0.8 and 58.1 ± 0.8: each estimate was within its margin of the truth. The sweeps needed no random runs at all, only the model P and R.

From values to a better policy

Q-values compare actions. From V_π, one line computes Q_π(s, a) for every state and action, using Q = R + γ × Σ P × V. Here they are for "repair when broken":

Try it yourselfPython
import numpy as np

P = np.zeros((3, 2, 3))
P[0, 0] = [0.7, 0.3, 0.0]
P[1, 0] = [0.0, 0.6, 0.4]
P[2, 0] = [0.0, 0.0, 1.0]
P[:, 1] = [1.0, 0.0, 0.0]
R = np.array([[10.0, -10.0], [6.0, -10.0], [0.0, -20.0]])
gamma = 0.9

def evaluate(policy):
    V = np.zeros(3)
    while True:
        V_new = np.array([R[s, policy[s]] + gamma * P[s, policy[s]] @ V for s in range(3)])
        if np.max(np.abs(V_new - V)) < 1e-6:
            return V_new
        V = V_new

V = evaluate([0, 0, 1])                    # the values of "repair when broken"
Q = R + gamma * P @ V                      # Q(s, a) = R(s, a) + γ Σ P(s'|s, a) V(s'), all at once
for s, name in enumerate(["new", "worn", "broken"]):
    print(f"{name:<6}  Q(run) {Q[s, 0]:6.2f}   Q(repair) {Q[s, 1]:6.2f}   -> best: {['run', 'repair'][Q[s].argmax()]}")
Output
new     Q(run)  51.69   Q(repair)  36.52   -> best: run
worn    Q(run)  33.80   Q(repair)  36.52   -> best: repair
broken  Q(run)  23.87   Q(repair)  26.52   -> best: repair

The policy runs a worn machine, but its own Q-values say that repairing it is worth more: 36.52 against 33.80. Switching to the action with the best Q in every state gives "repair when worn", and the previous program showed that it is indeed better: 57.48 instead of 51.69 for a new machine. This is policy improvement, and it always works: acting greedily on a policy's Q-values gives a policy at least as good. Alternating evaluation and improvement until the policy stops changing is called policy iteration, and it ends at an optimal policy.

The Bellman optimality equation

The best possible values, V* and Q*, satisfy their own Bellman equation. Instead of averaging over the actions of a fixed policy, it takes the best action:

V*(s)    = max over a of [ R(s, a) + γ × Σ over s′ of P(s′ | s, a) × V*(s′) ]
Q*(s, a) = R(s, a) + γ × Σ over s′ of P(s′ | s, a) × (max over a′ of Q*(s′, a′))

in words: the best value of a state = the best action's (reward now + γ × best value of the next state)

The max makes these equations non-linear, so there's no direct formula, but repetition works again.

Value iteration on a grid world

Value iteration sweeps the optimality equation: start with V = 0, and in every sweep set each state's value to its best one-step look-ahead, until nothing changes. The grid world below has a goal G worth +10 and a trap T worth −10, which both end the episode, and a wall #. Every other move costs 1, and a move into the wall or the edge leaves the agent where it is. The ends are absorbing states, as in Markov Decision Processes. With P and R as arrays, P @ V computes Σ P(s′ | s, a) × V(s′) for every state and action at once:

Try it yourselfPython
import numpy as np

GRID = ["...G",      # G: goal, +10       T: trap, -10       #: wall
        ".#.T",      # every other move costs 1, and G and T end the episode
        "....",
        "S..."]
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]          # up, right, down, left
gamma = 0.9

# Build the MDP: P[s, a, s2] and R[s, a] for the 16 cells, s = row * 4 + column
P, R = np.zeros((16, 4, 16)), np.zeros((16, 4))
for s in range(16):
    row, col = divmod(s, 4)
    for a, (dr, dc) in enumerate(MOVES):
        if GRID[row][col] in "GT#":                  # an end (or the wall): absorbing, reward 0
            P[s, a, s] = 1
            continue
        r2, c2 = row + dr, col + dc
        if not (0 <= r2 < 4 and 0 <= c2 < 4) or GRID[r2][c2] == "#":
            r2, c2 = row, col                        # bumped into the edge or the wall: stay put
        P[s, a, r2 * 4 + c2] = 1
        R[s, a] = {"G": 10, "T": -10}.get(GRID[r2][c2], -1)

def show(V):
    for row in range(4):
        print(" ".join(f"{GRID[row][col]:>5}" if GRID[row][col] in "GT#" else f"{V[row * 4 + col]:5.1f}"
                       for col in range(4)))

V = np.zeros(16)
for sweep in range(1, 100):
    Q = R + gamma * P @ V                            # the Bellman optimality backup, for every s and a
    V_new = Q.max(axis=1)
    if sweep <= 2:
        print(f"after sweep {sweep}:")
        show(V_new)
    if np.max(np.abs(V_new - V)) < 1e-6:
        break
    V = V_new
print(f"converged after sweep {sweep}:")
show(V)

policy = (R + gamma * P @ V).argmax(axis=1)          # the greedy policy: one step of look-ahead
print("greedy policy:")
for row in range(4):
    print(" ".join(GRID[row][col] if GRID[row][col] in "GT#" else "↑→↓←"[policy[row * 4 + col]] for col in range(4)))

s, G, moves = 12, 0.0, []                            # follow the policy from S (cell 12)
for t in range(10):
    a = policy[s]
    G += gamma ** t * R[s, a]
    moves.append(["up", "right", "down", "left"][a])
    s = int(P[s, a].argmax())                        # moves are certain: the next cell is where P is 1
    if GRID[s // 4][s % 4] in "GT":
        break
print("from S:", " ".join(moves), f"-> return {G:.2f}, and V(S) = {V[12]:.2f}")
Output
after sweep 1:
 -1.0  -1.0  10.0     G
 -1.0     #  -1.0     T
 -1.0  -1.0  -1.0  -1.0
 -1.0  -1.0  -1.0  -1.0
after sweep 2:
 -1.9   8.0  10.0     G
 -1.9     #   8.0     T
 -1.9  -1.9  -1.9  -1.9
 -1.9  -1.9  -1.9  -1.9
converged after sweep 7:
  6.2   8.0  10.0     G
  4.6     #   8.0     T
  3.1   4.6   6.2   4.6
  1.8   3.1   4.6   3.1
greedy policy:
→ → → G
↑ # ↑ T
↑ → ↑ ←
↑ ↑ ↑ ↑
from S: up up up right right right -> return 1.81, and V(S) = 1.81

Watch the good news spread. After sweep 1, only the cell next to G knows about the goal: its value is 10. After sweep 2, the cells two moves away have −1 + 0.9 × 10 = 8. Each sweep carries the information one cell further, so after 6 sweeps it reaches the far corner, and sweep 7 confirms that nothing changes any more. The cell below the trap is worth 4.6, not −10: the best action there is to step left, away from it.

Extracting the greedy policy

Optimal values are not yet a policy, but one step of look-ahead turns them into one: in every state, take the action with the best reward-plus-value, which is exactly the Q-value:

π*(s) = the action a with the largest  R(s, a) + γ × Σ over s′ of P(s′ | s, a) × V*(s′)  =  Q*(s, a)

The arrows in the output are this greedy policy. Following it from S takes six moves to G, and its return, 1.81, matches V(S), as it should for an optimal policy. Where two actions tie, such as up and right in the bottom row, argmax picks the first one; both are equally good. Notice that this look-ahead needs the model, P and R. With Q* you can skip it, because π*(s) is simply the action with the largest Q*(s, a). That's why Q-Learning, which never sees P or R, learns Q rather than V. In Solving a Grid World, you'll make the floor slippery and watch value iteration change its mind about the route.

Common mistakes

Practice

Practice exercise

For a fixed policy, the Bellman expectation equation is just a set of linear equations, one per state, so a small MDP can be evaluated in one step instead of many sweeps. Complete evaluate so that it solves them, and print V(new), V(worn) and V(broken) for two policies. Check that you get the same values as the sweeps.

Your solutionPython
import numpy as np

P = np.zeros((3, 2, 3))
P[0, 0] = [0.7, 0.3, 0.0]
P[1, 0] = [0.0, 0.6, 0.4]
P[2, 0] = [0.0, 0.0, 1.0]
P[:, 1] = [1.0, 0.0, 0.0]
R = np.array([[10.0, -10.0], [6.0, -10.0], [0.0, -20.0]])
gamma = 0.9

def evaluate(policy):
    P_pi = np.array([P[s, policy[s]] for s in range(3)])     # transitions under the policy
    R_pi = np.array([R[s, policy[s]] for s in range(3)])     # rewards under the policy
    # V = R_pi + gamma * P_pi @ V is 3 linear equations with 3 unknowns.
    # Rearrange it to (I - gamma * P_pi) @ V = R_pi, and solve it with np.linalg.solve
    return np.zeros(3)

for name, policy in [("repair when worn", [0, 1, 1]), ("repair when broken", [0, 0, 1])]:
    print(f"{name}: " + " ".join(f"{v:.2f}" for v in evaluate(policy)))
Knowledge check

What is the difference between the Bellman expectation equation and the Bellman optimality equation?

Summary

  • V_π(s) is the expected return from state s under policy π; Q_π(s, a) is the expected return after taking action a in s first. V averages Q over the policy's actions.
  • The Bellman expectation equation says a value equals the expected reward now plus γ times the value of the next state. Iterative policy evaluation sweeps it until the values stop changing.
  • Acting greedily on a policy's Q-values gives a policy at least as good: policy improvement.
  • The Bellman optimality equation replaces the average over actions with a max. Value iteration sweeps it to find V*, spreading values outwards from the rewards one step per sweep.
  • The greedy policy picks the action with the largest Q*(s, a). With V* alone, that look-ahead needs the model.

Next: Multi-Armed Bandits.

Finished reading? Tick it off to track your progress.