Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 1

Lab: From a Q-Table to a Deep Q-Network

Trace value-based RL from tabular Bellman updates to Deep Q-Networks (DQN), implementing experience replay memory buffers, target networks for training stability, and epsilon-greedy annealing in continuous state spaces.

Contentsand lesson path

On this page

  1. Value-Based Reinforcement Learning: Tabular Q-Learning to DQN

Lessons of Reinforcement Learning Foundations

What you will learn

  • Implement tabular Q-learning on a small Gymnasium environment, extend it to a deep Q-network with experience replay and a target network, and report mean episode return across several seeds.

Prerequisites: Deep Learning Fundamentals

01. Value-Based Reinforcement Learning: Tabular Q-Learning to DQN

In discrete, small-scale state spaces (such as simple gridworlds), an agent can maintain an exact lookup table—a Q-Table storing a numerical expected return $Q(s, a)$ for every conceivable state-action pair $(s, a) \in \mathcal{S} \times \mathcal{A}$. However, real-world control systems operate in continuous, high-dimensional observation spaces (such as robotic joint angles, continuous velocities, or raw Atari pixel rasters). Discretizing a 10-dimensional continuous state vector into 100 bins per dimension requires $100^{10} = 10^{20}$ table entries, an insurmountable curse of dimensionality. Deep Q-Networks (DQN) bridge this gap by replacing the discrete lookup table with a deep neural network function approximator $Q_\theta(s, a) \approx Q^*(s, a)$.

  • Tabular Q-Learning and Temporal Difference (TD) Updates: Watkins (1989) formulated tabular Q-learning as an off-policy temporal difference algorithm. Upon observing transition $(s, a, r, s')$, the agent updates its estimate using the Bellman optimality operator:

$$Q(s, a) \leftarrow Q(s, a) + \alpha \cdot \left[ \underbrace{r + \gamma \max_{a'} Q(s', a')}_{\text{TD Target}} - Q(s, a) \right]$$

The quantity $\delta_t = r + \gamma \max_{a'} Q(s', a') - Q(s, a)$ is the Temporal Difference (TD) Error. Tabular Q-learning is provably guaranteed to converge to the optimal action-values $Q^*$ under standard Robbins-Monro learning rate decay schedules.

  • The "Deadly Triad" of Reinforcement Learning: Sutton & Barto identified that combining three core elements creates severe instability and risk of divergence:

    1. Function Approximation: Using non-linear neural networks rather than lookup tables.
    2. Bootstrapping: Updating value estimates from subsequent downstream estimates ($r + \gamma \max Q(s', a')$) rather than complete Monte Carlo rollouts.
    3. Off-Policy Learning: Training on data collected under an exploratory behavior policy (e.g., $\epsilon$-greedy) while learning the optimal target policy.
  • Deep Q-Networks (DQN): The Two Foundational Stabilizers: Mnih et al. (2015, DeepMind) stabilized deep neural function approximation through two architectural innovations:

    • 1. Experience Replay Memory Buffer ($\mathcal{D}$): In sequential environments, consecutive transitions $(s_t, a_t, r_t, s_{t+1})$ are strongly autocorrelated, violating the independent and identically distributed (i.i.d.) assumption foundational to stochastic gradient descent. DQN stores transitions in a large ring buffer $\mathcal{D}$ of capacity $N$ (e.g., $10^5$ to $10^6$ steps). Mini-batches of transitions are sampled uniformly at random during training, breaking temporal autocorrelation and preventing catastrophic forgetting of rarely visited state regimes.

    • 2. Decoupled Target Network ($Q_{\theta^-}$): If a single network parameterized by $\theta$ is used to compute both the prediction $Q_\theta(s, a)$ and the target $r + \gamma \max_{a'} Q_\theta(s', a')$, every parameter update shifts the target, causing oscillations and runaway gradient explosion (analogous to a dog chasing its own tail). DQN introduces a separate Target Network parameterized by frozen weights $\theta^-$. The loss function minimizes squared TD error against fixed target weights:

$$\mathcal{L}(\theta) = \mathbb{E}{(s, a, r, s') \sim \mathcal{D}}\left[\left( r + \gamma \max{a'} Q_{\theta^-}(s', a') - Q_\theta(s, a) \right)^2\right]$$

The target parameters $\theta^-$ are held fixed and updated periodically (e.g., every 1,000 steps via hard copy $\theta^- \leftarrow \theta$, or continuously via soft Polyak averaging $\theta^- \leftarrow \tau \theta + (1 - \tau) \theta^-$ with $\tau \approx 0.005$).

  • Advanced DQN Extensions (Double DQN & Dueling DQN):

    • Double DQN (DDQN): Standard DQN suffers from severe maximization bias because the $\max_{a'} Q(s', a')$ operator uses the same noisy values to both select and evaluate actions. Double DQN decouples selection from evaluation: action selection is performed by online network $\theta$, while action evaluation is scored by target network $\theta^-$: $Y_{\text{DDQN}} = r + \gamma Q_{\theta^-}(s', \arg\max_{a'} Q_\theta(s', a'))$.
    • Dueling DQN: Decomposes the Q-network architecture into two separate functional streams sharing early representation layers: a scalar State Value stream $V_\theta(s)$ and an Advantage stream $A_\theta(s, a)$, combining them as $Q(s, a) = V(s) + (A(s, a) - \frac{1}{|\mathcal{A}|} \sum_{a'} A(s, a'))$. This enables the network to learn which states are fundamentally valuable without having to learn the effect of every action in every state.
  • Hyperparameter Sensitivity and Seed Variance: Deep RL algorithms exhibit significant performance variance across different random seed initializations due to stochastic exploration trajectories and non-convex gradient dynamics. Best engineering practices require evaluating DQN performance across at least 5 to 10 independent random seeds, plotting the mean reward curve alongside 95% bootstrap confidence intervals.

  • Prioritized Experience Replay (PER - Sampling by Surprise): Uniform random sampling from the replay buffer treats all transitions identically, wasting immense compute on routine transitions whose TD error is already near zero. Schaul et al. (2015) introduced Prioritized Experience Replay (PER), assigning sampling probabilities proportional to absolute TD error magnitude: $P(i) = \frac{|\delta_i|^\alpha}{\sum_k |\delta_k|^\alpha}$. Because non-uniform sampling skews the expected distribution of gradient updates, PER introduces importance sampling weights: $w_i = (N \cdot P(i))^{-\beta}$, scaling gradients down for over-sampled high-priority transitions and restoring unbiased gradient expectations.

  • Huber Loss for Gradient Stabilization: Standard Mean Squared Error loss $\mathcal{L} = \frac{1}{2} \delta^2$ yields linear gradients with respect to TD error $\frac{\partial \mathcal{L}}{\partial \delta} = \delta$. When an unexpected outlier reward or severe target step occurs, TD error explodes, producing destabilizingly large gradient updates that destroy pre-trained network representations. Deep Q-learning employs Huber Loss (Smooth L1): behaving quadratically for small errors $|\delta| \le 1$ to ensure smooth convergence near the optimum, but transitioning to linear penalties for $|\delta| > 1$, effectively clipping gradient magnitudes to $[-1, 1]$ and preventing network destabilization.

  • Synthesizing Enhancements: The Rainbow DQN Benchmark: Hessel et al. (2018) unified six orthogonal improvements into Rainbow DQN: combining Double DQN, Dueling architectures, Prioritized Replay, Multi-step bootstrapped returns ($n$-step returns $G_{t:t+n} = \sum_{k=0}^{n-1} \gamma^k r_{t+k+1} + \gamma^n \max Q$), Distributional RL (predicting full return probability distributions via C51), and Noisy Networks (parametric exploration noise). Extensive ablation studies demonstrated that these individual enhancements compound synergistically, setting landmark sample-efficiency records.

  • Observation Normalization and Frame Stacking in Sensory Control: In complex visual and continuous robotic environments, individual sensor channels vary across divergent physical units. Production DQN pipelines implement continuous observation normalization, updating running empirical mean and standard deviation vectors online. Furthermore, to overcome partial observability in video rasters where a single static image cannot convey velocity or momentum, pipelines utilize frame stacking—concatenating the 4 most recent consecutive environment frames into a single unified input tensor, restoring velocity information to the Markov state.

Python · tabular_td_update.py Tabular Q-learning step and TD error derivation
import numpy as np

np.random.seed(42)
alpha = 0.1
gamma = 0.95
q_table = np.zeros((4, 2))
q_table[0, 1] = 1.5

# Step transition: state 0, action 1 -> reward 1.0, next state 1
state, action, reward, next_state = 0, 1, 1.0, 1
next_max_q = 2.0  # max_a Q(next_state, a)
td_target = reward + gamma * next_max_q
td_error = td_target - q_table[state, action]
q_table[state, action] += alpha * td_error

print("=== TABULAR Q-LEARNING STEP AUDIT ===")
print(f"TD Target: {td_target:.2f}")
print(f"TD Error:  {td_error:.4f}")
print(f"Updated Q(0, 1): {q_table[0, 1]:.4f}")
Terminal · python tabular_td_update.py · Expected output
=== TABULAR Q-LEARNING STEP AUDIT ===
TD Target: 2.90
TD Error:  1.4000
Updated Q(0, 1): 1.6400
Practice check · 2 questions

Check Your Understanding

Review key concepts and verify your understanding with these practice questions.

Q1. What primary role does the experience replay memory buffer serve in Deep Q-Networks?
Q2. Why does DQN decouple the target network weights from the online network weights?
Practice only: not graded, not saved, not evidence.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check