Value Functions and Q Functions
Value-Based Reinforcement Learning: Q-Learning and Beyond
This section covers value-based reinforcement learning methods, with a focus on Q-learning—arguably the first deep reinforcement learning algorithm. The core idea is to learn a Q-function that can be used to derive a policy without explicitly representing the policy as a separate neural network.
Recap: From Policy Gradients to Actor-Critic
Earlier lectures covered two main families of algorithms:
Policy gradient methods: Alternating between collecting data from the current policy and improving the policy by increasing the log-likelihood of actions that yield higher-than-average returns (with a baseline subtracted to reduce variance).
Actor-critic methods: Introduce an additional step—estimating the expected future reward (a value function or Q-function) for the current policy and using that estimate to improve the policy. The policy gradient becomes: ∇J≈E[∇logπ(a∣s)⋅(Q(s,a)−b)], where b is a baseline.
A key extension was off-policy actor-critic: Instead of using only data from the current policy (on-policy), we can reuse all past data from a replay buffer. To do this, we need to estimate a Q-function from past policy data. The Q-function is defined recursively:
We use a neural network with input (s,a) and output Qϕ(s,a). The learning objective uses bootstrapped targets: sample (s,a,s′) from the buffer, sample a′ from the current policy (not the past policy), and set the target as yi=r+γQϕ(s′,a′). Then we perform supervised learning on these targets. A critical requirement is coverage: the data set must contain enough state-action pairs that the current policy would visit, especially for actions the new policy might take.
From Q-Functions to Policies: A Key Insight
Suppose we have an accurate estimate of the Q-function for a given policy π, denoted Qπ(s,a). Then we can define a new policy π′ that simply chooses the action with the highest Q-value at each state:
This is a deterministic policy that always follows what the Q-function suggests is best.
Example: 2D Navigation
Consider a 2D navigation problem where the agent starts in a blue box and must reach a star. The reward is +1 at the star and 0 elsewhere. The current policy π always moves right. We have accurate Qπ values.
State-action space: Moving up takes 1 time step to cover a certain distance; moving right takes 2 time steps for the same distance. The grid is divided into rows.
Qπ values for states on the row containing the star: For actions consistent with π (moving right), Qπ=1 (because you will eventually reach the star). For actions like moving up, if followed by the policy (which goes right), you might still reach the star, so Qπ=1 as well (with discount γ=1).
Qπ values for states one row below the star: For action right, Qπ=0 (you never reach the star by going right). For action up, Qπ=1 (because you move up to the star row, then follow the policy which eventually gets the reward).
Qπ values for states further below (two rows down): For action up, Qπ=0 (following up then the policy still misses the star because after moving up you are still not on the correct row and then you go right forever).
The new policy π′ (greedy with respect to Qπ) will:
Continue right for states on the star row.
Go up for states one row below the star.
For states two rows below, all Q-values are zero, so it defaults to the previous behavior (go right, since that's the action with highest Q, though all are zero; in practice, ties break arbitrarily, often remaining with the original policy's action).
Result: π′ is better than π (it reaches the star from more states) but it is not optimal. From the starting state (two rows below), it still goes right and never reaches the star. This shows that a single step of greedy improvement does not yield the optimal policy.
Key Property: Policy Improvement Theorem
The new policy π′ is always at least as good as π (assuming Qπ is accurate). Proof: For any state s,
so the expected return from following π′ is at least as high as from following π.
If we iterate this process—update the Q-function for the new policy, then improve again—we converge to the optimal policy. This iterative procedure is called policy iteration.
Generalization to Continuous Actions
When actions are continuous, the argmax operation is nontrivial. Possible approaches:
Gradient-based optimization (e.g., gradient ascent on Q(s,a) w.r.t. a), though this often works poorly.
Sampling: generate many candidate actions and pick the one with highest Q.
Cross-entropy method or other sampling-based optimization.
For discrete action spaces (e.g., text), one can perform a discrete search over actions.
Policy Iteration Algorithm
The policy iteration algorithm consists of two alternating steps:
Policy Evaluation: Estimate Qπ for the current policy π.
Policy Improvement: Set π′ to be greedy w.r.t. Qπ: π′(s)=argmaxaQπ(s,a).
In practice, we can implement this using an off-policy actor-critic framework:
Step 1: Collect data using some policy (often the current greedy policy with exploration, or an older policy).
Step 2: Fit Qϕ to approximate Qπ using bootstrapped targets:
yi=r(s,a)+γQϕ(s′,a′),a′∼π(⋅∣s′)Step 3: Improve the policy by setting πnew to be greedy: πnew(s)=argmaxaQϕ(s,a).
Alternatively, we can incorporate the improvement directly into the target by using maxa′Qϕ(s′,a′) instead of Ea′∼πQϕ(s′,a′). This yields targets that are Q-values for the new (greedy) policy. This leads to the Bellman optimality equation for Q-functions.
The Bellman Equation and Bellman Optimality Equation
Bellman Equation (for any policy π):
Qπ(s,a)=Es′[r(s,a)+γEa′∼πQπ(s′,a′)]Used for policy evaluation.
Bellman Optimality Equation (for the optimal policy π∗):
Q∗(s,a)=Es′[r(s,a)+γmaxa′Q∗(s′,a′)]This holds if and only if the policy is optimal. Q-learning aims to find a Q-function that satisfies this equation—effectively directly learning Q∗.
Key takeaway: The Bellman optimality equation characterizes the optimal Q-function. If we can learn Q∗, the optimal policy is simply π∗(s)=argmaxaQ∗(s,a).
Q-Learning Algorithm
Q-learning is an off-policy algorithm that learns the optimal Q-function directly, without separately representing a policy. The central update uses the Bellman optimality equation.
Basic Tabular Q-Learning (Convergence Guaranteed)
For small, discrete state and action spaces, Q-learning stores a table Q(s,a). Under two conditions—full coverage of all state-action pairs in the data and sufficient exploration—tabular Q-learning converges to Q∗. However, this guarantee does not hold when using function approximation (e.g., neural networks), even with linear functions; divergence can occur.
Deep Q-Learning (DQN)
Deep Q-learning uses a neural network Qϕ(s,a) to approximate the Q-function. The algorithm collects data using some exploration policy (often epsilon-greedy) and stores transitions (s,a,r,s′) in a replay buffer. Then it samples a batch uniformly from the buffer and updates the network to minimize:
Note: The target r+γmaxa′Qϕ(s′,a′) uses the same network for both selecting and evaluating the next action, which can cause overestimation (discussed later).
Why Off-Policy? Exploration Policy
The data in the replay buffer may come from different policies than the current one. This is fine because Q-learning is off-policy: the Bellman optimality equation holds for all (s,a), regardless of how they were sampled. However, to get accurate Q-values for all actions, especially those considered in the max, we need good coverage of the action space. If an action is never sampled, its Q-value may be erroneously high, leading to poor targets.
Common exploration policies:
Epsilon-greedy: With probability ϵ, take a random action (uniformly); otherwise, take the greedy action a=argmaxaQϕ(s,a). Typically ϵ starts high and decays over time.
Boltzmann exploration: Sample actions with probability proportional to exp(Q(s,a)/τ), where τ is a temperature parameter. This naturally weights actions by their Q-values.
For continuous actions, epsilon-greedy generalizes to sampling from a uniform distribution over the action space (or a wide Gaussian), while Boltzmann exploration is more common.
Practical DQN Algorithm
Initialize replay buffer D as empty.
For each iteration:
Collect data using exploration policy (e.g., epsilon-greedy) and add to D.
(Optional: Pre-populate buffer with random data.)
For K gradient steps:
Sample a batch {(s,a,r,s′)} uniformly from D.
Compute targets: yi=ri+γmaxa′Qϕ(si′,a′).
Update ϕ by gradient descent on N1∑(yi−Qϕ(si,ai))2.
After training, extract policy: π(s)=argmaxaQϕ(s,a).
K can be set to 1 (common) or larger for better data efficiency.
The replay buffer typically uses a fixed size (e.g., 1 million transitions) with FIFO replacement. Old data is discarded to avoid outdated experiences.
Three Tricks for Stable Deep Q-Learning
Even with a replay buffer, deep Q-learning can be unstable. Three crucial enhancements make it work:
1. Target Network (DQN)
The instability partly comes from a moving target: as Qϕ changes, the targets r+γmaxa′Qϕ(s′,a′) change every gradient step. This makes the optimization non-stationary.
Solution: Freeze a separate target network Qϕ− (with parameters ϕ− that are not updated) for generating targets. Periodically (e.g., every 10,000 steps) copy the current ϕ to ϕ−. The update becomes:
Now the targets are fixed for many steps, making the inner loop a stable supervised learning problem. This algorithm is the classic DQN (Deep Q-Network) introduced in 2013, which successfully learned to play Atari games from pixel observations.
Important practical tip: During training, the Q-loss often increases over time! This is not necessarily a bug—as the agent collects better data (with higher rewards), the targets scale up, increasing the loss magnitude. Don't be alarmed if the loss goes up.
2. Double DQN (Mitigating Overestimation)
Q-learning tends to overestimate Q-values because the target uses the same function to both select and evaluate the action: maxa′Qϕ(s′,a′). Any noise in Qϕ (due to function approximation) is exploited by the max, leading to upward bias.
Solution: Double Q-learning uses two different networks to decorrelate the noise:
One network (the current network ϕ) selects the action: a∗=argmaxa′Qϕ(s′,a′).
A different network (the target network ϕ−) evaluates that action: Qϕ−(s′,a∗).
Thus the target becomes:
Because DQN already has two sets of parameters (the current and target networks), Double DQN simply reuses them in this way without additional memory. This significantly reduces overestimation, leading to more accurate Q-values and better policies.
3. N-Step Returns (Trade-off)
The standard Q-learning target uses a one-step bootstrap: r+γmaxQ(s′). If the Q-function is poor early in training, this bootstrap may be noisy. In actor-critic, n-step returns were used to reduce bias by using actual rewards for n steps before bootstrapping:
Advantage: Faster learning early on because the targets rely more on actual rewards (less biased) and less on potentially inaccurate Q-values.
Disadvantage: Off-policy issue—the rewards rt+k were collected under the behavior policy (the exploration policy that generated the data), not under the greedy policy we are trying to evaluate. Only for n=1 is the reward purely a function of (s,a) and thus independent of the behavior policy.
In practice, many implementations simply ignore this mismatch and use n>1, often with good results. More sophisticated approaches:
Dynamically choose n based on how well the actions in the trajectory match the current greedy policy (e.g., only use n-step returns for segments where all actions are greedy).
Importance sampling to correct for the distribution mismatch.
Comparison of Online RL Algorithms
Three major families of online deep RL algorithms covered so far:
PPO (Proximal Policy Optimization)
Type: On-policy, policy gradient.
Strengths: Stable, easy to tune, works well across many problems.
Weaknesses: Very data-inefficient (discards samples after each update).
Best for: Problems where data is cheap (e.g., simulation) and stability is paramount.
DQN (Deep Q-Network) and Variants
Type: Off-policy, value-based.
Strengths: Data-efficient (reuses past data), works well for discrete action spaces or low-dimensional continuous actions (with sampling-based max).
Weaknesses: Less stable than PPO; requires tricks (target network, double DQN, etc.) to work well.
Best for: Problems with discrete actions, pixel observations, or where sample efficiency matters.
SAC (Soft Actor-Critic) and Variants
Type: Off-policy, actor-critic (maximizes both reward and entropy).
Strengths: Very data-efficient, works well for continuous control.
Weaknesses: More hyperparameters to tune, slightly less stable than PPO.
Best for: Robotic control and other sample-constrained continuous problems.
Successful Applications of DQN
Atari Games: DQN achieved human-level or above performance on many games (e.g., Breakout, Pong) using only pixel observations. The bar chart shows games above the line were superhuman.
Robotic Grasping: DQN with continuous actions (using sampling-based optimization) trained a robot to grasp objects with 96% success rate. The RL approach learned to maneuver around objects, not just pick straight down, demonstrating the power of learning from trial and error.
Key Takeaways
Q-functions allow us to derive a policy without explicitly representing it: π(s)=argmaxaQ(s,a).
Policy iteration alternates between evaluating Qπ and setting π greedy w.r.t. it; this converges to the optimal policy.
Q-learning directly learns the optimal Q-function from the Bellman optimality equation, off-policy, using bootstrapped targets r+γmaxQ(s′,a′).
Practical deep Q-learning requires three tricks:
Target network to stabilize targets.
Double DQN to reduce overestimation.
N-step returns to speed up learning (with some bias).
Exploration is critical; epsilon-greedy is a common choice.
The choice of algorithm depends on the problem: PPO for stability, DQN for discrete actions, SAC for sample-efficient continuous control.

Ask anything
We've read this whole study set, so questions about it get the best answers.