Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Deep Q-networks

Deep Q-Networks (DQN) use neural networks to approximate the action-value function Q(s,a) for large MDPs, and they stabilise learning using experience replay and a target network.

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

Deep Q-Networks (DQN) show how to extend tabular Q-learning to large or continuous state spaces by using a neural network as a function approximator for the action-value function. An engineer uses DQN when the state space is too large for tables (for example, raw images, continuous sensors) and they need an off-policy, value-based control method that can learn from past transitions stored in replay memory.

Key ideas

  • Optimal action-value function (Q): Q(s,a) = max_π Qπ(s,a). It satisfies the Bellman optimality equation: Q*(s,a) = E[r + γ max_{a'} Q*(s',a') | s,a]. Important property: under standard assumptions (bounded rewards and 0≤γ<1), the Bellman optimality operator is a γ-contraction in the sup-norm on the space of bounded action-value functions, so Q* exists and is unique. (State assumptions: bounded rewards; γ∈[0,1).)

  • Q-learning (tabular): Off-policy TD control algorithm that iteratively applies the sample update Q(s,a) ← Q(s,a) + α [r + γ max_{a'} Q(s',a') - Q(s,a)]. Converges to Q* under Robbins–Monro step-size conditions, visiting all state-action pairs infinitely often, and for tabular representations.

  • Function approximation problem: When state space is large, store Qθ(s,a) with parameters θ (e.g., neural network). Simple substitution of a moving target r + γ max_a' Qθ(s',a'; θ) into a gradient update can diverge. This is the practical cause of instability linked to the deadly triad: (1) function approximation, (2) bootstrapping, (3) off-policy updates.

  • Deep Q-Network (DQN): A practical architecture and training recipe to stabilise Q-learning with deep networks. Key components:

    • Q-network: a parameterised function Q(s,a; θ) (typically a neural network) that outputs action-values.
    • Experience replay (replay memory): store transitions (s,a,r,s',done) in a buffer and sample i.i.d. minibatches to break temporal correlations and improve data efficiency.
    • Target network: a copy of the Q-network with parameters θ⁻ that are held fixed for a number of steps and periodically (or softly) updated to θ; used to compute the bootstrap target y = r + γ max_{a'} Q(s',a'; θ⁻). This reduces moving-target instability.
    • Loss: mean squared error between the target y and Q(s,a; θ): L(θ) = E[(y - Q(s,a; θ))^2]. Many implementations (including DQN for Atari) use the Huber loss (smooth L1) with κ=1 to reduce sensitivity to large TD errors. Training minimises L by gradient descent.
  • Derivation of DQN gradient (standard exam derivation): With target y treated as constant (depends on θ⁻ only),

    • Define δ(θ) = y - Q(s,a; θ).
    • L(θ) = 1/2 · E[δ(θ)^2] (some implementations omit 1/2; DQN paper used MSE without 1/2).
    • ∇_θ L(θ) = -E[δ(θ) ∇_θ Q(s,a; θ)]. Show step-by-step: derivative of 1/2 δ^2 is δ · dδ/dθ; dδ/dθ = -∇_θ Q; hence gradient is -E[δ ∇_θ Q]. This provides the supervised regression-style gradient.
  • Policy extraction: The greedy policy with respect to Qθ is π(s) = argmax_a Qθ(s,a). In practice, an exploration policy (ε-greedy) is used during training.

  • Practical tricks: reward clipping, frame stacking (for images), normalising inputs, gradient clipping, minibatch sizes, learning rate selection, periodic target update frequency, replay buffer size, prioritised replay (sample important transitions with higher probability), double DQN (use online network to select action and target network to evaluate to reduce overestimation), dueling networks (separate value and advantage streams). Refer to related topics: Value-function approximation, Deadly triad, Double DQN, Prioritised replay and dueling.

Diagrams to draw in an exam (describe what to draw):

  • Draw a small block diagram with two neural networks side-by-side labelled Qθ (online) and Qθ⁻ (target). Show input s and s' going into both; show action a chosen by ε-greedy from Qθ; show transition stored in replay memory; show minibatch sampled feeding into Qθ to compute Q(s,a; θ) and into Qθ⁻ to compute max_{a'} Q(s',a'; θ⁻); show target y computed and loss L computed and gradients backpropagated into Qθ only.

Formulas

y = r + γ · max_{a'} Q(s', a'; θ⁻) — y is the bootstrap target; r is reward (unit: same as reward units, usually unitless); γ is discount factor (unitless); Q is action-value (same units as reward). Applies when s' is non-terminal; if terminal then y = r. For Double DQN (non-terminal), use y = r + γ · Q(s', argmax_{a'} Q(s', a'; θ), θ⁻) to reduce overestimation.

L(θ) = E_{(s,a,r,s')∼D}[ (y - Q(s,a; θ))^2 ] — mean-squared error loss; θ are network parameters (unitless); D is replay distribution (empirical); applies during minibatch SGD updates. Huber loss with threshold κ=1: Huber_κ(δ) = 0.5·δ^2 if |δ| ≤ κ; else κ·(|δ| − 0.5·κ); use L(θ) = E[Huber_κ(y − Q(s,a; θ))].

∇_θ L(θ) = E_{(s,a,r,s')∼D}[ -2 · (y - Q(s,a; θ)) · ∇_θ Q(s,a; θ) ] — gradient of MSE; if using 1/2 factor then the 2 cancels.

Q-update (stochastic gradient step): θ ← θ + α · (y - Q(s,a; θ)) · ∇_θ Q(s,a; θ) — α is learning rate (unitless). Applies per-gradient-step with minibatch.

ε-greedy policy: with probability ε choose random a ∈ A; else a = argmax_a Q(s,a; θ) — ε is exploration probability (unitless). Applies during data collection.

Target network update (hard): θ⁻ ← θ every C steps — C is target update period (unitless count). Alternatively soft update: θ⁻ ← τ θ + (1-τ) θ⁻ with τ ∈ (0,1).

Note: Q, y, r typically dimensionless in RL software (reward units). Verify reward units when modelling physical systems.

Worked examples

  1. Theory derivation (exam-style).

Question: Derive the gradient ∇_θ L(θ) for DQN loss L(θ) = E[(y - Q(s,a; θ))^2] where y is treated constant (depends on θ⁻ only).

Answer (model solution): Let δ(θ) = y - Q(s,a; θ). Then L(θ) = E[δ(θ)^2]. dL/dθ = E[2 δ(θ) · dδ/dθ] = E[2 δ(θ) · ( -∇_θ Q(s,a; θ) )] = E[ -2 (y - Q(s,a; θ)) ∇_θ Q(s,a; θ) ]. If loss includes 1/2 factor, gradient becomes E[ - (y - Q) ∇_θ Q ]. During SGD we use θ ← θ + α (y - Q) ∇_θ Q.

  1. Numerical hand-computation (short numerical problem).

Given a minibatch of one sample with s, a, r = 1.0, γ = 0.9, Q(s',·; θ⁻) returns [2.0, 1.5] so max = 2.0. Online Q(s,a; θ) = 1.2 for the taken action. The network outputs for that action depend on parameters; suppose ∇_θ Q(s,a; θ) (dot product with parameter step) along direction Δθ has magnitude vector g = [0.5, -0.2] (two-parameter example); learning rate α = 0.01. Compute y, loss, gradient step numerically.

Steps:

  • y = r + γ max Q(s',·; θ⁻) = 1.0 + 0.9*2.0 = 2.8.
  • δ = y - Q(s,a; θ) = 2.8 - 1.2 = 1.6.
  • Loss L = δ^2 = 2.56 (or 1/2 δ^2 = 1.28 if using 1/2 factor).
  • Gradient (no 1/2) ∇_θ L = -2 · δ · g = -2 * 1.6 * [0.5, -0.2] = -3.2 * [0.5, -0.2] = [-1.6, 0.64].
  • SGD update θ ← θ - (η) ∇_θ L with η=0.01 gives Δθ = -0.01 * ∇_θ L = -0.01 * [-1.6, 0.64] = [0.016, -0.0064] so θ increases first param by 0.016 and decreases second by 0.0064. (If using the alternate sign convention shown earlier, update formula may be θ ← θ + α (y-Q) g giving same numeric result.)

Final answer: y=2.8, loss=2.56, parameter change [0.016, -0.0064].

  1. Minimal runnable Python example (toy MLP with numpy): trains one SGD step on a toy transition. Copy-paste runnable in standard Python 3 environment. (This is minimal and illustrative; does not use a full RL environment.)
# Minimal DQN one-step update using numpy
import numpy as np

# Toy network: linear Q(s,a) = W · φ(s) for two actions (no bias)
# State feature φ(s) is a fixed vector
phi = np.array([1.0, 0.5])        # example feature vector (2-dim)
W = np.array([[0.6, -0.1],        # shape (num_actions, feature_dim)
              [0.2,  0.4]])
# parameters W flattened to vector theta if needed

action = 0
r = 1.0
gamma = 0.9
# target network: copy of W (held fixed)
W_target = W.copy()
# suppose next state phi' leads to Q-targets [2.0, 1.5]
Q_next = np.array([2.0, 1.5])   # e.g., given target-network outputs for next state
# compute target y
y = r + gamma * np.max(Q_next)
# current Q for (s,a)
Q_sa = W[action].dot(phi)
# TD error
delta = y - Q_sa
# learning rate
alpha = 0.01
# gradient of Q_sa wrt W[action] is phi
grad_Wa = -2 * delta * phi       # gradient of loss L = (y-Q)^2 w.r.t W[action]
# update only the row corresponding to action
W[action] = W[action] - alpha * grad_Wa

print('y=', round(y,4))
print('Q_sa_old=', round(Q_sa,4))
print('delta=', round(delta,4))
print('W_new=', np.round(W,4))

Sample output (exact):

y= 2.8 Q_sa_old= 0.55 delta= 2.25 W_new= [[ 0.645 -0.0775] [ 0.2 0.4 ]]

Explanation: This shows one SGD update on a simple linear Q-network. Real DQN uses deeper networks, minibatches, replay memory and target networks updated less frequently.

Common mistakes

  • Using sequential (non-shuffled) samples for updates — this breaks the i.i.d. assumption and makes training unstable; that is why replay is used.
  • Not handling terminal transitions: when s' is terminal, the target should be y = r (not r + γ max Q).
  • Mixing sign conventions in gradient updates; be consistent whether you write θ ← θ − η ∇L or θ ← θ + α (y − Q) ∇Q and keep the sign correct.
  • Expecting immediate high performance: DQN often needs many environment steps and hyperparameter tuning.

For your exam

Question types you will see: definitions (define DQN, experience replay, target network), short notes (explain why target network helps), derivations (derive gradient of DQN loss), diagrams (draw network + replay buffer), numericals (compute single-step update), small programs or pseudo-code (DQN training loop).

What a full-marks answer includes:

  • Clear definitions of Q-network, target network, experience replay, and the DQN loss.
  • Assumptions used (bounded rewards, γ<1, replay buffer approximates IID sampling).
  • Correct derivation of gradient steps with signs and factor 1/2 accounted for.
  • Correct handling of terminal states in the bootstrap target.
  • A labelled diagram showing data flow between environment, replay, online network, and target network.

Quick check

  1. Why do we use a target network in DQN?
  2. Write the DQN bootstrap target y for a terminal and a non-terminal s'.
  3. Give one reason why experience replay helps training.

Answers: 1) To keep the bootstrap target fixed for several updates and reduce instability caused by moving targets; 2) Non-terminal: y = r + γ max_{a'} Q(s',a'; θ⁻); Terminal: y = r; 3) Replay breaks temporal correlations by sampling transitions i.i.d. and increases data efficiency.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?