Lesson 1
RL 0-4
These are my original lecture notes, kept as they were. They're being rebuilt into the Reinforcement learning course.
1. Introduction & Overview
What is Reinforcement Learning?
Reinforcement Learning (RL) is a type of machine learning where an agent learns to make decisions by interacting with an environment. Unlike supervised learning where you're given explicit input-output pairs, in RL you learn from rewards/punishments received after taking actions.
The Three Types of Machine Learning:
| Type | Input | Output | Goal |
|---|---|---|---|
| Supervised | (x, y) pairs | Function f | Map x → y |
| Unsupervised | x values only | Function f | Describe/cluster x's |
| Reinforcement | (x, z) pairs | Function f → y | Learn optimal actions from rewards |
In RL, you receive states (x) and rewards (z), but you must discover the optimal actions (y) yourself.
The Core Problem
The key challenge in RL is the temporal credit assignment problem: you take a sequence of actions, and only later receive feedback about how well you did. Which action was responsible for your success or failure?
Example - Chess: You play 60 moves and then lose. Did you lose because of:
- A bad move early in the game?
- A mistake near the end?
- Consistently mediocre play?
RL algorithms must figure out how to assign "credit" (or "blame") to individual actions in the sequence.
2. Markov Decision Processes (MDPs)
An MDP is the mathematical framework we use to model decision-making problems.
Components of an MDP
An MDP is defined by the tuple: (S, A, T, R, γ)
| Component | Symbol | Description |
|---|---|---|
| States | S | Set of all possible states the agent can be in |
| Actions | A | Set of all possible actions the agent can take |
| Transition Function | T(s, a, s') | Probability of reaching state s' when taking action a in state s |
| Reward Function | R(s) | Immediate reward for being in state s |
| Discount Factor | γ | How much to value future rewards (0 ≤ γ < 1) |
The Markov Property
"Only the present matters."
The probability of transitioning to the next state depends only on the current state, not on any previous history:
Intuition: If you're in state s, it doesn't matter how you got there—only that you're there now.
Practical Note: If history does matter, you can fold the relevant history into your state representation (though this increases state space size).
Stationarity
The transition and reward functions don't change over time. The "physics" of the world remain constant.
Example: Grid World
Consider a 3×4 grid where:
- Agent starts at (1,1)
- Goal state at (4,3) gives +1 reward
- Trap state at (4,2) gives -1 reward
- Actions: Up, Down, Left, Right
- Each action succeeds with 80% probability; 10% chance of slipping perpendicular in each direction
With deterministic actions: The shortest path from start to goal is 5 steps (e.g., up, up, right, right, right).
With stochastic actions: The probability of this exact sequence succeeding is:
This illustrates why we need policies rather than fixed plans.
Policy vs Plan
| Concept | Definition | When to Use |
|---|---|---|
| Plan | Fixed sequence of actions | Deterministic environments |
| Policy | Mapping from states → actions | Stochastic environments |
Policy (π): A function π: S → A that tells you which action to take in each state.
Optimal Policy (): The policy that maximizes expected long-term reward.
3. Value Functions & The Bellman Equation
Utility vs Reward
| Concept | Definition | Time Horizon |
|---|---|---|
| Reward R(s) | Immediate feedback for being in state s | Single timestep |
| Utility U(s) | Expected total future reward from state s | Long-term |
Key insight: A state with low immediate reward might have high utility if it leads to better states.
Example: College costs money (negative immediate reward) but leads to higher earnings (positive utility).
Why We Need Discounting
If we simply sum all future rewards:
This sum can be infinite for infinite time horizons!
The Discounted Reward Solution:
where 0 ≤ γ < 1.
Properties of discounting:
- γ close to 0: Only care about immediate reward
- γ close to 1: Care about long-term reward
- Ensures the sum converges even for infinite sequences
The Geometric Series Bound:
This gives us a finite upper bound on utility even with infinite time horizons.
The Value Function V(s)
The value function V(s) represents the expected utility of being in state s and following policy π:
The Q-Function Q(s, a)
The Q-function represents the expected utility of taking action a in state s, then following policy π:
Relationship between V and Q:
The Bellman Equation ⭐
The most important equation in RL!
The Bellman equation expresses the recursive relationship between the value of a state and the values of its successor states.
For the Value Function:
For the Q-Function:
Intuition: The value of a state equals:
- The immediate reward, plus
- The discounted value of where you'll end up (in expectation)
The Continuation Function C(s, a)
An alternative representation that separates immediate reward from future value:
Relationships:
Why C matters: Q-functions encapsulate everything needed to act optimally without knowing R or T. If you have Q, you can derive V easily.
4. Solving MDPs: Value Iteration & Policy Iteration
Given a known MDP (known T and R), how do we find the optimal policy?
Value Iteration
Algorithm:
- Initialize V(s) = 0 (or arbitrary values) for all states
- Repeat until convergence:
- Extract policy:
Why it works:
- n equations (one per state) in n unknowns (the V values)
- The max makes it nonlinear, so we can't solve directly
- But iterative updates converge because the Bellman operator is a contraction mapping
The Bellman Operator
Define the Bellman operator B as:
Key properties:
- (the optimal Q-function is a fixed point)
- Value iteration:
5. Reinforcement Learning Basics
The Agent-Environment Loop
┌─────────────────────────────────────┐
│ │
▼ │
┌─────────┐ action a ┌───────────────┐
│ Agent │ ───────────────► │ Environment │
│ │ ◄─────────────── │ │
└─────────┘ state,reward s,r └───────────────┘Sequence: The agent experiences:
Often written as SARS: (State, Action, Reward, State')
RL vs MDP Solving
| Aspect | MDP Solving | Reinforcement Learning |
|---|---|---|
| Model T, R | Known | Unknown |
| Data | Not needed | Learn from experience |
| Computation | Mostly offline | Online updates |
The core RL challenge: Learn a good policy without knowing T or R—only by observing rewards from experience!
Evaluating Policies and Learners
Policy Evaluation: How good is this policy?
- Expected discounted reward when following it
Learner Evaluation:
- Quality: Does it find a good (optimal?) policy?
- Computational Complexity: How much compute time?
- Sample Complexity: How many experiences/interactions needed?
6. Three Families of RL Algorithms
Overview Diagram
EXPERIENCE (SARS tuples)
│
┌───────────────────────┼───────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ MODEL-BASED │ │ VALUE-BASED │ │ POLICY-BASED │
└───────┬───────┘ └───────┬───────┘ └───────┬───────┘
│ │ │
▼ │ │
┌───────────────┐ │ │
│ Learn T, R │ │ │
│ (dynamics & │ │ │
│ rewards) │ │ │
└───────┬───────┘ │ │
│ │ │
▼ │ │
┌───────────────┐ │ │
│ Plan/Solve │ │ │
│ (Value Iter) │ │ │
└───────┬───────┘ │ │
│ │ │
▼ ▼ │
┌───────────────┐ ┌───────────────┐ │
│ Q* │ │ Learn Q* │ │
│ │ │ directly │ │
│ │ │ (Q-learning) │ │
└───────┬───────┘ └───────┬───────┘ │
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ π* = argmax │ │ π* = argmax │ │ Learn π* │
│ │ │ │ │ directly │
└───────┬───────┘ └───────┬───────┘ └───────┬───────┘
│ │ │
└──────────────────────┴──────────────────────┘
│
▼
POLICY π*1. Model-Based RL
Approach: Learn T and R from experience, then solve the MDP.
Flow: SARS* → Learn T, R → MDP Solver → Q* → Policy
Pros: Learning T, R is basically supervised learning (easy) Cons: Requires building and storing a model; two-phase process
2. Value-Based (Model-Free) RL
Approach: Learn Q* directly from experience without learning T or R.
Flow: SARS* → Value Update → Q* → Policy
Pros: No model needed; simpler; direct Cons: Harder learning problem (what target to use?)
Examples: TD Learning, Q-Learning, SARSA
3. Policy-Based RL
Approach: Learn π directly, bypassing value functions entirely.
Flow: SARS* → Policy Update → Policy
Pros: Most direct; works with continuous actions Cons: Hardest learning signal; high variance
Examples: REINFORCE, Policy Gradient methods
7. Temporal Difference Learning
The Core Idea
TD learning learns value functions from experience by using bootstrapping: updating estimates based on other estimates.
Learning from Returns (Outcome-Based)
Given episodes of experience, estimate V(s) by averaging observed returns:
where is the total discounted return observed starting from state s in episode i.
Incremental Update Rule
Rather than storing all returns, update incrementally:
This has the form of a perceptron/gradient descent update:
- Error: (what we observed vs what we predicted)
- Learning rate: controls how much to adjust
Learning Rate Requirements ⭐
For the incremental update to converge to the true value:
Intuition:
- First condition: Learning rates must be "big enough" collectively to move from any starting point to the true value
- Second condition: Learning rates must decay fast enough to "settle down" and not bounce around forever
Which learning rates work?
| Learning Rate | Σ | Σ | Converges? |
|---|---|---|---|
| 1/t | ∞ | < ∞ | ✅ Yes |
| 1/t² | < ∞ | < ∞ | ❌ No (too small) |
| 1/t^(2/3) | ∞ | < ∞ | ✅ Yes |
| 1/√t | ∞ | ∞ | ❌ No (too big) |
| constant c | ∞ | ∞ | ❌ No (never settles) |
TD(1): Episode-Based Updates
Wait until the end of each episode, then update all visited states using the full return.
Problem: High variance (one noisy episode affects the estimate a lot)
TD(0): One-Step Bootstrapping
Don't wait for the episode to end! Update after each step using the current estimate of the next state's value:
The TD Error (δ):
This is the "temporal difference"—the difference between:
- What we now think:
- What we thought before:
Why TD(0) works:
- Uses actual reward (ground truth)
- Uses estimate for the rest (bootstrapping)
- Over time, improves, making our targets better
TD(0) gives the Maximum Likelihood estimate!
TD(λ): Interpolating Between TD(0) and TD(1)
TD(λ) provides a spectrum between TD(0) and TD(1):
- λ = 0: TD(0) (one-step lookahead)
- λ = 1: TD(1) (full episode return)
- 0 < λ < 1: Weighted combination of k-step returns
First: What are k-step returns?
For a trajectory starting at , the k-step return uses k actual rewards then bootstraps:
Tradeoff: Small k = more bias (trust estimates), large k = more variance (trust actuals)
The λ-return: a weighted average
TD(λ) computes a weighted average of ALL these k-step returns:
The weights are:
| Return | Weight |
|---|---|
Why do the weights sum to 1?
Visual: Weight distribution
λ = 0 (TD(0)) λ = 1 (Monte Carlo)
Weight Weight
│ │
1 │ █ │ █
│ █ │ █
│ █ │ █
│ █ │ █
└─█─────────────► k └────────────────────────────█► k
1 2 3 4 ∞ 1 2 3 4 ... ∞
All weight on 1-step All weight on full return
λ = 0.5 (balanced)
Weight
│
│ █
│ █ █
│ █ █ █
│ █ █ █ █ █ █ █ ...
└─█─█─█─█─█─█─█─────► k
1 2 3 4 5 6 7 ∞
Exponentially decaying weightsConcrete example
Say and we have:
Weights:
- :
- :
- :
- ... and so on
The two extremes
λ = 0:
- Weight on is
- Weight on everything else is
- → TD(0)
λ = 1:
- Weights become for all finite k
- All weight shifts to → Monte Carlo
Why this helps
Instead of choosing a single k (which is arbitrary), TD(λ) hedges by using all of them. The λ parameter controls how much you trust:
- Short-term estimates (low λ): Lower variance, but biased if V is wrong
- Long-term actuals (high λ): Unbiased, but high variance
Empirically, λ ∈ [0.3, 0.7] often works better than either extreme.
Eligibility Traces
TD(λ) is implemented efficiently using eligibility traces: Weight past states by λᵏ based on distance; which is the same as applying a forward looking λᵏ discount for the current-state
For each episode:
Initialize e(s) = 0 for all states
For each step (s_t → s_{t+1} with reward r_{t+1}):
e(s_t) ← e(s_t) + 1 # Mark visited state eligible
δ ← r_{t+1} + γV(s_{t+1}) - V(s_t) # Compute TD error
For all states s visited in episode:
V(s) ← V(s) + α · δ · e(s) # Update proportional to eligibility
e(s) ← γλ · e(s) # Decay eligibilityIntuition: Eligibility traces remember which states were recently visited. When we get a TD error, we assign credit to all recently-visited states, with more recent states getting more credit. The forward view says: "Each future reward contributes to this state's value". The backward view says: "Each reward distributes credit to past states".
Empirical Results
In practice, λ between 0.3 and 0.7 often works best:
- Combines the low variance of TD(0)
- With the lower bias of TD(1)
8. Q-Learning and Control
From Prediction to Control
TD learning (as described above) learns to predict values under a fixed policy. For control, we need to learn the optimal policy by learning Q*.
The Q-Learning Update ⭐
Key difference from TD: The max over next actions!
The Q-Learning Algorithm:
Initialize Q(s, a) arbitrarily for all s, a
For each episode:
Start in state s
For each step:
Choose action a (e.g., ε-greedy based on Q)
Take action a, observe reward r and next state s'
Q(s, a) ← Q(s, a) + α[r + γ max_a' Q(s', a') - Q(s, a)]
s ← s'
Until s is terminalOff-Policy Learning
Q-learning is off-policy: it learns about the optimal policy π* while following a different behavior policy (e.g., ε-greedy for exploration).
This works because the update uses , which corresponds to what the optimal policy would do, regardless of what action we actually took!
Exploration vs Exploitation
The dilemma: Should we:
- Exploit: Choose the action we currently think is best?
- Explore: Try other actions to potentially discover something better?
ε-greedy strategy:
- With probability 1-ε: Choose
- With probability ε: Choose a random action
Common practice: Start with high ε (explore a lot), decay over time (exploit more as Q improves).
9. Convergence Theory
Why Do These Algorithms Converge?
The Bellman equation can be written using the Bellman operator B:
Fixed point: (the optimal Q-function satisfies the Bellman equation)
Value Iteration:
Contraction Mappings
Definition: An operator B is a contraction mapping with factor γ < 1 if:
for all functions F, G.
The infinity norm:
Intuition: Applying B brings any two functions closer together.
The Bellman Operator is a Contraction! ⭐
Proof sketch:
Contraction Mapping Theorem
If B is a contraction mapping with factor γ < 1, then:
- B has a unique fixed point Q* such that
- Iteration converges: For any starting , the sequence converges to Q*
- Convergence rate:
Q-Learning Convergence Theorem ⭐
Theorem: Q-learning converges to Q* with probability 1 if:
- All state-action pairs are visited infinitely often
- Learning rates satisfy: and
The decomposition argument:
Q-learning combines two approximations:
- Sampling: Using samples instead of computing expectations
- Bootstrapping: Using Q estimates instead of true Q*
Both converge independently:
- Sampling converges (law of large numbers + learning rate conditions)
- Bootstrapping converges (Bellman operator is a contraction)
Together, they still converge!
What Operations are Non-Expansions?
The following operations, when used in place of max in the Bellman equation, preserve convergence:
| Operation | Example Use |
|---|---|
| max | Standard optimal control |
| min | Minimax (adversarial) |
| Fixed convex combination | Stochastic policies |
| Order statistics | Robust optimization |
| Expectation | Policy evaluation |
Warning: Boltzmann (softmax) exploration is NOT guaranteed to be a non-expansion because the weights depend on the Q values themselves!
Generalized MDPs
The convergence theory extends to "Generalized MDPs" where max is replaced by other non-expansion operators:
- Minimax MDPs: For two-player zero-sum games
- Stochastic games: Multiple agents with mixed strategies
10. Key Equations Summary
Bellman Equations
Value function (prediction):
Optimal value function:
Q-function:
TD Update Rules
TD(0) for V:
Q-Learning:
TD Error:
Discounting
Discounted return:
Geometric series bound:
Learning Rate Conditions