Solve a small MDP with policy iteration

Why it matters Exact dynamic programming like this is the ground truth used to test RL algorithms.

Policy iteration alternates exact policy evaluation with greedy improvement until the policy stops changing.

Write policy_iteration(P, R, gamma). P is (A, S, S) with P[a, s, s'] transition probabilities, R is (S, A) rewards. Start with policy all zeros. Evaluate exactly by solving (I - gamma P_pi) V = R_pi. Improve: pi(s) = argmax_a R[s, a] + gamma sum_s' P[a, s, s'] V[s'] (ties to the smaller action). Stop when the policy is unchanged. Return (pi, V).

Signaturedef policy_iteration(P, R, gamma)

Example

one state, two actions with rewards [0, 1] that both loop back, gamma 0.5: the policy picks action 1 and V = 1 / (1 - 0.5) = 2.

Understand the idea

Policy iteration solves a small MDP exactly with two repeated steps. Evaluate the current policy exactly with a linear solve, then improve it greedily with a one-step lookahead. Stop when the policy no longer changes. Worked example: 2 states, gamma 0.5. Action 0 stays put, action 1 moves to the other state. R = [[0, 1], [2, 0]]. Start pi = [0, 0] (both stay): V = [0, 2 / 0.5] = [0, 4]. Improve state 0: stay 0 + 0.5 * 0 = 0, move 1 + 0.5 * 4 = 3, so move. State 1: stay 2 + 2 = 4, move 0 + 0 = 0, so stay. pi = [1, 0]. Evaluate: V1 = 4, V0 = 1 + 0.5 * 4 = 3. Improving again gives the same policy, so return pi [1, 0], V [3, 4]. Rule: P_pi[s] = P[pi(s), s, :], R_pi[s] = R[s, pi(s)]; solve (I - gamma P_pi) V = R_pi; Q[s, a] = R[s, a] + gamma * sum over s' of P[a, s, s'] V[s']; pi = argmax over a (ties to the smaller action). Used in: planning with a known model.

Shapes and data flow

P (A, S, S), R (S, A)
pi (S,) -> P_pi (S, S), R_pi (S,) -> V (S,)
Q (S, A) = R + gamma * einsum('ast,t->sa', P, V)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplepolicy_iteration([[[1.0]], [[1.0]]], [[0, 1]], 0.5)
  • Sample 2: chainpolicy_iteration(_P, _R, 0.9)