This is a great question about reinforcement learning fundamentals. I need to:
- Derive the Bellman optimality equation for Q-values
- Explain the connection to temporal difference (TD) error
- Connect it to Q-learning
Let me work through this systematically.
Part 1: Deriving the Bellman Optimality Equation for Q-values
Starting from first principles:
Q-value definition:
The Q-value Q(s,a) represents the expected cumulative discounted reward from taking action a in state s and following the optimal policy thereafter.
Q^π(s,a) = E[R_t | S_t = s, A_t = a] where the expectation is over the trajectory following policy π
The optimal Q-value:
Q*(s,a) = max_π Q^π(s,a)
Recursive decomposition:
The key insight is that we can decompose the Q-value recursively:
Q*(s,a) = E[R_t + γ Q*(S_{t+1}, A*_{t+1}) | S_t = s, A_t = a]
where A*{t+1} = argmax{a'} Q*(S_{t+1}, a') is the action taken under the optimal policy
Expanding the expectation:
Q*(s,a) = E[R_t | s,a] + γ E[max_{a'} Q*(S_{t+1}, a') | s,a]
Due to the Markov property:
Q*(s,a) = ∑{s'} P(s'|s,a)[R(s,a,s') + γ max{a'} Q*(s', a')]
where P(s'|s,a) is the transition probability and R(s,a,s') is the immediate reward.
This is the Bellman Optimality Equation for Q-values.
Part 2: Connection to TD Error and Q-learning
The Bellman equation holds perfectly for true Q* values, but when learning we work with an approximation Q(s,a). The temporal difference error measures the gap between what the Bellman equation predicts and our current estimate:
δ_t = [R_t + γ max_{a'} Q(S_{t+1}, a')] - Q(S_t, A_t)
The bracketed term is the bootstrapped target—it combines the immediate reward with our best estimate of future value—while the second term is our current Q-estimate. This error signal directly drives Q-learning updates, where we adjust Q(S_t, A_t) toward the target by an amount proportional to δ_t.
When the bootstrapped estimate exceeds our current Q-value, we increase it; when it falls short, we decrease it. The learning rate α controls how aggressively we move toward the target. Q-learning converges to Q* under standard conditions like bounded rewards and sufficient exploration, making it an off-policy algorithm that learns the optimal policy even while following a different exploratory behavior.
Bellman Optimality Equation for Q-values and Q-learning
Part 1: Deriving the Bellman Optimality Equation
Starting from First Principles
The Q-value represents the expected cumulative discounted reward:
Q∗(s,a)=E[∑
Recursive Decomposition
Breaking this into immediate and future components:
Q∗(s,a)=E[R
Bellman Optimality Equation (Full Form)
Using the Markov property and law of expectation:
Q∗
Key insight: At the optimal policy, we always take the greedy action in the next state.
Visual Representation
Current State s
|
| Take action a
↓
Receive R
Transition to s'
|
| Look ahead (via max over all a')
↓
Q*(s', best_a')
|
| Discount and combine
↓
Q*(s,a) = R + γ · max(Q*(s', a'))
Part 2: Temporal Difference Error
The Gap Between Theory and Practice
We don't know the true Q∗, only approximations Q(s,a). Define the TD error:
δt
Interpretation:
- Target: Our bootstrapped estimate of what Q(St,At) should be
- Current Estimate: What our value function currently predicts
- Error: How wrong our prediction was
Why "Temporal Difference"?
The error spans two time steps and combines:
- Immediate reward at time t
- Bootstrapped estimate at time t+1
Part 3: Q-learning Algorithm
The Update Rule
Q-learning uses the TD error to incrementally improve estimates:
Q(St,At
Expanding:
Q(St,A
Rearranged Form
Q(St,A
This is a convex combination between the old Q-value and the new target.
Implementation Example
Tabular Q-learning
import numpy as np
class QLearning:
def __init__(self, n_states, n_actions, learning_rate=0.1, discount=0.99):
self.Q = np.zeros((n_states, n_actions))
self.alpha = learning_rate # α
self.gamma = discount # γ
def update(self, state, action, reward, next_state, done):
"""
Apply Q-learning update rule
TD Target: r + γ * max(Q(s', a'))
TD Error: target - Q(s, a)
Update: Q(s,a) += α * (TD Error)
"""
# Compute TD target
if done:
# No future value if terminal state
td_target = reward
else:
# Bootstrap: use max Q-value of next state
max_next_q = np.max(self.Q[next_state, :])
td_target = reward + self.gamma * max_next_q
# Compute TD error
td_error = td_target - self.Q[state, action]
# Q-learning update
self.Q[state, action] += self.alpha * td_error
return td_error
def get_action(self, state, epsilon=0.1):
"""ε-greedy action selection"""
if np.random.random() < epsilon:
return np.random.randint(self.Q.shape[1]) # Explore
else:
return np.argmax(self.Q[state, :]) # Exploit
# Example usage
agent = QLearning(n_states=10, n_actions=4)
# Simulate one step
state, action, reward, next_state = 2, 1, 5.0, 3
td_error = agent.update(state, action, reward, next_state, done=False)
print(f"TD Error: {td_error:.4f}")
print(f"Updated Q({state},{action}): {agent.Q[state, action]:.4f}")
Deep Q-Network (DQN) Extension
import torch
import torch.nn as nn
class DQN(nn.Module):
"""Neural network approximator for Q(s,a)"""
def __init__(self, state_dim, action_dim, hidden_dim=64):
super().__init__()
self.net = nn.Sequential(
nn.Linear(state_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, action_dim)
)
def forward(self, state):
return self.net(state)
def dqn_update(model, target_model, state, action, reward,
next_state, done, device, gamma=0.99, alpha=0.001):
"""
DQN update with neural network Q-function
"""
state = torch.FloatTensor(state).to(device)
next_state = torch.FloatTensor(next_state).to(device)
# ============ Compute TD Target ============
with torch.no_grad():
if done:
td_target = reward
else:
# Use target network for stability
next_q_values = target_model(next_state.unsqueeze(0))
max_next_q = next_q_values.max().item()
td_target = reward + gamma * max_next_q
# ============ Compute TD Error ============
q_pred = model(state.unsqueeze(0))[0, action]
td_error = td_target - q_pred.item()
# ============ Gradient Descent ============
loss = (q_pred - td_target) ** 2
loss.backward()
return td_error, loss.item()
Convergence Analysis
Convergence Theorem
Under these conditions:
- Bounded rewards: ∣R∣≤Rmax
- All state-action pairs visited infinitely
- Decaying learning rate: ∑αt,
Then: Q(s,a)→Q∗(s,a) with probability 1 (tabular case)
Why Q-learning Converges
The update rule is a contraction mapping:
∥BQ−BQ′∥∞≤γ∥Q
where B is the Bellman backup operator. Contraction mappings have unique fixed points (Q∗).
Key Differences: On-Policy vs Off-Policy
| Aspect | SARSA (On-Policy) | Q-learning (Off-Policy) |
|---|
| Bootstrap | α(R+γQ(s′,a′)) | |
Summary
Bellman Optimality → Q*(s,a) = R + γ·max Q*(s',a')
↓
(We don't know Q*)
↓
TD Error → δ = [R + γ·max Q(s',a')] - Q(s,a)
↓
Q-learning → Q(s,a) ← Q(s,a) + α·δ
↓
Iteration → Converges to Q*
The TD error quantifies how much our current estimate violates the Bellman equation, and Q-learning corrects it proportionally.