Guide to AI and Data Courses · Lecture Notes
Chapter 7: Reinforcement Learning
It is almost impossible to write a list of rules that teaches a child to ride a bicycle; the child tries, falls, tries again and works out how balance is kept. The only feedback is delayed and crude, such as "you fell" or "you moved forward". Reinforcement learning is the course about this way of learning: an agent interacts with an environment, sees nothing but a reward signal, and tries to find the behavior that maximizes the total reward in the long run. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.
Learning outcomes
- The interaction loop
- Set up a problem in terms of agent, environment, state, action and reward; tell reinforcement learning apart from supervised learning.
- Return
- Compute the discounted return of a reward sequence and explain how the discount factor changes behavior.
- Value iteration
- Apply the Bellman optimality equation by hand for a few sweeps on a small Markov decision process and read off the best policy.
- Q-learning and exploration
- Compute one Q-learning update; explain ε-greedy selection and the balance of exploration and exploitation.
- Place of the course
- State what separates reinforcement learning from machine learning, optimization, multi-agent systems and robotics.
7.1What question does the course ask?
How can good decisions be learned by trial and error from a reward signal alone?
Reinforcement learning studies how an agent, interacting with its environment and guided only by a reward signal, learns by trial and error the behavior that maximizes total reward in the long run. The right action is never given in advance, and the effects of actions often arrive with a delay.
In supervised learning every example comes with the right answer. In reinforcement learning there is no such teacher: the agent takes an action, and the environment returns a new state and a number, the reward. The reward says "that went well" but never "you should have done this". Worse, the reward is often delayed: in chess the value of a move becomes clear only after the game ends. The agent's question is: which action should I choose now so that the total future reward is as large as possible?
This question brings two difficulties. The first is credit assignment: which of the earlier actions deserve the reward that finally arrives? The second is data: the agent collects its own data with its own actions, so its choices decide which examples it will see. It cannot know whether an action it has never tried is good; a balance is needed between using what is known and trying something new (exploration and exploitation).
7.1.1The framework of the course
The course first states the problem with a formal model, the Markov decision process (MDP): states, actions, transition probabilities and rewards. If the model of the environment is known, the best behavior can be computed with dynamic programming. If it is not, the agent learns from experience: Monte Carlo and temporal-difference methods, Q-learning and SARSA are the classic examples. When the number of states grows, a function approximator, today usually a neural network, replaces the table; this is deep reinforcement learning. The three core sections below work through the first links of this chain, namely the return, the Bellman equation and Q-learning, in one small corridor world.
7.1.2At a glance
| Criterion | Reinforcement Learning |
|---|---|
| Approach | trial and error with rewards |
| Input | environment: state, reward |
| Output | policy: state → action |
| Success measure | total expected reward |
| Math load | high: probability, dynamic programming |
| Data needs | generated through interaction |
7.2A short history
| Year | Milestone |
|---|---|
| 1957 | Bellman's Dynamic Programming introduces the Bellman equation and the idea of a value function. |
| 1988 | Sutton publishes temporal-difference (TD) learning: correcting a prediction with the next prediction. |
| 1989 | Watkins proposes Q-learning in his PhD thesis. |
| 1992 | Tesauro's TD-Gammon nears expert level at backgammon by playing against itself. |
| 2015 | DeepMind's deep Q-network (DQN) learns Atari games from raw pixels (Nature). |
| 2016 | AlphaGo beats Lee Sedol at Go: tree search, deep networks and reinforcement learning together. |
7.3Core concepts
The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.
| Concept | Meaning |
|---|---|
| Agent and environment | The agent acts; the environment returns a new state and a reward. |
| Markov decision process | States, actions, transition probabilities and rewards. |
| Return | The sum of discounted future rewards. |
| Policy | A rule that says which action to choose in each state. |
| Value function | The expected return from a state or an action. |
| Exploration vs. exploitation | Balancing trying new actions against using what is known. |
| Temporal difference | TD, Q-learning, SARSA: model-free, step-by-step learning. |
| Policy gradient | Improving the policy directly with the gradient of the return. |
7.4Reward, return and policy
At each step the agent sees a state, chooses an action, and receives a reward and a new state from the environment. The rule for choosing actions is the policy. The goal is to maximize not the reward of a single step but the long-run sum of rewards, the return. Future rewards count for less than present ones; a discount factor γ (0 ≤ γ ≤ 1) is applied for every step.
Gt = rt+1 + γ rt+2 + γ2 rt+3 + … = rt+1 + γ Gt+1. If γ is near zero the agent looks only at near rewards; if it is near one, distant rewards matter too.
The world we compute by hand is a corridor: states 1, 2, 3 and a goal state G lie side by side (1 − 2 − 3 − G). The actions are "right" and "left". Right moves to the next state, left to the previous one; in state 1, left stays in place. Every step gives −1 (lost time is a cost), entering the goal gives +10, and the episode ends when the goal is reached. The discount factor is γ = 0.9.
The agent starts in state 1. Let us compare two policies.
- Go straight. Actions right, right, right; rewards −1, −1, +10. G = −1 + 0.9·(−1) + 0.92·10 = −1 − 0.9 + 8.1 = 6.2.
- Take a detour. First left (stays in place), then right, right, right; rewards −1, −1, −1, +10. G = −1 − 0.9 − 0.81 + 0.93·10 = −2.71 + 7.29 = 4.58.
- Comparison. The straight path has the larger return (6.2 > 4.58). The return lets us rank two reward sequences with a single number.
- The recursive form. With Gt = r + γ Gt+1 we can work backward: going right from state 3 gives a return of 10; in state 2 it is −1 + 0.9·10 = 8; in state 1 it is −1 + 0.9·8 = 6.2. The same result as the first calculation.
The discount factor changes behavior. With γ = 0 the return of both paths is just the first reward (−1); the agent never sees the goal. With γ = 1 the straight path gives −2 + 10 = 8 and the detour −3 + 10 = 7; the ranking is kept, but in tasks that never end the sum can grow without bound. That is why γ is usually chosen a little below 1.
A policy can be deterministic ("in state 1, right") or stochastic ("90% right, 10% left"). The rest of the course is about ways of finding the best policy, the one that maximizes the return.
Confusing reward with return. The reward is the immediate number the environment gives in one step; the return is the discounted sum of all rewards from that moment on. In the corridor above, the reward of the first right step in state 1 is −1, but its return is 6.2. The agent must decide by the return, not by the immediate reward.
7.5The Bellman equation and value iteration
Instead of summing the return from scratch each time, we use the value function: the expected return when starting from a state and following a policy. The value of the best policy is the optimal value V*. The recursive form (G = r + γ G') leads, for optimal values, to the equation below; Bellman introduced the idea in 1957.
V*(s) = maxa [ r(s, a) + γ · V*(s') ], where s' is the state reached from s by action a. The value of the goal state is taken as 0.
The right-hand side contains the unknown V* values, so instead of solving in one go we use value iteration: start with all values at zero, compute the right-hand side for every state and update the values, and stop when the values no longer change. Each sweep brings the values a little closer to the truth.
The corridor from the previous section: γ = 0.9, +10 on entering the goal, −1 on other steps. At the start V = (0, 0, 0) (states 1, 2, 3). In each sweep we compute the values from the values of the previous sweep.
- Sweep 1. State 3: right 10 + 0.9·0 = 10, left −1 + 0 = −1; the larger is 10. In states 2 and 1 both actions give −1 + 0.9·0 = −1. Result V = (−1, −1, 10).
- Sweep 2. State 2: right −1 + 0.9·10 = 8, left −1 + 0.9·(−1) = −1.9; the larger is 8. State 1: both actions give −1 + 0.9·(−1) = −1.9. State 3 stays at 10. V = (−1.9, 8, 10).
- Sweep 3. State 1: right −1 + 0.9·8 = 6.2, left −1 + 0.9·(−1.9) = −2.71; 6.2. State 2 stays at 8 and state 3 at 10. V = (6.2, 8, 10).
- Sweep 4. In state 1 the left action is now −1 + 0.9·6.2 = 4.58; right (6.2) still wins. No value changed: the iteration is done. V* = (6.2, 8, 10).
- Reading off the policy. In every state the action with the largest value is right: the best policy is "always go right". The value 6.2 of state 1 is the return of the straight path we found by hand in the previous section.
Information flowed backward from the goal: state 3 got its correct value in the first sweep, state 2 in the second, state 1 in the third. As many sweeps are needed as the goal is steps away.
Value iteration requires the model of the environment, that is, knowing which action leads to which state and what reward it gives. It is a dynamic programming method, a relative of ideas from the Optimization and Algorithms courses. If the number of states is very large it is impossible to sweep all of them; if the model is unknown the computation cannot be done at all. The third core section gets around both obstacles.
Stopping the iteration early. At the end of sweep 1 the value of state 2 is −1, although its best value is 8; the reward information at the goal reaches only one more state back per sweep. An iteration that does not run until the values stop changing can give a wrong policy: at the end of sweep 2, right and left look equal in state 1 (−1.9).
7.6Q-learning and exploration
If the model of the environment is unknown, the agent learns from experience. For this we store the value of a state-action pair instead of a state: Q(s, a) is the expected return of taking action a in state s and then behaving optimally. Once the Q table is known the policy is easy: in every state choose the action with the largest Q. Q-learning, proposed by Watkins in 1989, updates the Q values after every step, using the transition just seen.
Q(s, a) ← Q(s, a) + α · [ r + γ · maxa' Q(s', a') − Q(s, a) ]. The bracket is the temporal-difference (TD) error: the difference between the "target" (r + γ max Q(s', ·)) and the old estimate. α is the learning rate.
This resembles gradient descent: the estimate is pulled toward the target by a small step. The target itself contains an estimate (the Q value of the next state); that is why the method is described as correcting a prediction with the next prediction (Sutton's 1988 temporal-difference idea).
The same corridor. The current values in the Q table are Q(2, right) = 0 and, in state 3, max Q(3, ·) = 4 (the values are illustrative). α = 0.5, γ = 0.9. The agent chooses right in state 2, moves to state 3 and receives a reward of −1.
- Target. r + γ max Q(3, ·) = −1 + 0.9·4 = 2.6.
- TD error. 2.6 − Q(2, right) = 2.6 − 0 = 2.6.
- Update. Q(2, right) ← 0 + 0.5 · 2.6 = 1.3.
- Reading. The true value is 8, so the estimate moved only a little closer. Q values approach the truth not in one step but by seeing the same transitions many times; information spreads backward from the goal, as in value iteration.
7.6.1Exploration and exploitation
If the agent always picks the action with the largest Q (the greedy policy), it may never try a better action when its early estimates are wrong. So an action is sometimes chosen at random. The most common rule is ε-greedy: with probability 1 − ε choose the best-known action, with probability ε a random action. Because the random choice is made among all actions, the total probability of the greedy action is 1 − ε + ε/k (k is the number of actions).
A machine with two arms. The agent pulls arm 1 three times and receives the rewards 1, 0, 1. The value estimate is updated after every reward with an incremental average: Qn = Qn−1 + (rn − Qn−1)/n.
- Q1 = 0 + (1 − 0)/1 = 1.
- Q2 = 1 + (0 − 1)/2 = 0.5.
- Q3 = 0.5 + (1 − 0.5)/3 ≈ 0.667; the same as the mean of the three rewards.
- Arm 2 has never been pulled and its estimate is still 0. A greedy agent keeps pulling arm 1 and never finds out that arm 2 may be better. With ε = 0.1 and two arms, arm 2 is tried with probability ε/2 = 5% at every step.
Q-learning is an off-policy method: in its update it assumes the best action (the max) in the next state, whatever action the agent actually chooses. Its relative that uses the action the agent really chose is SARSA (on-policy). When the number of states is very large a neural network replaces the table (deep Q-network; for the common ground see Deep Learning).
Expecting Q-learning to find the right value after a single transition, or switching exploration off completely. In the update above Q rose from 0 to 1.3 while the target was 8 away. Also, evaluating with the training ε after learning is over makes performance look lower than it is; evaluation usually uses ε = 0 or a very small value.
7.7How is the course taught?
7.7.1A typical workflow
A warehouse robot observes its position on a grid, usually picks the best direction it knows and sometimes a random one, and gets +10 for reaching the shelf and −1 for hitting a wall. Q-learning updates action values at every step; after thousands of trials a short, safe path emerges.
7.7.2Topics over the semester
- Multi-armed bandits and exploration
- Markov decision processes and Bellman equations
- Dynamic programming: policy and value iteration
- Monte Carlo methods
- Temporal-difference learning: TD(0) and SARSA
- Q-learning and off-policy learning
- n-step methods and eligibility traces
- Value estimation with function approximation
- Deep Q-networks: experience replay, target network
- Policy gradients and REINFORCE
- Actor-critic methods and PPO
- Model-based RL and Monte Carlo tree search
This is a typical semester; the order and coverage vary between universities.
7.7.3Skills you will gain
- building environments with Gymnasium
- writing Q-learning from scratch
- training agents with Stable-Baselines3
- designing reward functions
- running and reporting multi-seed experiments
7.7.4Try it yourself
The Try It: The Vacuum Finds Its Charger slide in the presentation lets you solve a typical problem of this course yourself: The robot vacuum has no map; each step is −1, the charging dock +10, falling down the stairs −10. Let it learn by trial over episodes: train it, then send the robot from the top-left corner.
7.8Are you ready for this course?
7.8.1Prerequisites
| Course | Why it is needed |
|---|---|
| Machine Learning | learning from rewards instead of labels |
| Algorithms | dynamic programming and shortest paths in graphs |
| Programming | simulation loops and arrays in Python |
7.8.2Ask yourself
For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.
| Question | If not, start with |
|---|---|
| Can you compute an expected value and a conditional probability? | Probability and Statistics |
| Can you solve a shortest-path problem with dynamic programming? | Dynamic programming from an algorithms course |
| Can you explain a loss function and gradient descent? | Machine Learning |
| Can you write a simulation loop in Python and plot the result? | An intro programming course, then a short Matplotlib tutorial |
7.9Neighboring courses
7.9.1Where it overlaps
| Relation | Course | Shared ground |
|---|---|---|
| subfield | This course is a subfield of Machine Learning | learning from rewards instead of labels |
| shares methods | Shares methods with Deep Learning | deep Q-networks, deep policy networks |
| shares methods | Shares methods with Multi-Agent Systems | multi-agent reinforcement learning, game theory |
| shares methods | Shares methods with Robotics and Robot Vision | control, learning motor skills |
| shares methods | Shares methods with Optimization | dynamic programming, policy gradient |
7.9.2Where it differs
- Machine Learning: In supervised learning every example comes with the right answer; in RL there is only a delayed reward, and data is collected by the agent's own actions.
- Optimization: Optimization solves a problem whose model is known; RL learns by interacting, without knowing the environment's model.
- Multi-Agent Systems: Multi-agent systems study coordination and conflict among agents; this course mostly focuses on a single agent learning.
- Robotics and Robot Vision: Robotics covers perception, kinematics and control; RL contributes only learning behavior from experience.
7.10In practice
7.10.1Applications
| Area | What is done |
|---|---|
| Games | Go, chess, Atari and strategy games. |
| Robot control | Learning to walk, grasp and move. |
| Resource management | Data center cooling, network traffic routing. |
| Recommender systems | Caring about long-term user satisfaction. |
| Traffic signals | Reducing waiting times at intersections. |
| Language model fine-tuning | Reinforcement learning from human feedback (RLHF). |
7.10.2Risks and ethics
| Risk | Explanation |
|---|---|
| Reward hacking | OpenAI's boat-racing agent circled endlessly to hit the same scoring targets instead of finishing the race. |
| Unsafe exploration | Trial and error is costly in the real world: a robot or a treatment policy can cause harm while it explores. |
| Results that do not reproduce | The same algorithm gives very different results across random seeds; an advantage reported over a few seeds can mislead. |
| Shaping the user | A recommendation policy that maximizes clicks can push users toward more extreme content and compulsive use. |
These issues are discussed in depth in Explainable AI and AI Ethics.
7.10.3Tools and datasets
Tools: Gymnasium, Stable-Baselines3, PyTorch, RLlib, MuJoCo, PettingZoo.
Classic environments: Gridworld, Multi-armed bandit, CartPole, MountainCar, Atari games (ALE), MuJoCo control tasks.
RL gives you an environment instead of a ready-made dataset: the agent produces data by its own actions, so simulation is the course's lab.
7.11Common misconceptions
RL is just another name for supervised learning.
The right action is never given; the agent learns only from rewards and the experience it collects.
Writing the reward is easy.
An agent exploits a poorly designed reward with unexpected shortcuts (reward hacking).
A robot that learns in simulation works in reality.
The gap between simulation and the real world (sim-to-real) must be handled separately.
RL is only for games.
Control, resource management and training language models from human feedback also use RL.
7.12Summary
- In reinforcement learning the agent receives only a state and a reward from the environment; the right action is never given and the reward may be delayed.
- The goal is not the immediate reward but the discounted return: G = r1 + γ r2 + γ2 r3 + …; a policy is a rule from states to actions.
- The value function is the expected return; the Bellman optimality equation V*(s) = maxa [r + γ V*(s')] and value iteration find the best policy when the model is known.
- When the model is unknown, Q-learning learns from experience with the update Q ← Q + α(r + γ max Q' − Q); the bracket is the temporal-difference error.
- Exploration and exploitation must be balanced: ε-greedy selection tries a random action now and then, which keeps the agent from getting stuck with wrong estimates.
7.13Test Yourself
The rewards are 2, 0, 4 and γ = 0.5. What is the return?
Answer
G = 2 + 0.5·0 + 0.52·4 = 2 + 0 + 1 = 3.
In the corridor world let γ = 0.8, +10 on entering the goal and −1 on other steps. If the value of state 3 is 10, what is the best value of state 2?
Answer
Right: −1 + 0.8·10 = 7. Left would be lower, so the best value is 7.
Q(s, a) = 2, reward r = 1, max Q = 5 in the next state, α = 0.1, γ = 0.9. What is Q(s, a) after the Q-learning update?
Answer
Target 1 + 0.9·5 = 5.5; TD error 5.5 − 2 = 3.5; new value 2 + 0.1·3.5 = 2.35.
In the situation of the third question the agent explored in the next state and chose the action whose Q value is 2. What does SARSA do to Q in the same transition? What does the difference show?
Answer
SARSA builds the target from the Q value of the chosen action: 1 + 0.9·2 = 2.8; TD error 2.8 − 2 = 0.8; new value 2 + 0.1·0.8 = 2.08. Q-learning, taking the max, had given 2.35. Q-learning ignores the agent's own exploratory steps (off-policy); SARSA takes them into account (on-policy).
For an ε-greedy policy with ε = 0.2 and four actions, what is the probability of the best action and of each other action? Do they sum to 1?
Answer
In the random choice each action gets ε/4 = 0.05. The greedy action gets 0.8 + 0.05 = 0.85, the other three 0.05 each. The sum is 0.85 + 3·0.05 = 1.
A chess agent is given the reward "+1 for every piece captured". Why is this risky? What could be a better reward?
Answer
The agent may maximize pieces captured instead of winning, that is, the reward gets exploited (reward hacking); it may risk checkmate to take a piece. A reward that reflects the goal directly is better: +1 for a win at the end, −1 for a loss, 0 on intermediate steps. The price is that the reward is sparse and delayed, which makes credit assignment harder.
7.14After this course
After reinforcement learning you can move to multi-agent systems, where many agents learn together, or to robotics, for machines that learn in the physical world. Deep learning helps with deep RL, and optimization makes policy gradient methods easier to understand.
Related careers: Reinforcement learning engineer, Robotics software engineer, Game AI developer, Researcher.
7.15Further reading
- R. S. Sutton and A. G. Barto, Reinforcement Learning: An Introduction (2nd ed., 2018): the standard textbook of the field; MDPs, dynamic programming, temporal-difference learning and Q-learning follow the same path as these notes.
- C. Szepesvári, Algorithms for Reinforcement Learning (2010): a short, theory-oriented summary, for readers who want to see why the algorithms converge.
- D. P. Bertsekas, Reinforcement Learning and Optimal Control (2019): looks at reinforcement learning from the side of dynamic programming and optimal control.
7.16References
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd ed., MIT Press, 2018.
- Szepesvári, Algorithms for Reinforcement Learning, Morgan & Claypool, 2010.
- Bertsekas, Reinforcement Learning and Optimal Control, Athena Scientific, 2019.
- Mnih et al., "Human-level control through deep reinforcement learning", Nature 518, 2015.
Related pages: Slides · Slides (PDF) · Course page