◆ AI All-in-One

Level 3 In-Depth AI · Reinforcement Learning

Deep Q-Networks

Replace Q-learning's lookup table with a neural network, and stabilise it with experience replay and a target network. The 2013–2015 DeepMind breakthrough that learned dozens of Atari games from raw pixels.

Level
●●●●● Intermediate
Reading
13 min
To learn it well
1.5 hours to read, an afternoon to practise
↗ Plan a path here

Read first

Q-LearningNeural Networks

This leads to

—
The full path from zero — 18 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Reinforcement Learning: The Basics
  12. Linear Regression
  13. The Perceptron
  14. Markov Decision Processes
  15. Logistic Regression
  16. Value Functions and Bellman Equations
  17. Neural Networks
  18. Q-Learning
  19. Deep Q-Networks

Read them roughly in this order. See it on the concept map →

Why it matters

Q-Learning keeps one number for every state–action pair. That works for a 4 × 4 grid. It is hopeless for a video game, where the state is the screen. A single 84 × 84 greyscale frame with 256 shades has 2567056256^{7056} possible values, and almost every frame the agent sees is one it has never seen before. A table can't generalise: what it learned about one screen tells it nothing about a nearly identical one.

The Deep Q-Network (DQN) fixes this by replacing the table with a neural network that takes the state as input and outputs a Q-value for every action. Similar screens get similar values automatically. In 2013, and in a landmark Nature paper in 2015, DeepMind showed that a single DQN architecture, with the same hyperparameters, could learn to play 49 different Atari 2600 games from nothing but the pixels and the score. It reached the level of a professional human games tester on many of them. That result started the deep reinforcement learning era that led to AlphaGo, robotics in simulation, and the RL used to train today's language models (RLHF and Preference Optimization, Reasoning Models and Test-Time Compute).

Making it work took two engineering ideas, experience replay and a target network. Both are still standard.

The intuition

The naive idea is simple. Take the Q-learning update, which moves Q(s,a)Q(s, a) towards the target r+γmax⁡a′Q(s′,a′)r + \gamma \max_{a'} Q(s', a'), and treat it as a supervised regression problem. The network's output Q(s,a)Q(s, a) is the prediction, the target is the label, and Gradient Descent reduces the squared difference.

Done naively, this falls apart, for two reasons.

1. The training data is highly correlated. Consecutive frames of a game are nearly identical. Training on them in order is like studying for an exam by reading one page 500 times, then the next page 500 times. The network overfits to whatever it saw last and forgets the rest. Experience replay fixes this. Store every transition (s,a,r,s′,done)(s, a, r, s', \text{done}) in a large memory, the replay buffer. Train on small batches drawn at random from it. Each batch then mixes moments from many different times and situations, which is much closer to the independent samples that gradient descent expects. A bonus: every experience gets reused many times, which makes learning more data-efficient. Because Q-learning is off-policy, learning from old actions taken by an older version of the policy is perfectly legitimate.

2. The target moves. In supervised learning, labels stay fixed. Here the label r+γmax⁡a′Q(s′,a′)r + \gamma \max_{a'} Q(s', a') is computed by the same network you are updating. Each gradient step changes the targets too, like a dog chasing its own tail. Values can oscillate or spiral off to infinity. The target network fixes this. Keep a second, frozen copy of the network and use it only to compute targets. Every few thousand steps, copy the current weights into it. Between copies the targets hold still, so each stretch of training is an ordinary regression problem.

Environment CartPole, Atari, … store (s, a, r, s′, done) Replay buffer last 50,000 transitions random mini-batch of 64 transitions s′ of each Q-network θ input s → one Q per action trained every step Target network θ⁻ a frozen copy of θ used only to compute targets copy θ → θ⁻ every 500 steps act ε-greedily: argmaxₐ Q(s, a) loss = ( Q(s, a; θ) − [ r + γ maxₐ′ Q(s′, a′; θ⁻) ] )² prediction vs. TD target (a Huber loss is used in practice) ∇ loss
Fig. 1 DQN's training loop. The agent acts ε-greedily using the Q-network and stores every transition in the replay buffer. Training samples random mini-batches from the buffer. The Q-network predicts Q(s, a), the frozen target network supplies the TD target, and the gradient of the difference updates only the Q-network. Every so often its weights are copied into the target network.

Key idea DQN is Q-learning with a neural network instead of a table, plus two stabilisers. Experience replay breaks the correlations in the data. A target network holds the regression targets still. Without them, deep Q-learning usually diverges.

How it works

The network

The Q-network Q(s,a;θ)Q(s, a; \theta) has parameters θ\theta (all its weights). It takes a state and outputs one number per action. One forward pass therefore scores every action at once, and choosing the greedy action is just an argmax over the outputs. For CartPole the input is 4 numbers and there are 2 outputs. For Atari, the Nature DQN used:

  • Input: the last 4 frames, converted to greyscale and shrunk to 84 × 84, stacked into an 84 × 84 × 4 tensor. One frame doesn't show motion. Four do, which makes the state close enough to Markov (Markov Decision Processes).
  • Three convolutional layers (Convolutional Neural Networks): 32 filters of 8 × 8 with stride 4, 64 of 4 × 4 with stride 2, and 64 of 3 × 3 with stride 1.
  • A fully connected layer of 512 units, then one output per action (up to 18 joystick actions).

The loss

For a mini-batch of transitions (s,a,r,s′,d)(s, a, r, s', d) sampled from the buffer, where dd is 1 if s′s' is terminal and 0 otherwise, the TD target uses the target network's weights θ−\theta^-:

y=r+γ (1−d) max⁡a′Q(s′,a′;θ−)y = r + \gamma\, (1 - d)\, \max_{a'} Q(s', a'; \theta^-)

and the loss is the average squared error between prediction and target:

L(θ)=E(s,a,r,s′,d)∼D[(y−Q(s,a;θ))2]L(\theta) = \mathbb{E}_{(s,a,r,s',d) \sim \mathcal{D}} \Big[ \big( y - Q(s, a; \theta) \big)^2 \Big]

D\mathcal{D} is the replay buffer, and "∼D\sim \mathcal{D}" means "sampled at random from it". The factor (1−d)(1 - d) switches off the future term at the end of an episode. The gradient flows only through Q(s,a;θ)Q(s, a; \theta). The target yy is treated as a constant, which is why the code computes it under torch.no_grad().

In practice the squared error is usually replaced by the Huber loss, which is squared for small errors and linear for large ones. A single huge TD error then can't produce a huge gradient. (The Nature paper achieved a similar effect by clipping the error term to [−1,1][-1, 1].)

Worked example. CartPole gives reward 1 for every step the pole stays up, and γ=0.99\gamma = 0.99. Suppose for one sampled transition the network predicts Q(s,right)=40.0Q(s, \text{right}) = 40.0, the episode did not end, and the target network rates the next state's actions at 45.0 (left) and 42.0 (right). The target is y=1+0.99×45.0=45.55y = 1 + 0.99 \times 45.0 = 45.55. The error is 45.55−40.0=5.5545.55 - 40.0 = 5.55, so gradient descent pushes Q(s,right)Q(s, \text{right}) up. Note the scale. If the pole could stay up forever, the value would approach 1/(1−0.99)=1001 / (1 - 0.99) = 100. Values in CartPole live between 0 and 100.

The whole algorithm

  1. Initialise the Q-network θ\theta randomly, copy it to the target network θ−←θ\theta^- \leftarrow \theta, and create an empty replay buffer.
  2. At each step:
    • Choose an action ε-greedily from Q(s,⋅ ;θ)Q(s, \cdot\,; \theta), with ε\varepsilon decaying from 1.0 to a small value.
    • Take it. Store (s,a,r,s′,d)(s, a, r, s', d) in the buffer. When the buffer is full, the oldest transitions are dropped.
    • Sample a random mini-batch, compute targets with θ−\theta^-, and take one gradient step on L(θ)L(\theta).
    • Every CC steps, set θ−←θ\theta^- \leftarrow \theta.

The Nature DQN used a replay buffer of 1 million transitions, mini-batches of 32, C=10,000C = 10{,}000 updates, γ=0.99\gamma = 0.99, and ε\varepsilon annealed from 1.0 to 0.1 over the first million frames. It also clipped all rewards to [−1,+1][-1, +1] so that one learning rate would suit every game, and it trained for 50 million frames per game.

In code

A complete DQN in PyTorch on CartPole: balance a pole on a cart by pushing left or right. The physics is the classic cart-pole model, written out by hand with the same constants Gymnasium uses, so no extra libraries are needed. The episode ends if the pole tilts past 12° or the cart leaves the track, and it is cut off at 500 steps. Training takes about a minute on a laptop CPU.

import math, random
from collections import deque
import torch, torch.nn as nn

class CartPole:
    """The classic cart-pole physics (same constants as Gymnasium's CartPole-v1)."""
    def reset(self):
        self.s = [random.uniform(-0.05, 0.05) for _ in range(4)]   # x, x_dot, theta, theta_dot
        self.t = 0
        return list(self.s)
    def step(self, action):
        x, x_dot, th, th_dot = self.s
        force = 10.0 if action == 1 else -10.0
        cos, sin = math.cos(th), math.sin(th)
        temp = (force + 0.05 * th_dot**2 * sin) / 1.1             # pole mass 0.1, total mass 1.1
        th_acc = (9.8 * sin - cos * temp) / (0.5 * (4/3 - 0.1 * cos**2 / 1.1))
        x_acc = temp - 0.05 * th_acc * cos / 1.1
        x, x_dot = x + 0.02 * x_dot, x_dot + 0.02 * x_acc          # Euler step, 0.02 s
        th, th_dot = th + 0.02 * th_dot, th_dot + 0.02 * th_acc
        self.s, self.t = [x, x_dot, th, th_dot], self.t + 1
        fell = abs(x) > 2.4 or abs(th) > 12 * math.pi / 180
        return list(self.s), 1.0, fell, self.t >= 500               # state, reward, terminated, truncated

random.seed(0); torch.manual_seed(0)
q_net = nn.Sequential(nn.Linear(4, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 2))
target_net = nn.Sequential(nn.Linear(4, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 2))
target_net.load_state_dict(q_net.state_dict())
opt = torch.optim.Adam(q_net.parameters(), lr=5e-4)
buffer, gamma, steps = deque(maxlen=50_000), 0.99, 0
env = CartPole()

history = []
for episode in range(1, 501):
    s, done, total = env.reset(), False, 0
    while not done:
        eps = max(0.05, 1.0 - steps / 5_000)                      # explore a lot, then less
        if random.random() < eps: a = random.randrange(2)
        else:
            with torch.no_grad(): a = q_net(torch.tensor(s)).argmax().item()
        s2, r, term, trunc = env.step(a)
        buffer.append((s, a, r, s2, term))                         # store the transition
        s, done, total, steps = s2, term or trunc, total + r, steps + 1

        if len(buffer) >= 1000:                                    # learn from a random mini-batch
            S, A, R, S2, T = map(torch.tensor, zip(*random.sample(buffer, 64)))
            q = q_net(S).gather(1, A.unsqueeze(1)).squeeze(1)      # Q(s, a) for the actions taken
            with torch.no_grad():
                target = R + gamma * target_net(S2).max(1).values * (1 - T.float())
            loss = nn.functional.smooth_l1_loss(q, target)
            opt.zero_grad(); loss.backward(); opt.step()
        if steps % 500 == 0:                                       # refresh the frozen copy
            target_net.load_state_dict(q_net.state_dict())
    history.append(total)
    if episode % 50 == 0:
        print(f"episodes {episode-49:3d}-{episode:3d}: average {sum(history[-50:])/50:5.1f} steps balanced")

# episodes   1- 50: average  22.6 steps balanced
# episodes  51-100: average  17.4 steps balanced
# episodes 101-150: average 151.3 steps balanced
# episodes 151-200: average 102.4 steps balanced
# episodes 201-250: average  60.3 steps balanced
# episodes 251-300: average  80.9 steps balanced
# episodes 301-350: average 151.8 steps balanced
# episodes 351-400: average 244.2 steps balanced
# episodes 401-450: average 209.1 steps balanced
# episodes 451-500: average 416.0 steps balanced

The run is a realistic picture of deep RL. Learning is real (from about 20 steps to over 400) but bumpy. Performance rose, collapsed, then recovered.

0 100 200 300 400 500 0 100 200 300 400 500 500 episode limit average of last 25 grey single episodes episode steps the pole stayed up
Fig. 2 The learning curve from the code above. Grey: steps balanced in each episode. Blue: the average of the last 25 episodes. Performance climbs, collapses around episode 150–250, and recovers to near the 500-step limit. Instability like this is normal for DQN.

Each line of the training step maps to the algorithm. random.sample(buffer, 64) is experience replay. target_net(S2).max(1).values is max⁡a′Q(s′,a′;θ−)\max_{a'} Q(s', a'; \theta^-). * (1 - T.float()) is the (1−d)(1 - d) that ends the return at a terminal state. Note that only term is stored, not trunc. When the 500-step time limit cuts an episode off, the pole is still up and the future still counts.

The next step: Gymnasium and Stable-Baselines3

With Gymnasium and the Stable-Baselines3 library, the same experiment, with many extra refinements, is a few lines. This needs pip install gymnasium stable-baselines3, so it isn't run here:

import gymnasium as gym
from stable_baselines3 import DQN

env = gym.make("CartPole-v1")
model = DQN("MlpPolicy", env, learning_rate=5e-4, buffer_size=50_000,
            target_update_interval=500, exploration_fraction=0.1, verbose=1)
model.learn(total_timesteps=100_000)

obs, info = env.reset(seed=0)
action, _ = model.predict(obs, deterministic=True)    # greedy action from the trained Q-network

For Atari, swap in an Atari environment and "CnnPolicy", which builds the convolutional network for you.

Common pitfalls

  • Treating time-outs as deaths. If you store done = terminated or truncated, the agent learns that surviving 500 steps leads to zero future reward, which is false. Store only true terminations for the target.
  • Forgetting no_grad on the target. If gradients flow into the target term, you are no longer doing Q-learning, and training usually becomes unstable.
  • Learning before the buffer has data. Training on the first few dozen transitions overfits them badly. Wait until the buffer holds a few thousand (the code waits for 1,000).
  • Reading too much into one run. Deep RL results vary hugely between random seeds. Change random.seed(0) to another number and the curve above will look different. Published comparisons use many seeds and report averages with spread.
  • Catastrophic collapse. As in the curve above, performance can crash after looking solved. Keep evaluation checkpoints and save the best model, not just the last.
  • Overestimation. The max over noisy Q-values is biased upwards (see Q-Learning), and with a network the bias can compound. Double DQN, below, is a one-line fix.

Watch out DQN only works with a small, discrete set of actions, because it needs max⁡aQ(s,a)\max_a Q(s, a) over all of them. For continuous actions, like a robot's joint torques, use policy-based methods (Policy Gradients, Actor-Critic Methods, Proximal Policy Optimization) or actor-critic methods built for continuous control such as DDPG, TD3 and SAC.

Variations

Six improvements followed quickly, and the Rainbow agent (Hessel et al., 2017) showed that combining them works far better than any one alone:

  • Double DQN (van Hasselt, Guez & Silver, 2015): let the online network choose the next action and the target network score it, y=r+γ Q(s′,arg⁡max⁡a′Q(s′,a′;θ);θ−)y = r + \gamma\, Q\big(s', \arg\max_{a'} Q(s', a'; \theta); \theta^-\big). This greatly reduces overestimation.
  • Dueling networks (Wang et al., 2016): split the network's head into a state value V(s)V(s) and per-action advantages A(s,a)A(s, a), then recombine them. The network learns which states are good without having to learn the effect of every action in each.
  • Prioritized experience replay (Schaul et al., 2015): replay surprising transitions, those with a large TD error, more often.
  • Multi-step returns: use nn real rewards before bootstrapping, as in n-step methods.
  • Distributional RL (C51; Bellemare, Dabney & Munos, 2017): learn the whole distribution of returns, not just its mean.
  • Noisy networks (Fortunato et al., 2017): learned noise in the weights replaces ε-greedy exploration.

Later DeepMind agents pushed value-based deep RL further. Agent57 (2020) was the first to score above the human baseline on all 57 games of the standard Atari benchmark. Today's approaches to the same problems include policy-gradient methods (Proximal Policy Optimization) and model-based agents (Model-Based RL and World Models).

A bit of history

The idea of combining Q-learning with neural networks is old. Long-Ji Lin introduced experience replay in the early 1990s, and Gerald Tesauro's TD-Gammon (1992) had already shown a neural network learning values by TD. But for two decades, attempts to train deep networks this way were notoriously unstable. In December 2013, Volodymyr Mnih and colleagues at DeepMind posted "Playing Atari with Deep Reinforcement Learning". A single network learned seven Atari games from pixels and beat a human expert on three of them (Breakout, Enduro and Pong). Google acquired DeepMind in early 2014. In February 2015 the expanded version, "Human-level control through deep reinforcement learning", appeared in Nature. It added the target network and tested on 49 games. With one architecture and one set of hyperparameters, DQN reached at least 75% of a professional games tester's score on 29 of them. DeepMind's footage of DQN discovering that it could tunnel through the side of the wall in Breakout and bounce the ball across the top became one of the iconic images of the deep-learning boom.

Try it

  1. Delete the target network: compute the target with q_net instead of target_net. Run a few seeds. Is training more or less stable?
  2. Shrink the replay buffer to maxlen=1000 and then to maxlen=64, so that it holds only recent experience. What happens to learning?
  3. Implement Double DQN by changing only the target line: choose a2 = q_net(S2).argmax(1, keepdim=True), then score it with target_net(S2).gather(1, a2). Compare curves over three seeds.

Hint for 2: a tiny buffer brings back the correlated, ever-changing data that experience replay was designed to remove.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You train a Q-network on transitions in the order they happen, and it keeps forgetting earlier parts of the game. Which DQN ingredient addresses this?

  2. Why does DQN compute the TD target with a separate, periodically copied target network?

  3. In CartPole (reward 1 per step, γ = 0.99) the network predicts Q(s, right) = 40, the episode continues, and the target network rates the next state's actions at 45 and 42. What is the TD target?

  4. You store done = terminated or truncated in the replay buffer. What does the agent wrongly learn?

  5. You want DQN to control a robot arm's continuous joint torques. What is the problem?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face Deep RL Course

Hugging Face · Intermediate · Free

A hands-on deep reinforcement learning course from Q-learning to PPO. You train agents in games.

Tutorial

Reinforcement Learning (DQN) Tutorial

PyTorch · Intermediate · Free

The official PyTorch tutorial: a DQN with replay memory and a target network that learns CartPole from Gymnasium.

Paper

Deep Reinforcement Learning with Double Q-learning

van Hasselt, Guez & Silver · 2015 · Advanced · Free

Shows that DQN overestimates action values and fixes it by letting the online network choose the action and the target network score it.

Tool

CleanRL

Shengyi Huang et al. · Intermediate · Free

Single-file implementations of DQN, PPO, SAC and others, each a few hundred readable lines. Ideal for seeing every detail of a real algorithm in one place.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/dqn.md