Hello! Welcome to our third lesson in the Reinforcement Learning Foundations module.
In our last two lessons, we formulated problems as Markov Decision Processes (MDPs) and derived the Bellman equations, which provide the theoretical bedrock for solving them. We saw how the Bellman optimality equation defines the value of an optimal policy:
We briefly introduced two algorithms based on this principle: Value Iteration and Policy Iteration. Today, we're moving from theory to practice. Your goal for this lesson is to implement these two foundational dynamic programming algorithms from scratch. Given your software engineering background and fluency in Python, this will be an excellent opportunity to turn these mathematical concepts into working code.
Let's get started.
1. Value Iteration: Finding the Optimal Value Function
Value Iteration (VI) is a straightforward way to solve for the optimal value function, . The idea is to turn the Bellman optimality equation into an iterative update rule. We start with a random or zero-initialized value function and repeatedly update it for every state until it converges.
The update rule, which we saw last time, is:
This process is sometimes called applying the "Bellman backup operator."
The Algorithm
The algorithm proceeds as follows:
- Initialize for all states .
- Loop until convergence:
- For each state :
- Calculate the value for each action :
- Update the state-value:
- For each state :
- Output: Once has converged to , extract the optimal policy by choosing the action that maximizes the expected value for each state:
The following video provides a clear, detailed explanation of this process.
Lecture 17 - MDPs & Value/Policy Iteration | Stanford CS229: Machine Learning Andrew Ng (Autumn2018)
In this segment from his Stanford lecture, Andrew Ng walks through the Value Iteration algorithm. He explains how to initialize the values and repeatedly apply the Bellman update, and he clarifies the convergence properties.
Watch from 24:26 to 49:18. Pay close attention to: The definition of the optimal value function V* and its Bellman equation (24:26 - 31:47). The step-by-step description of the Value Iteration algorithm and how it uses this equation as an update rule (31:47 - 49:18).
Implementation in Python
Now, let's see what this looks like in code. The next video demonstrates how to implement Value Iteration in Python, including how to structure the data and manage the iterative updates.
Value Iteration Algorithm - Dynamic Programming Algorithms in Python (Part 9)
The channel 'Coding Perspective' provides a concise implementation of Value Iteration. This is a great practical guide to translating the algorithm we just discussed into Python.
Watch the following segments: (01:04 - 02:15): Understand the iterative calculation of Q-values and V-values. (02:15 - 04:20): Follow the Python implementation. Note how a dictionary is used to store the value function and how a convergence condition is checked. (05:56 - 06:48): See how to modify the function to also output the final optimal policy.
Now it's your turn to code. You will implement Value Iteration yourself. The following GitHub repository contains a Jupyter Notebook with a solution for the "Gridworld" environment from the Sutton & Barto textbook.
Dynamic Programming Value Iteration Solution
This GitHub repository by Antonio Serrano contains Python implementations of many core RL algorithms. We will use the 'Value Iteration Solution.ipynb' notebook as a reference.
Navigate to the Jupyter Notebook titled 'Value Iteration Solution.ipynb'. Your task is to implement the Value Iteration algorithm yourself in a separate script or notebook. You can use the provided notebook as a reference for the environment setup and the algorithm's structure, but try to write the core logic from scratch to solidify your understanding. Focus on the value_iteration function.
2. Policy Iteration: The Dance of Evaluation and Improvement
Policy Iteration (PI) takes a different approach. Instead of directly targeting , it iterates on the policy itself until it finds the optimal one. It does this by repeating two steps in a loop: Policy Evaluation and Policy Improvement.

The Algorithm
- Initialization: Start with a random policy, .
- Loop until the policy no longer changes:
- a) Policy Evaluation: Given the current policy , calculate its value function, . This is done by solving the Bellman expectation equation. In practice, we solve it iteratively:
- Loop until converges:
- Loop until converges:
- b) Policy Improvement: For each state , update the policy by choosing the action that is greedy with respect to :
- If , the algorithm has converged. Otherwise, set and repeat.
- a) Policy Evaluation: Given the current policy , calculate its value function, . This is done by solving the Bellman expectation equation. In practice, we solve it iteratively:
Let's return to Andrew Ng's lecture for an explanation of this two-step process.
Lecture 17 - MDPs & Value/Policy Iteration | Stanford CS229: Machine Learning Andrew Ng (Autumn2018)
Here, Andrew Ng explains the Policy Iteration algorithm, contrasting it with Value Iteration. He details the two core steps and discusses why the process is guaranteed to converge.
Watch from 50:18 to 54:22. Focus on understanding the distinction between the two main steps: solving for V_pi (evaluation) and then updating the policy Pi (improvement).
Implementation in Python
Now, you'll implement Policy Iteration. The structure will be slightly more complex than Value Iteration, involving an outer loop for policy improvement and an inner loop for policy evaluation.
Dynamic Programming Policy Iteration Solution
Let's go back to the same GitHub repository. This time, we'll use the Policy Iteration notebook as our guide.
Navigate to the notebook 'Policy Iteration Solution.ipynb'. Your task is to implement Policy Iteration from scratch. Pay close attention to how the policy_eval function implements the iterative evaluation step. Then, see how the main loop calls policy_eval and then performs the policy improvement step. Write your own version to ensure you understand the flow.
3. Value Iteration vs. Policy Iteration
So, which algorithm is better? There's no single answer; it depends on the problem.
- Policy Iteration often converges in very few policy iterations. However, each iteration is computationally expensive because it requires a full policy evaluation (which is itself an iterative process).
- Value Iteration involves simpler, cheaper updates in each iteration. It may take more iterations to converge to the optimal value function, but each one is faster.
For large state spaces, solving the linear system for policy evaluation becomes very costly, so Value Iteration is often preferred.
Reinforcement Learning and Control
The CS229 lecture notes provide a concise written comparison of the two algorithms, summarizing the key trade-offs.
Read Section 2.1, 'Comparison of value iteration and policy iteration.' This short section summarizes the practical considerations for choosing between the two algorithms, reinforcing the points made in the video.
Test your understanding!
Imagine you have an MDP with a vast number of states (e.g., millions), but you know that the optimal policy is likely simple and will be found after only a few policy updates. However, performing a full, exact policy evaluation for every policy is computationally infeasible.
Which algorithm, Value Iteration or Policy Iteration, seems like a better starting point? Could you suggest a "hybrid" approach?
Show answer
Value Iteration would be the more practical starting point. The primary reason is that the expensive step in Policy Iteration—a full policy evaluation—is infeasible in a huge state space. The cheap, incremental updates of Value Iteration are much more manageable.
A "hybrid" approach, often called Modified Policy Iteration or Truncated Policy Iteration, is a very effective strategy. Instead of running the policy evaluation step until full convergence, you only run it for a small, fixed number of iterations (say, k steps).
So the loop would be:
- Run
ksteps of the Bellman expectation update to get an approximate . - Perform one step of policy improvement based on this approximate value function.
- Repeat.
Interestingly, if you set k=1, this hybrid algorithm becomes identical to Value Iteration! This shows that VI and PI are two ends of a spectrum.
Conclusion
Congratulations! You have now implemented the two foundational algorithms for solving MDPs when the model is known. These dynamic programming methods are the theoretical basis for many more advanced reinforcement learning techniques.
Key Takeaways:
- Dynamic Programming in RL refers to algorithms that solve MDPs using the Bellman equations, assuming a perfect model of the environment.
- Value Iteration directly computes the optimal value function by repeatedly applying the Bellman optimality update.
- Policy Iteration alternates between two steps: evaluating the current policy to find and improving it by acting greedily with respect to .
- The choice between VI and PI involves a trade-off between the number of iterations and the computational cost per iteration.
Preview of the Next Lesson:
So far, we've operated under a critical assumption: we know the environment's dynamics, . This is why these are called model-based methods. But what happens when we don't have a model? How can an agent learn to navigate a world it doesn't understand beforehand?
In our next lesson, we will step into the world of model-free reinforcement learning. We will start with Monte Carlo methods, where an agent learns the value of states simply by running through many episodes of experience and averaging the results. This marks a crucial shift from planning with a known model to learning directly from interaction.