Lesson 6
RL Supplementary topics
These are my original lecture notes, kept as they were. They're being rebuilt into the Reinforcement learning course.
1. Introduction and Core Concepts
1.1 The Three Types of Feedback in Machine Learning
Machine learning can be characterized by three types of feedback:
| Feedback Type | Description | RL Relevance |
|---|---|---|
| Sequential vs One-shot | Multiple decisions over time vs single decision | RL is sequential |
| Evaluative vs Supervised | Only see rewards for actions taken vs see correct labels | RL is evaluative |
| Sample vs Exhaustive | Learn from samples vs see all possibilities | RL uses samples |
Key insight: Deep Reinforcement Learning combines ALL THREE challenges:
- Sequential: Balance immediate vs long-term rewards
- Evaluative: Balance exploration vs exploitation
- Sample: Generalize across unseen states
1.2 Core Terminology
Reward (): The immediate, one-step signal the agent receives at each timestep.
Return (): The total (potentially discounted) sum of rewards from time onward:
Value Function (): The expected return when starting in state and following policy :
Action-Value Function (): The expected return when starting in state , taking action , then following policy :
1.3 The Two Fundamental Problems
| Problem | Goal | Input → Output |
|---|---|---|
| Prediction | Evaluate a given policy | Policy → Value function or |
| Control | Find the optimal policy | Environment → Optimal policy |
Analogy:
- Prediction is like a movie critic rating films — given a movie (policy), tell me how good it is
- Control is like a movie studio trying to make the best film possible
2. The Exploration-Exploitation Trade-off
2.1 The Fundamental Dilemma
Exploration: Trying new actions to gather information about the environment
- Pro: May discover better strategies
- Con: May waste time on suboptimal actions
Exploitation: Using current knowledge to maximize rewards
- Pro: Maximizes immediate expected reward
- Con: May miss better opportunities
Real-world analogy: Restaurant choice
- Exploitation: Always go to your favorite restaurant
- Exploration: Try new restaurants to potentially find a better one
2.2 Multi-Armed Bandits
A simplified RL setting that isolates the exploration-exploitation problem:
- Single state (no sequential decisions)
- Multiple actions (arms) with unknown reward distributions
- Goal: Minimize regret (cumulative difference from optimal)
where is the optimal expected reward.
2.3 Exploration Strategies
Greedy Strategy (Always Exploit)
- Always choose
- Problem: Gets stuck with suboptimal actions
- Example: First action happens to give reward → never try others
Random Strategy (Always Explore)
- Choose actions uniformly at random
- Problem: Never exploits learned knowledge
- Eventually learns true values but very inefficiently
ε-Greedy Strategy (Balance Both)
- Typical values: or
- Often decayed over time: start exploratory, become greedy
- Simple but surprisingly effective in practice
3. Prediction Methods
The goal: Given a policy , estimate for all states .
3.1 Monte Carlo Prediction
Core Idea: Run episodes, collect returns, average them.
Algorithm:
- Generate episodes using policy
- For each state visited in episode:
- Calculate return from that point
- Update:
Incremental Update Formula:
Key Components:
- MC Target: (the actual return)
- MC Error:
Two Variants:
- First-visit MC: Only count first visit to each state per episode
- Every-visit MC: Count every visit to each state
Properties:
| Property | Value |
|---|---|
| Bias | Unbiased (uses actual returns) |
| Variance | High (returns vary a lot) |
| Bootstrapping | No (waits for episode end) |
| Works for non-episodic? | No |
Analogy: Like computing your average grade by actually taking all exams and averaging the scores.
3.2 Temporal Difference (TD) Learning
Core Idea: Don't wait for episode end — bootstrap from current estimates.
TD(0) Update:
Key Components:
- TD Target:
- TD Error:
Why This Works (Bellman Equation):
TD learning uses this relationship — the value of a state should equal the expected immediate reward plus the discounted value of the next state.
Properties:
| Property | Value |
|---|---|
| Bias | Biased (uses estimated values) |
| Variance | Low (only one-step randomness) |
| Bootstrapping | Yes |
| Works for non-episodic? | Yes |
Analogy: Like estimating your final grade after each exam by combining your current score with your predicted average for remaining exams.
3.3 Comparing MC vs TD
MC Targets (for state 3 in random walk): TD Targets:
1 V(4) or V(2)
0 ↓
1 Approaches true
0 values more smoothly
... but with initial bias
High variance, unbiased Low variance, biasedVisual intuition:
- MC estimates jump around the true value (high variance, unbiased)
- TD estimates start off-target but converge smoothly (low variance, initially biased)
3.4 n-Step TD Learning
Generalization: Use steps of actual rewards before bootstrapping.
| n | Method |
|---|---|
| n = 1 | TD(0) |
| n = 2 | 2-step TD |
| n = ∞ | Monte Carlo |
3.5 TD(λ) — Eligibility Traces
Core Idea: Blend ALL n-step returns using exponentially decaying weights.
λ-Return:
Special Cases:
- : Pure TD(0)
- : Pure Monte Carlo
Eligibility Traces (Backward View):
For each state , maintain an eligibility trace :
Update all states simultaneously:
Intuition: When you receive a reward, credit goes back to recently visited states (high eligibility) more than distant states (decayed eligibility).
Analogy: If you win a game, the moves just before winning get more credit than moves at the start. Eligibility traces implement this "recency credit assignment."
4. Control Methods
The goal: Find the optimal policy .
4.1 Generalized Policy Iteration (GPI)
All control methods follow this pattern:
Policy Evaluation
↓
π → V^π (or Q^π)
↑ ↓
└── Policy ImprovementPolicy Improvement Theorem: If for all , then .
4.2 Monte Carlo Control
Idea: Use MC for evaluation + ε-greedy for improvement.
Algorithm:
- Generate episode using ε-greedy policy
- For each pair in episode:
- Update policy: (with ε-greedy)
4.3 SARSA (On-Policy TD Control)
Name origin: Uses — hence SARSA.
Update:
Key characteristic: Uses the action that you actually take (including exploratory actions).
On-Policy: The policy being learned IS the policy being used to collect data.
# SARSA pseudocode
for each episode:
S = initial state
A = ε-greedy action from Q(S,·)
while not terminal:
Take action A, observe R, S'
A' = ε-greedy action from Q(S',·) # Choose next action
Q(S,A) += α * (R + γ*Q(S',A') - Q(S,A))
S, A = S', A'4.4 Q-Learning (Off-Policy TD Control)
Update:
Key difference from SARSA: Uses instead of .
Off-Policy: Learning about the greedy policy while following an exploratory policy.
# Q-learning pseudocode
for each episode:
S = initial state
while not terminal:
A = ε-greedy action from Q(S,·)
Take action A, observe R, S'
Q(S,A) += α * (R + γ*max_a Q(S',a) - Q(S,A)) # Use max!
S = S'4.5 SARSA vs Q-Learning: Key Differences
| Aspect | SARSA | Q-Learning |
|---|---|---|
| Type | On-policy | Off-policy |
| Target | ||
| Action used | Actual next action | Best next action |
| Learns about | Current ε-greedy policy | Optimal greedy policy |
| Safer behavior | Yes (accounts for exploration) | No (assumes greedy future) |
When does this matter?
Consider a cliff-walking problem:
- SARSA learns a safer path (avoids cliff edge because it knows it might accidentally fall)
- Q-learning learns the optimal path (hugs cliff edge, assuming perfect execution)
5. Deep Reinforcement Learning Foundations
5.1 Why Function Approximation?
Problem with Tabular Methods:
For Atari games: State space ≈ (a number with 242,000 digits!)
Three Reasons for Function Approximation:
- High-dimensional discrete spaces: Too many states to store in a table
- Continuous state spaces: Infinite states (e.g., robot joint angles)
- Generalization: Learn about similar states simultaneously
Analogy: You can't memorize the value of every possible chess position. Instead, you learn general principles (control the center, protect your king) that generalize.
5.2 How Function Approximation Helps
Without FA: Each state updated independently
V(s1) = 2.1 # Update s1 only affects s1
V(s2) = 3.4
V(s3) = 1.8With FA: Updates affect similar states
V_θ(s) = θ₀ + θ₁·s # A linear function
# Updating θ affects V for ALL statesKey insight: One update can improve estimates for many states you've never visited.
5.3 Neural Network Basics for RL
Architecture for Q-learning:
Input Layer (state) Hidden Layer(s) Output Layer (Q-values)
[s1] [h1] [Q(s,a1)]
[s2] → W1 → [h2] → W2 → [Q(s,a2)]
[s3] [h3] [Q(s,a3)]
[s4] [Q(s,a4)]For this course: One hidden layer is typically sufficient.
Warning: Deeper networks require more data and training time.
5.4 The CartPole Environment
A standard benchmark for testing RL algorithms:
Observations (4 continuous values):
- Cart position:
- Cart velocity:
- Pole angle: (terminal if exceeded)
- Pole tip velocity:
Actions: 2 discrete (push left or push right)
Reward: +1 for each timestep the pole stays upright
Goal: Keep the pole balanced for as long as possible
6. Value-Based Deep RL: DQN and Beyond
6.1 The Ideal Objective
We want to minimize:
Problem: We don't have !
Solution: Use TD targets as a proxy:
6.2 Two Critical Issues with Naive Deep Q-Learning
Issue 1: Non-Stationary Targets
When you update , the target also changes!
Imagine chasing a moving target:
Before update: Target at position X
After update: Target moved to position Y
→ Optimization landscape keeps shifting!This can cause divergence — the agent "unlearns" and performance collapses.
Issue 2: Correlated Data
Standard ML assumes IID (independent, identically distributed) data.
But in RL, consecutive samples are highly correlated:
- depends on and
- Training on trajectory data violates IID assumption
6.3 DQN: Deep Q-Networks
Two key innovations:
1. Experience Replay Buffer
Store transitions in a buffer (e.g., 1 million samples).
Sample random mini-batches for training → breaks correlation!
Replay Buffer D: [(s₁,a₁,r₁,s₁'), (s₂,a₂,r₂,s₂'), ...]
↓
Sample mini-batch uniformly at random
↓
Train on decorrelated data2. Target Network
Maintain a separate network for computing targets.
Update only periodically (e.g., every 10,000 steps).
Why it helps: Target stays fixed for many updates → stable optimization.
6.4 DQN Algorithm
Initialize Q_θ (online network) and Q_θ⁻ (target network)
Initialize replay buffer D
for each episode:
s = initial state
while not terminal:
# Select action (ε-greedy)
a = ε-greedy from Q_θ(s,·)
# Execute and observe
s', r, done = env.step(a)
# Store transition
D.store(s, a, r, s', done)
# Sample mini-batch from D
batch = D.sample(batch_size=32)
# Compute targets (using target network!)
y = r + γ * max_a' Q_θ⁻(s', a') * (1 - done)
# Update Q_θ via gradient descent
loss = (y - Q_θ(s,a))²
θ = θ - α∇_θ loss
# Periodically update target network
if step % C == 0:
θ⁻ = θ
s = s'6.5 The Target Network Equation
DQN Loss:
Note: is the target network (fixed), is the online network (being updated).
Critical: Don't backpropagate through the target! (Use .detach() in PyTorch)
6.6 Double DQN
Problem with DQN: Overestimation bias
When computing , we use the same network to:
- Select the best action
- Evaluate that action's value
If Q-values are noisy (they always are), max picks the one with the highest noise → systematic overestimation.
Solution: Decouple selection and evaluation
Standard DQN:
Double DQN:
- Online network : Selects the best action
- Target network : Evaluates that action
Example:
Online network estimates: Q_θ(s', a0) = 3.5, Q_θ(s', a1) = 1.2, Q_θ(s', a2) = 3.9
→ argmax = a2
Target network estimates: Q_θ⁻(s', a0) = 3.8, Q_θ⁻(s', a1) = -1.5, Q_θ⁻(s', a2) = 3.6
→ Use Q_θ⁻(s', a2) = 3.6 as target
Without Double DQN: Would use Q_θ⁻(s', a0) = 3.8 (target's argmax)This cross-validation style approach reduces overestimation.
6.7 Summary of DQN Improvements
| Technique | Problem Solved |
|---|---|
| Experience Replay | Correlated data, IID violation |
| Target Network | Non-stationary targets |
| Double DQN | Overestimation bias |
Additional improvements (not covered in depth):
- Prioritized Experience Replay: Sample important transitions more often
- Dueling Networks: Separate state value and advantage
- Noisy Nets: Learned exploration
- Rainbow: Combines multiple improvements
7. Policy-Based Methods
7.1 Value-Based vs Policy-Based
| Value-Based (DQN) | Policy-Based |
|---|---|
| Learn , derive policy as | Learn policy directly |
| Outputs values | Outputs action probabilities |
| Implicit policy | Explicit policy |
| Struggles with continuous actions | Natural for continuous actions |
| Deterministic policy (plus ε-greedy) | Can learn stochastic policies |
7.2 Why Policy-Based Methods?
Advantage 1: Continuous Action Spaces
With DQN, you need to compute . For continuous actions, this is intractable!
Policy networks output distributions directly:
Input: state s
Output: μ₁, σ₁, μ₂, σ₂, ... (means and std devs for each action dimension)Sample actions from
Advantage 2: Stochastic Policies
Some problems require randomness. Example: Rock-Paper-Scissors
The optimal strategy is uniform random:
A deterministic policy would be exploitable!
Advantage 3: State Aliasing
If two different states look identical to the agent, a stochastic policy can hedge:
State looks like X, but could be:
- State A (optimal action: left)
- State B (optimal action: right)
Optimal response: 50% left, 50% right7.3 Policy Gradient Objective
Goal: Find parameters that maximize expected return:
where is a trajectory
7.4 The Policy Gradient Theorem
Key Result:
Intuition:
- : Direction to make action more likely
- : How good was the outcome?
- Product: Increase probability of good actions, decrease probability of bad actions
Derivation insight (optional): Uses the "log-derivative trick":
7.5 REINFORCE Algorithm
The simplest policy gradient algorithm:
for each episode:
Generate trajectory τ = (s₀, a₀, r₁, ..., sT) using π_θ
for t = 0 to T:
G_t = Σ_{k=t}^T γ^(k-t) r_{k+1} # Return from t
θ = θ + α · ∇_θ log π_θ(aₜ|sₜ) · G_tKey improvement: Use rewards-to-go instead of full return
Instead of using for all timesteps, use (future rewards only).
Why? Actions at time shouldn't get credit for rewards that happened before .
7.6 Baselines and Variance Reduction
Problem: Policy gradients have high variance (noisy updates).
Solution: Subtract a baseline that doesn't depend on actions:
Why this works: (baseline doesn't change expected gradient)
Best baseline: (the value function!)
This leads to the Advantage Function:
Interpretation: How much better is action compared to the average action in state ?
8. Actor-Critic Methods
8.1 The Actor-Critic Framework
Two networks:
- Actor: Policy — chooses actions
- Critic: Value function — evaluates states
Environment
↓ state s
┌───────┴───────┐
↓ ↓
Actor Critic
π_θ(a|s) V_φ(s)
↓ ↓
action a value estimate
↓ ↓
└────┬────┘
↓
TD error δ = r + γV(s') - V(s)
↓
Update both networks8.2 Advantage Estimation
One-step advantage (TD error):
This IS the TD error! It estimates how much better the action was than expected.
8.3 A3C: Asynchronous Advantage Actor-Critic
Key idea: Run multiple workers in parallel, each with its own environment copy.
Benefits:
- Natural decorrelation (workers explore different parts of state space)
- Better CPU utilization (no GPU needed)
- Faster wall-clock training
Architecture:
Global Network (θ, φ)
/ | \ \
Worker1 Worker2 Worker3 ...
↓ ↓ ↓
Env1 Env2 Env3
↓ ↓ ↓
gradients (asynchronous updates to global network)"Asynchronous": Workers update the global network independently, without waiting for each other.
8.4 A2C: Advantage Actor-Critic (Synchronous)
Same as A3C but:
- Workers collect data in parallel
- Wait for all workers to finish
- Update network once with combined batch
Advantage: More stable updates (no race conditions)
Trade-off: Faster workers must wait for slower ones
8.5 n-Step Returns and GAE
n-Step Advantage:
Generalized Advantage Estimation (GAE):
where
Special cases:
- : One-step TD advantage (low variance, high bias)
- : Monte Carlo advantage (high variance, low bias)
Practical: or works well
8.6 Actor-Critic Update Equations
Critic Update (minimize TD error):
Actor Update (policy gradient with advantage):
Entropy bonus (encourages exploration):
where is entropy. Added to actor objective to prevent premature convergence.
9. Deterministic Policy Gradient Methods
9.1 Motivation: Continuous Control
Problem with Q-learning for continuous actions:
Computing requires iterating over all actions — impossible for continuous spaces!
Solution: Learn a deterministic policy that directly outputs the optimal action.
9.2 DDPG: Deep Deterministic Policy Gradient
Key insight: Combine DQN techniques with policy gradients for continuous control.
Two networks:
- Actor: — outputs deterministic action
- Critic: — evaluates state-action pairs
Note: Unlike A3C/A2C, the critic is a Q-function, not a V-function!
9.3 DDPG Architecture
State s → Actor μ_θ(s) → Action a
↓
┌───────────┴───────────┐
↓ ↓
State s, Action a → Critic Q_φ(s,a) → Q-valueActor objective: Maximize Q-values for chosen actions
Critic objective: Minimize TD error
9.4 DDPG Key Features
From DQN:
- Experience replay buffer
- Target networks (both actor and critic)
Different from DQN:
- Soft target updates: Instead of copying weights every steps,
where (e.g., 0.001). Smoother, more stable.
Exploration: Add noise to actions (e.g., Ornstein-Uhlenbeck noise for temporally correlated exploration)
9.5 Algorithm Family
| Algorithm | Key Features |
|---|---|
| DDPG | Deterministic policy + Q-learning for continuous control |
| TD3 | Twin critics + delayed policy updates (reduces overestimation) |
| SAC | Soft Actor-Critic, adds entropy regularization |
Recommendation for continuous control: TD3 or SAC are more stable than DDPG
10. Convergence and Theory
10.1 GLIE: Greedy in the Limit with Infinite Exploration
For control algorithms to converge to optimal, two conditions must hold:
Condition 1: All state-action pairs must be visited infinitely often:
Condition 2: Policy must converge to greedy:
ε-greedy with decay satisfies GLIE:
- Start with high ε (explore)
- Decay towards 0 (exploit)
- But decay slowly enough to keep exploring
10.2 Robbins-Monro Conditions for Step Sizes
For stochastic approximation (including TD/Q-learning) to converge:
Condition 1: Sum of step sizes is infinite (can reach any target):
Condition 2: Sum of squared step sizes is finite (variance goes to zero):
Example: satisfies both.
In practice: Often use constant small α (doesn't technically converge but tracks changing targets)
10.3 On-Policy vs Off-Policy Convergence
| On-Policy (SARSA) | Off-Policy (Q-Learning) | |
|---|---|---|
| Convergence guarantee | Needs GLIE | Needs GLIE for optimal control |
| What it converges to | Value of ε-greedy policy | Optimal Q-values |
| For accurate Q* | Needs both conditions | Only needs condition 1 |
10.4 Deep RL: No Guarantees
Important: All classical convergence guarantees assume:
- Tabular representations
- Exact updates
With function approximation (especially neural networks):
- No convergence guarantees
- Can diverge in practice
- "Deadly triad": function approximation + bootstrapping + off-policy = potential divergence
Mitigation techniques (used in DQN, etc.):
- Target networks
- Experience replay
- Gradient clipping
- Careful hyperparameter tuning
11. Algorithm Summary and Comparison
11.1 Prediction Methods
| Method | Update Target | Bias | Variance | Bootstraps |
|---|---|---|---|---|
| Monte Carlo | (actual return) | None | High | No |
| TD(0) | Yes | Low | Yes | |
| TD(λ) | λ-weighted mix | Tunable | Tunable | Yes |
11.2 Tabular Control Methods
| Method | Type | Update Target |
|---|---|---|
| MC Control | On-policy | |
| SARSA | On-policy | where is actual next action |
| Q-Learning | Off-policy |
11.3 Deep RL Methods
| Method | Type | Action Space | Key Features |
|---|---|---|---|
| DQN | Value-based | Discrete | Replay buffer, target network |
| Double DQN | Value-based | Discrete | + Decoupled action selection/evaluation |
| REINFORCE | Policy-based | Both | Simplest policy gradient |
| A2C/A3C | Actor-Critic | Both | Parallel workers, advantage |
| DDPG | Actor-Critic | Continuous | Deterministic policy, soft updates |
| TD3 | Actor-Critic | Continuous | Twin critics, delayed updates |
| PPO | Actor-Critic | Both | Clipped objective, stable |
11.4 When to Use What
| Scenario | Recommended Algorithm |
|---|---|
| Discrete actions, image input | DQN / Double DQN / Rainbow |
| Continuous actions | DDPG / TD3 / SAC / PPO |
| Simple discrete environment | Q-Learning (tabular) |
| Need stable training | PPO or TD3 |
| Multi-CPU, no GPU | A3C |
| Sample efficiency critical | SAC or model-based methods |
11.5 Key Equations Reference Card
Bellman Equation:
TD Error:
Q-Learning Update:
Policy Gradient:
DQN Loss:
Double DQN Target:
Exam Preparation Tips
- Know the core update equations for Q-learning, SARSA, TD, and policy gradients
- Understand the motivation for each technique (why replay buffers? why target networks?)
- Be able to trace through one update step for each algorithm
- Distinguish on-policy vs off-policy and when each matters
- Understand the bias-variance trade-off in MC vs TD
- Know the advantages of policy-based vs value-based methods
- Remember the two DQN innovations: replay buffer and target network
- Understand Double DQN: why it reduces overestimation