Q-learning and deep Q-networks
Q-learning and Deep Q-Networks (DQN): value-based reinforcement learning methods for learning policies from rewards using Bellman equations, temporal-difference updates, and neural-network function approximation.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Reinforcement learning (RL) is used when an agent must learn actions to maximise long-run reward by trial and error. Q-learning gives a simple, widely used algorithm for model-free RL; deep Q-networks (DQN) scale Q-learning to large or continuous state spaces using neural networks. Engineers use these to build agents for control, games, robotics simulators, and recommendation systems where labelled training pairs are not available.
Key ideas
Define action-value function (Q-function) Q^π(s,a) = E[Σ_{t=0}^∞ γ^t r_{t} | s_0=s, a_0=a, π]. This gives expected return if we take action a in state s and follow policy π thereafter.
Bellman expectation equation (for policy π): V^π(s) = Σ_a π(a|s) Σ_{s'} P(s'|s,a) [R(s,a,s') + γ V^π(s')]. This is an exact linear equation in V^π.
Define optimal value and action-value functions: V^(s) = max_π V^π(s), Q^(s,a) = max_π Q^π(s,a). The policy π^(s) = argmax_a Q^(s,a) is optimal.
Bellman optimality equation (exact): Q^(s,a) = Σ_{s'} P(s'|s,a) [R(s,a,s') + γ max_{a'} Q^(s',a')]. This is the fixed-point equation Q^* must satisfy.
Q-learning: a model-free, off-policy, temporal-difference method that iteratively updates an estimate Q(s,a) toward the Bellman optimality target observed from experience (s,a,r,s'). Q-learning update rule (tabular): Q(s,a) ← Q(s,a) + α [r + γ max_{a'} Q(s',a') − Q(s,a)], where α ∈ (0,1] is the learning rate. Under standard assumptions (every state-action pair visited infinitely often, α_t decays with Σ α_t = ∞ and Σ α_t^2 < ∞), bounded rewards, and either γ < 1 or episodic termination, Q(s,a) converges to Q^* with probability 1 in finite MDPs.
Exploration vs exploitation: to learn Q^* we must sometimes try non-greedy actions. Common scheme: ε-greedy policy: with probability ε choose random action, otherwise choose argmax_a Q(s,a). ε often decays over time.
Deep Q-networks (DQN): replace tabular Q(s,a) with a neural network Q(s,a; θ) that approximates the action-value function when S is large or continuous. Standard DQN assumes a discrete action space; for continuous actions use actor-critic methods (e.g., DDPG, TD3, SAC). Key stabilisation techniques introduced in DQN:
- Replay buffer (experience replay): store transitions (s,a,r,s') and sample mini-batches uniformly (or prioritized) to break correlation between sequential samples.
- Target network: maintain a separate parameter copy θ^- whose parameters are updated less frequently (e.g., every C steps) to form the target r + γ max_{a'} Q(s',a'; θ^-). This reduces oscillations.
- Double DQN (DDQN): use the online network θ to select a' = argmax_a Q(s',a; θ) and the target network θ^- to evaluate it, y = r + γ Q(s', a'; θ^-), which reduces overestimation bias.
- Use stochastic gradient descent on squared temporal-difference (TD) error: minimize L(θ) = E[(r + γ max_{a'} Q(s',a'; θ^-) − Q(s,a; θ))^2].
Assumptions and limitations: function approximation (neural nets) can break convergence guarantees of tabular Q-learning. DQN stabilisers help but do not guarantee convergence in all settings. Use target networks, small learning rates, regularisation, and careful reward scaling.
Diagram to draw for an exam: draw a three-layer diagram labelled "state s" -> neural network box with weights θ -> outputs Q(s,a1), Q(s,a2), ...; indicate arrow to chosen action a = argmax Q; show transition to next state s' and reward r; show replay buffer box storing (s,a,r,s') with arrow back into network training batch; draw smaller copy of network labelled θ^- used to compute target. Label all arrows and boxes.
Formulas
Bellman expectation for V^π: V^π(s) = Σ_a π(a|s) Σ_{s'} P(s'|s,a) [R(s,a,s') + γ V^π(s')] — V^π(s) is in reward units; typically γ ∈ [0,1) for continuing tasks (to ensure bounded returns), while γ = 1 is allowed for finite episodic tasks with terminal states; γ is dimensionless.
Bellman optimality for Q^*: Q^*(s,a) = Σ_{s'} P(s'|s,a) [R(s,a,s') + γ max_{a'} Q^*(s',a')] — Q in reward units; γ dimensionless.
Tabular Q-learning update: Q(s,a) ← Q(s,a) + α [r + γ max_{a'} Q(s',a') − Q(s,a)] — α dimensionless, r in reward units, γ dimensionless.
ε-greedy policy: with probability ε choose action uniformly at random; otherwise choose argmax_a Q(s,a) — ε dimensionless in [0,1].
DQN loss for a mini-batch: L(θ) = E_{(s,a,r,s',done)∼D} [(y − Q(s,a; θ))^2] where y = r + γ (1 − done) max_{a'} Q(s',a'; θ^-) — many implementations use the Huber loss instead of squared error; loss has squared reward units.
Target network soft update (Polyak averaging): θ^- ← τ θ + (1 − τ) θ^- — τ ∈ (0,1] dimensionless; often small (e.g., 0.001).
Worked examples
Example 1 — short derivation (exam-style): Derive the Q-learning update from the Bellman optimality equation. Answer (model): Start from Bellman optimality fixed point Q^(s,a) = E[r + γ max_{a'} Q^(s',a') | s,a]. We cannot compute this expectation without model P and R. Instead, when we observe a sample transition (s,a,r,s') from interaction, we view the sample target y = r + γ max_{a'} Q(s',a'; θ_current). The temporal-difference error is δ = y − Q(s,a). Interpreting the update as stochastic approximation to solve the fixed point, we apply the Robbins–Monro update rule: Q_{t+1}(s,a) = Q_t(s,a) + α_t δ_t, which yields the Q-learning update. This update is an unbiased sample of the Bellman optimality operator applied to the current Q under the transition distribution; however, the max over noisy estimates introduces overestimation bias in practice (Double Q-learning/Double DQN mitigates this). Convergence requires visiting all (s,a) infinitely often and α_t satisfying Σ α_t = ∞, Σ α_t^2 < ∞.
Example 2 — programming: small deterministic tabular Q-learning single-step update (Python). This is minimal, deterministic and exam-friendly.
Code:
# Tabular one-step Q-learning update (deterministic example)
import numpy as np
# small MDP: states 0,1,2 (2 is terminal), actions 0,1
Q = np.zeros((3,2))
alpha = 0.5
gamma = 0.9
# observe transition: from state 1, action 0, reward 1, next state 2 (terminal)
s = 1
a = 0
r = 1.0
s_next = 2
# update
Q[s,a] = Q[s,a] + alpha * (r + gamma * np.max(Q[s_next]) - Q[s,a])
print('Updated Q-table:')
print(Q)
Sample input: (none — program runs deterministically) Exact output:
Updated Q-table:
[[0. 0. ]
[0.5 0. ]
[0. 0. ]]
Explanation: Q[1,0] becomes 0.5 because 0 + 0.5*(1 + 0 − 0) = 0.5. If s_next is terminal, explicitly omit the γ max term; here it is zero because Q[2] = [0, 0].
Example 3 — programming: DQN forward pass with fixed weights (PyTorch). This demonstrates network shape, deterministic output and how target network is separate.
Code:
import torch
import torch.nn as nn
# tiny DQN forward-pass example with fixed weights
class TinyDQN(nn.Module):
def __init__(self, state_size, hidden, action_size):
super().__init__()
self.fc1 = nn.Linear(state_size, hidden)
self.fc2 = nn.Linear(hidden, action_size)
self.relu = nn.ReLU()
def forward(self, x):
h = self.relu(self.fc1(x))
return self.fc2(h)
state = torch.tensor([1.0, 2.0, 3.0, 4.0])
model = TinyDQN(state_size=4, hidden=8, action_size=2)
# set weights to fixed constants for deterministic output
model.fc1.weight.data.fill_(0.1)
model.fc1.bias.data.zero_()
model.fc2.weight.data.fill_(0.2)
model.fc2.bias.data.zero_()
q_values = model(state)
print('Q-values:', q_values)
Exact output:
Q-values: tensor([1.6000, 1.6000], grad_fn=<AddBackward0>)
Reason: fc1 produces hidden units each equal to 0.1*(1+2+3+4)=1.0; ReLU keeps 1.0; fc2 outputs for each action = 0.2*(8*1.0)=1.6.
Common mistakes
- Using the same network parameters for both the predicted Q and the target without a target network or soft updates — this often causes divergence.
- Not normalising or clipping rewards; large reward scales can destabilise neural-network training.
- Using an inappropriate learning-rate schedule; for tabular Q-learning α_t must decrease to satisfy convergence conditions.
- Sampling correlated sequential transitions instead of using a replay buffer — causes inefficient learning and unstable gradients.
For your exam
Question types you should expect: definitions (MDP, Q-function, Bellman equations), derivations (derive Q-learning update from Bellman equation), short notes (explain replay buffer and target network), numerical (compute one Q-update for given α, γ, r), program fragments (write one-step Q-update or a small DQN forward pass), and diagrams (draw DQN architecture with replay buffer and target network).
What full-marks answers include:
- Precise definitions with symbols (S, A, P, R, γ), clear statement of Bellman equations, and assumptions (Markov property, finite MDP for tabular convergence).
- Derivation steps for Q-learning as stochastic approximation and mention of Robbins–Monro conditions for α_t.
- In programming questions include code (or pseudo-code) for Q-update, specify exploration policy (ε-greedy), and explain stabilisation tricks (replay buffer, target network).
- For diagrams label all boxes and arrows and explain the flow of data during acting and learning.
Quick check
- State the tabular Q-learning update formula.
- Why use a target network in DQN?
- What conditions on α_t (learning rate sequence) are required for convergence in tabular Q-learning? Answers: 1) Q(s,a) ← Q(s,a) + α [r + γ max_{a'} Q(s',a') − Q(s,a)]. 2) To stabilise targets by decoupling the slowly-changing target parameters θ^- from the online network parameters θ, reducing oscillation/divergence. 3) Σ_t α_t = ∞ and Σ_t α_t^2 < ∞ (e.g., α_t = 1/t), and every state-action pair visited infinitely often.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?