1. Home
  2. Explore
  3. Computer Science
  4. Value Functions and Q Functions

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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)]\nabla J \approx \mathbb{E}[\nabla \log \pi(a|s) \cdot (Q(s,a) - b)]∇J≈E[∇logπ(a∣s)⋅(Q(s,a)−b)], where bbb 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:

Qπ(s,a)=Es′∼p(⋅∣s,a)[r(s,a)+γQπ(s′,a′)],a′∼π(⋅∣s′)Q^{\pi}(s,a) = \mathbb{E}_{s' \sim p(\cdot|s,a)} \left[ r(s,a) + \gamma Q^{\pi}(s', a') \right], \quad a' \sim \pi(\cdot|s')Qπ(s,a)=Es′∼p(⋅∣s,a)​[r(s,a)+γQπ(s′,a′)],a′∼π(⋅∣s′)

We use a neural network with input (s,a)(s,a)(s,a) and output Qϕ(s,a)Q_{\phi}(s,a)Qϕ​(s,a). The learning objective uses bootstrapped targets: sample (s,a,s′)(s,a,s')(s,a,s′) from the buffer, sample a′a'a′ from the current policy (not the past policy), and set the target as yi=r+γQϕ(s′,a′)y_i = r + \gamma Q_{\phi}(s', a')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 π\piπ, denoted Qπ(s,a)Q^{\pi}(s,a)Qπ(s,a). Then we can define a new policy π′\pi'π′ that simply chooses the action with the highest Q-value at each state:

π′(a∣s)={1if a=arg⁡max⁡aQπ(s,a)0otherwise\pi'(a|s) = \begin{cases} 1 & \text{if } a = \arg\max_{a} Q^{\pi}(s,a) \\ 0 & \text{otherwise} \end{cases}π′(a∣s)={10​if a=argmaxa​Qπ(s,a)otherwise​

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 π\piπ always moves right. We have accurate QπQ^{\pi}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πQ^{\pi}Qπ values for states on the row containing the star: For actions consistent with π\piπ (moving right), Qπ=1Q^{\pi}=1Qπ=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π=1Q^{\pi}=1Qπ=1 as well (with discount γ=1\gamma=1γ=1).

  • QπQ^{\pi}Qπ values for states one row below the star: For action right, Qπ=0Q^{\pi}=0Qπ=0 (you never reach the star by going right). For action up, Qπ=1Q^{\pi}=1Qπ=1 (because you move up to the star row, then follow the policy which eventually gets the reward).

  • QπQ^{\pi}Qπ values for states further below (two rows down): For action up, Qπ=0Q^{\pi}=0Qπ=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 π′\pi'π′ (greedy with respect to QπQ^{\pi}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: π′\pi'π′ is better than π\piπ (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 π′\pi'π′ is always at least as good as π\piπ (assuming QπQ^{\pi}Qπ is accurate). Proof: For any state sss,

Vπ′(s)=Qπ(s,arg⁡max⁡aQπ(s,a))≥Qπ(s,a)=Vπ(s) for all a,V^{\pi'}(s) = Q^{\pi}(s, \arg\max_a Q^{\pi}(s,a)) \geq Q^{\pi}(s, a) = V^{\pi}(s) \text{ for all } a,Vπ′(s)=Qπ(s,argmaxa​Qπ(s,a))≥Qπ(s,a)=Vπ(s) for all a,

so the expected return from following π′\pi'π′ is at least as high as from following π\piπ.

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 arg⁡max⁡\arg\maxargmax operation is nontrivial. Possible approaches:

  • Gradient-based optimization (e.g., gradient ascent on Q(s,a)Q(s,a)Q(s,a) w.r.t. aaa), though this often works poorly.

  • Sampling: generate many candidate actions and pick the one with highest QQQ.

  • 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:

  1. Policy Evaluation: Estimate QπQ^{\pi}Qπ for the current policy π\piπ.

  2. Policy Improvement: Set π′\pi'π′ to be greedy w.r.t. QπQ^{\pi}Qπ: π′(s)=arg⁡max⁡aQπ(s,a)\pi'(s) = \arg\max_a Q^{\pi}(s,a)π′(s)=argmaxa​Qπ(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ϕQ_{\phi}Qϕ​ to approximate QπQ^{\pi}Qπ using bootstrapped targets:

    yi=r(s,a)+γQϕ(s′,a′),a′∼π(⋅∣s′)y_i = r(s,a) + \gamma Q_{\phi}(s', a'), \quad a' \sim \pi(\cdot|s')yi​=r(s,a)+γQϕ​(s′,a′),a′∼π(⋅∣s′)
  • Step 3: Improve the policy by setting πnew\pi_{\text{new}}πnew​ to be greedy: πnew(s)=arg⁡max⁡aQϕ(s,a)\pi_{\text{new}}(s) = \arg\max_a Q_{\phi}(s,a)πnew​(s)=argmaxa​Qϕ​(s,a).

Alternatively, we can incorporate the improvement directly into the target by using max⁡a′Qϕ(s′,a′)\max_{a'} Q_{\phi}(s',a')maxa′​Qϕ​(s′,a′) instead of Ea′∼πQϕ(s′,a′)\mathbb{E}_{a'\sim\pi} Q_{\phi}(s',a')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 π\piπ):

    Qπ(s,a)=Es′[r(s,a)+γEa′∼πQπ(s′,a′)]Q^{\pi}(s,a) = \mathbb{E}_{s'} \left[ r(s,a) + \gamma \mathbb{E}_{a'\sim\pi} Q^{\pi}(s',a') \right]Qπ(s,a)=Es′​[r(s,a)+γEa′∼π​Qπ(s′,a′)]

    Used for policy evaluation.

  • Bellman Optimality Equation (for the optimal policy π∗\pi^*π∗):

    Q∗(s,a)=Es′[r(s,a)+γmax⁡a′Q∗(s′,a′)]Q^*(s,a) = \mathbb{E}_{s'} \left[ r(s,a) + \gamma \max_{a'} Q^*(s',a') \right]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∗Q^*Q∗.

Key takeaway: The Bellman optimality equation characterizes the optimal Q-function. If we can learn Q∗Q^*Q∗, the optimal policy is simply π∗(s)=arg⁡max⁡aQ∗(s,a)\pi^*(s) = \arg\max_a Q^*(s,a)π∗(s)=argmaxa​Q∗(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)Q(s,a)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∗Q^*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)Q_{\phi}(s,a)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′)(s,a,r,s')(s,a,r,s′) in a replay buffer. Then it samples a batch uniformly from the buffer and updates the network to minimize:

L(ϕ)=E(s,a,r,s′)∼D[(r+γmax⁡a′Qϕ(s′,a′)−Qϕ(s,a))2]\mathcal{L}(\phi) = \mathbb{E}_{(s,a,r,s')\sim \mathcal{D}} \left[ \left( r + \gamma \max_{a'} Q_{\phi}(s',a') - Q_{\phi}(s,a) \right)^2 \right]L(ϕ)=E(s,a,r,s′)∼D​[(r+γmaxa′​Qϕ​(s′,a′)−Qϕ​(s,a))2]

Note: The target r+γmax⁡a′Qϕ(s′,a′)r + \gamma \max_{a'} Q_{\phi}(s',a')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)(s,a)(s,a), regardless of how they were sampled. However, to get accurate Q-values for all actions, especially those considered in the max⁡\maxmax, 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 ϵ\epsilonϵ, take a random action (uniformly); otherwise, take the greedy action a=arg⁡max⁡aQϕ(s,a)a = \arg\max_a Q_{\phi}(s,a)a=argmaxa​Qϕ​(s,a). Typically ϵ\epsilonϵ starts high and decays over time.

  • Boltzmann exploration: Sample actions with probability proportional to exp⁡(Q(s,a)/τ)\exp(Q(s,a)/\tau)exp(Q(s,a)/τ), where τ\tauτ 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

  1. Initialize replay buffer D\mathcal{D}D as empty.

  2. For each iteration:

    • Collect data using exploration policy (e.g., epsilon-greedy) and add to D\mathcal{D}D.

    • (Optional: Pre-populate buffer with random data.)

    • For KKK gradient steps:

      • Sample a batch {(s,a,r,s′)}\{(s,a,r,s')\}{(s,a,r,s′)} uniformly from D\mathcal{D}D.

      • Compute targets: yi=ri+γmax⁡a′Qϕ(si′,a′)y_i = r_i + \gamma \max_{a'} Q_{\phi}(s_i', a')yi​=ri​+γmaxa′​Qϕ​(si′​,a′).

      • Update ϕ\phiϕ by gradient descent on 1N∑(yi−Qϕ(si,ai))2\frac{1}{N} \sum (y_i - Q_{\phi}(s_i,a_i))^2N1​∑(yi​−Qϕ​(si​,ai​))2.

  3. After training, extract policy: π(s)=arg⁡max⁡aQϕ(s,a)\pi(s) = \arg\max_a Q_{\phi}(s,a)π(s)=argmaxa​Qϕ​(s,a).

  • KKK 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ϕQ_{\phi}Qϕ​ changes, the targets r+γmax⁡a′Qϕ(s′,a′)r + \gamma \max_{a'} Q_{\phi}(s',a')r+γmaxa′​Qϕ​(s′,a′) change every gradient step. This makes the optimization non-stationary.

Solution: Freeze a separate target network Qϕ−Q_{\phi^-}Qϕ−​ (with parameters ϕ−\phi^-ϕ− that are not updated) for generating targets. Periodically (e.g., every 10,000 steps) copy the current ϕ\phiϕ to ϕ−\phi^-ϕ−. The update becomes:

L(ϕ)=E[(r+γmax⁡a′Qϕ−(s′,a′)−Qϕ(s,a))2]\mathcal{L}(\phi) = \mathbb{E} \left[ \left( r + \gamma \max_{a'} Q_{\phi^-}(s',a') - Q_{\phi}(s,a) \right)^2 \right]L(ϕ)=E[(r+γmaxa′​Qϕ−​(s′,a′)−Qϕ​(s,a))2]

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: max⁡a′Qϕ(s′,a′)\max_{a'} Q_{\phi}(s',a')maxa′​Qϕ​(s′,a′). Any noise in QϕQ_{\phi}Qϕ​ (due to function approximation) is exploited by the max⁡\maxmax, leading to upward bias.

Solution: Double Q-learning uses two different networks to decorrelate the noise:

  • One network (the current network ϕ\phiϕ) selects the action: a∗=arg⁡max⁡a′Qϕ(s′,a′)a^* = \arg\max_{a'} Q_{\phi}(s',a')a∗=argmaxa′​Qϕ​(s′,a′).

  • A different network (the target network ϕ−\phi^-ϕ−) evaluates that action: Qϕ−(s′,a∗)Q_{\phi^-}(s', a^*)Qϕ−​(s′,a∗).

Thus the target becomes:

yi=ri+γQϕ−(s′,arg⁡max⁡a′Qϕ(s′,a′))y_i = r_i + \gamma Q_{\phi^-}\left(s', \arg\max_{a'} Q_{\phi}(s',a')\right)yi​=ri​+γQϕ−​(s′,argmaxa′​Qϕ​(s′,a′))

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+γmax⁡Q(s′)r + \gamma \max Q(s')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 nnn steps before bootstrapping:

yi(n)=∑k=0n−1γkrt+k+γnmax⁡a′Qϕ(st+n,a′)y_i^{(n)} = \sum_{k=0}^{n-1} \gamma^k r_{t+k} + \gamma^n \max_{a'} Q_{\phi}(s_{t+n}, a')yi(n)​=∑k=0n−1​γkrt+k​+γnmaxa′​Qϕ​(st+n​,a′)
  • 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+kr_{t+k}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=1n=1n=1 is the reward purely a function of (s,a)(s,a)(s,a) and thus independent of the behavior policy.

In practice, many implementations simply ignore this mismatch and use n>1n>1n>1, often with good results. More sophisticated approaches:

  • Dynamically choose nnn 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⁡\maxmax).

  • 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)=arg⁡max⁡aQ(s,a)\pi(s) = \arg\max_a Q(s,a)π(s)=argmaxa​Q(s,a).

  • Policy iteration alternates between evaluating QπQ^{\pi}Qπ and setting π\piπ 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+γmax⁡Q(s′,a′)r + \gamma \max Q(s',a')r+γmaxQ(s′,a′).

  • Practical deep Q-learning requires three tricks:

    1. Target network to stabilize targets.

    2. Double DQN to reduce overestimation.

    3. 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent