On calm ice, following the 6-move shortest path always reaches the goal; on slippery ice, that same shortest-path policy succeeds in only 4.5\% of episodes:
Coupled multistage decisions: At cell 9, right steps closer to the goal on calm ice, but on slippery ice it lands in hole 5 one time in three.
Safety vs. delay:Down never enters hole 5, yet slides sideways into cell 8 or 10 two times in three.
Bellman’s core insight: We cannot rank actions by one-step distance; we must score each cell by the total future return still achievable from it.
Interpretation on FrozenLake:V^\pi(s) is the probability of reaching the goal from s, weighted by \gamma^t for arrival step t.
Action value Q^\pi(s, a): Commits to action a at step 0, then follows \pi thereafter, satisfying V^\pi(s) = \sum_a \pi(a \mid s) Q^\pi(s, a).
Bellman Expectation Equations and Tensor Backup
Recursive One-Step Lookahead
Splitting a trajectory after its first step and invoking the Markov property turns the infinite-horizon sum into a coupled linear system across neighboring states:
The one-step backup bracket: For any value vector \mathbf{V} \in \mathbb{R}^{|\mathcal{S}|}, the bracketed lookahead across all (s, a) pairs is a single matrix-vector product:
def backup(self, V):"""Q(s, a) = r(s, a) + gamma * sum_{s'} P(s'|s, a) V(s') for every state-action pair: the bracket of the Bellman equations."""returnself.r +self.gamma *self.P @ V
Action-value optimality:Q^*(s, a) = r(s, a) + \gamma \sum_{s'} P(s' \mid s, a) \max_{a'} Q^*(s', a').
Model-based vs. model-free extraction: Extracting \pi^* from V^* requires a lookahead with P and r, whereas \pi^*(s) = \mathrm{argmax}_a Q^*(s, a) requires no model.
Visualizing Exact and Sampled Bellman Backups
Backup Tree Diagrams
Every Bellman equation assembles the value at a root node from the values one step below it:
Expectation vs. optimality (a–c):V^\pi and Q^\pi average over policy actions \pi(a \mid s), whereas the optimality operator replaces the action average with \max_a (drawn as an arc).
Sampled backup (d): When P is unknown (§14.3), the learner follows a single realized environment transition (blue) instead of summing over P(s' \mid s, a).
Value Iteration: Sweeping the Bellman Operator
Fixed-Point Iteration
The Bellman optimality operator\mathcal{T} maps any value table V to its best one-step lookahead (\mathcal{T}V)(s) = \max_a \big[r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)V(s')\big]:
def value_iteration(mdp, num_iters):"""Sweep V <- max_a backup(V); return the whole history of iterates.""" V, history = np.zeros(mdp.num_states), []for _ inrange(num_iters): V = mdp.backup(V).max(axis=1) history.append(V)return np.array(history)
Fixed-point characterization: The optimal value table V^* satisfies V^* = \mathcal{T}V^*; value iteration starts from V_0 = \mathbf{0} and applies V_{k+1} = \mathcal{T}V_k repeatedly.
Wavefront Propagation on Calm Ice
Deterministic Shortest-Path Limit
When transitions are deterministic, value iteration propagates exact values backward from the goal one ring per sweep:
Closed-form calm values: A cell whose shortest path around the holes takes j moves has exact value V^*(s) = \gamma^{j-1}.
Finite termination in 6 sweeps: Sweep k finalizes all cells at distance k; the start cell (j = 6) stays at 0 for five sweeps and locks onto \gamma^5 = 0.774 on sweep 6.
Why slips require analysis: Stochastic slips create cycles (such as 14 \leftrightarrow 13), coupling all states together across infinitely many sweeps.
Contraction of the Bellman Operator in Sup Norm
Why Value Iteration Always Converges
In the sup norm \|V\|_\infty = \max_s |V(s)|, \mathcal{T} shrinks the gap between any two value tables by at least \gamma:
Unique fixed point:V = \mathcal{T}V and V' = \mathcal{T}V' implies V = V' = V^*.
Geometric decay: Error e_k \leq \gamma^k e_0 shrinks by \gamma per sweep.
Observable stopping certificate: Bound true distance using consecutive iterates and horizon factor \gamma/(1-\gamma).
Calm vs. Slippery Optimal Values and Policies
Solving FrozenLake Exactly
Running value iteration on slippery FrozenLake answers the cell 9 question and reveals how drastically stochastic slips reshape optimal behavior:
Safety wins at cell 9:Q^*(9, \textrm{down}) = 0.375 beats Q^*(9, \textrm{right}) = 0.289; avoiding hole 5 is worth sliding sideways two times in three.
Lower values everywhere: Slips cut the start-state value V^*(s_0) from 0.774 to 0.180, and even cell 14 adjacent to the goal drops from 1.000 to 0.724.
V*(s0) = 0.1805, V*(13) = 0.5090
state 14: V* = 0.7237; 1/3 + gamma (V*(13) + V*(14)) / 3 = 0.7237
cell 9: Q*(9, a) for a = <, v, >, ^: [0.247 0.375 0.289 0.213]
Empirical Convergence vs. Stopping Rules
Certifying Accuracy
Comparing true distance \|V_k - V^*\|_\infty against the a priori bound \gamma^k e_0 and the observable certificate highlights a common stopping pitfall:
Stopping on raw change is premature: Stopping when \|V_k - V_{k-1}\|_\infty \leq 10^{-6} halts at sweep 128, where true error is still 1.1 \times 10^{-5}(11\times above tolerance).
Certificate reliability: Waiting for \frac{\gamma}{1-\gamma}\|V_k - V_{k-1}\|_\infty \leq 10^{-6} halts at sweep 164, just 6 sweeps after the true error crosses 10^{-6} at sweep 158.
Policy Evaluation: Sweeps vs. Direct Linear Solve
Scoring a Fixed Policy
Linear Bellman system: Under a fixed policy \pi, V^\pi = r_\pi + \gamma P_\pi V^\pi with P_\pi(s' \mid s) = \sum_a \pi(a \mid s)P(s' \mid s, a).
Exact matrix solve: For \gamma < 1, V^\pi = (I - \gamma P_\pi)^{-1}r_\pi yields the uniform policy’s start value V(s_0) = 0.0078 in one O(|\mathcal{S}|^3) solve.
Policy Evaluation: Sweeps vs. Direct Linear Solve (Code)
Scoring a Fixed Policy
def policy_value(self, pi):"""V^pi = (I - gamma P_pi)^{-1} r_pi exactly, for pi[s, a] the probability of action a at state s (one-hot rows: deterministic). Needs gamma < 1 here: from_gym's terminal states loop on themselves.""" P_pi = np.einsum('sa,sat->st', pi, self.P) r_pi = (pi *self.r).sum(axis=1)return np.linalg.solve(np.eye(self.num_states) -self.gamma * P_pi, r_pi)print(f'V(s0) for the uniformly random policy, solved exactly: 'f'{mdp.policy_value(uniform)[0]:.4f}')
V(s0) for the uniformly random policy, solved exactly: 0.0078
Policy Improvement and Policy Iteration
Howard’s Monotone Improvement Loop
Acting greedily with respect to V^\pi via \pi'(s) = \mathrm{argmax}_a Q^\pi(s, a) guarantees monotone improvement V^{\pi'}(s) \geq V^\pi(s) at every state:
pi, num_outer = uniform, 0whileTrue: V = mdp.policy_value(pi) # evaluate pi exactly Q = mdp.backup(V) num_outer +=1if (Q.max(axis=1) <= V +1e-12).all(): # greedy gains nothing:break# pi is optimal pi = np.eye(mdp.num_actions)[Q.argmax(axis=1)] # improveassert np.abs(V - V_star).max() <1e-12
Tie-safe termination: Stop when \max_a Q^\pi(s, a) \leq V^\pi(s) + \varepsilon everywhere, rather than checking if argmax indices changed (which can cycle on tied actions like cell 6).
Generalized Policy Iteration (GPI)
Interleaving Evaluation and Improvement
Policy iteration and value iteration are two extremes of Generalized Policy Iteration, which alternates value evaluation steps toward V^\pi with greedy improvement steps toward \textrm{greedy}(V):
Policy iteration: Completes exact evaluation (V = V^\pi) before each greedy step; on FrozenLake, the very first greedy step on the uniform policy’s values already yields \pi^* (2 solves total).
Value iteration: Takes a single evaluation sweep before improving; while certifying V^* takes 164 sweeps (10{,}496 backups), its greedy policy locks onto \pi^* by sweep 14 (896 backups).
Slip-Aware Optimum Beats Shortest Path 16 to 1
Exact vs. Monte Carlo Success Rates
Evaluating policies over 100 sweeps at \gamma = 1 gives the exact probability of reaching the goal within Gymnasium’s 100-step limit, matching 2,000-episode Monte Carlo rollouts:
slip-aware optimum: goal within 100 steps 0.730 exactly, 0.736 in 2000 episodes
shortest-path policy: goal within 100 steps 0.045 exactly, 0.046 in 2000 episodes
uniformly random policy: goal within 100 steps 0.014 exactly, 0.010 in 2000 episodes
Dramatic survival gap: The slip-aware optimal policy \pi^* reaches the goal in 73.0\% of episodes, compared with 4.5\% for the calm-ice shortest path and 1.4\% for random play.
Why the Optimal Policy Walks Away from the Goal
Risk Analysis Across Cells
Solving (I - P_\pi^\top)\,\mathbf{v} = \mathbf{e}_{s_0} for expected cell visits before termination reveals exactly where episodes fall into holes:
pi*: P(falls into a hole) 0.22, from 6: 0.22
shortest: P(falls into a hole) 0.96, from 4: 0.31, 1: 0.31, 8: 0.13, 6: 0.08, 3: 0.06, 10: 0.05
Wall-bouncing as a shield: In five cells (0, 1, 3, 4, 14), \pi^* commands into a wall so the intended direction stays put and both perpendicular slips stay away from holes.
Pointing away from the goal: In four cells (2, 6, 8, 10), \pi^* points away from the goal, reducing one-step hole risk to 0 everywhere except cell 6 (flanked by holes 5 and 7), where all 22\% of its falls occur.
How Naive Approach Bonuses Corrupt Optimal Play
Reward Shaping Verification
Using value iteration on the shaped MDP \tilde{r}(s, a) = r(s, a) + b \sum_{s'} P(s' \mid s, a)\mathbf{1}(\ell(s') < \ell(s)) proves that naive progress bonuses break \pi^* on slippery ice:
Catastrophic looping (b = 0.3): The shaped optimum commands left(<) at cell 14 to shuttle back to cell 13 and farm the bonus, earning shaped value 2.15 but 0.000 true goal value.
Potential-based invariance (Ng et al., 1999): Shaping via \tilde{r} = r + \gamma\Phi(s') - \Phi(s) shifts every policy’s value by identical -\Phi(s)(\tilde{V}^\pi = V^\pi - \Phi), leaving \pi^* invariant.
Concept Check: Bellman Equations and Contraction
Check Your Understanding
Work through these three questions on dynamic programming:
Bellman equation at cell 14: Cell 14 lies left of the goal on the bottom wall. If \pi commands down at cell 14, write the Bellman expectation equation for V^\pi(14) in terms of V^\pi(13) and V^\pi(14).
Contraction & certificates: If \gamma = 0.95 and consecutive value-iteration sweeps satisfy \|V_k - V_{k-1}\|_\infty = 10^{-5}, what upper bound does the certificate place on \|V_k - V^*\|_\infty?
Action values vs. state values: Once we have converged to the optimal tables, why can an agent act optimally from Q^* without knowing P(s' \mid s, a), whereas acting from V^* still requires P?
Answers:
Commanding down hits the bottom wall (staying at 14), slips left to 13, or slips right into the goal (reward 1, value 0) with probability 1/3 each: V^\pi(14) = \frac{1}{3} + \frac{\gamma}{3}[V^\pi(13) + V^\pi(14)].
By the certificate inequality, \|V_k - V^*\|_\infty \leq \frac{\gamma}{1-\gamma}\|V_k - V_{k-1}\|_\infty = 19 \times 10^{-5} = 1.9 \times 10^{-4}.
Because Q^*(s, a) already averages over the transition distribution P(\cdot \mid s, a), greedy extraction is just \mathrm{argmax}_a Q^*(s, a), whereas V^* requires computing r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)V^*(s').