Search

Search papers and lessons

Deep Q-Network

Level 4 · 10 min read

A deep Q-network replaces the Q-learning table with a neural network, and stabilises training with a replay buffer and a slowly updated target network.

On this page

  • Colour = topic mix
  • Reinforcement learning
  • Probability
  • Linear algebra
  • Neural network basics
  • Stochastic processes
  • Discrete math
  • Sign in to see your progress

TL;DR

A deep Q-network, or DQN, is Q-learning where the table of action values is replaced by a neural network. The network takes a state and outputs one value per action, so it can handle states too numerous to tabulate, such as raw screen pixels. Naive training of such a network is unstable, so DQN adds two things: a replay buffer that breaks up the correlation between consecutive samples, and a target network that holds the regression target still for many updates.

Where you'll see it: the 2015 Atari agent that learned dozens of games from pixels, and the template for later value-based agents in games, robot control and recommendation.

Intuition

Q-learning keeps one number per state-action pair. That works for a maze with 25 cells. It does not work for a game whose screen has more possible images than there are atoms in the room you are in. The fix is to stop storing the numbers and instead learn a function that produces them. A neural network can take the screen as input and output a score for each joystick action. Nearby screens get similar scores, so what it learns about one situation carries over to similar ones.

The trouble is that the thing being learned keeps moving. In supervised learning the targets are fixed labels. Here, the target for a state depends on the network's own estimate of the next state, and that estimate changes after every update. The network is chasing a target that shifts whenever it moves. Two consecutive frames of a game are also nearly identical, so the training data is highly correlated, which makes gradient steps noisy and biased in one direction.

DQN handles both problems with simple machinery:

  • A replay buffer stores recent transitions and trains on random samples from it, so each minibatch mixes different moments of play. See experience replay.
  • A target network is a copy of the Q-network whose weights are held fixed and refreshed only every few thousand steps. Targets come from this copy, so they stop moving with every step.
flowchart LR
  A["Agent acts with epsilon-greedy policy"] --> B["Store transition in replay buffer"]
  B --> C["Sample random minibatch"]
  C --> D["Compute targets with frozen target network"]
  D --> E["Gradient step on online network"]
  E --> F["Copy weights to target network every C steps"]
  F --> D
  E --> A

The math

Setup

The agent sees a state StS_t and picks an action AtA_t from a finite set A\mathcal{A}. It receives reward Rt+1R_{t+1} and next state St+1S_{t+1}, and the goal is to maximise the discounted return with discount factor γ∈[0,1)\gamma \in [0, 1). The optimal action-value function q∗(s,a)q^*(s, a) is the expected return from taking aa in ss and then acting optimally. Q-learning estimates it with an update rule. DQN estimates it with a function approximator Q(s,a;θ)Q(s, a; \theta), where θ\theta is the vector of network weights.

The loss

For a stored transition (s,a,r,s′,done)(s, a, r, s', \text{done}), the target is

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

where θ−\theta^- are the weights of the target network and done\text{done} is 1 if the episode ended. The loss is the squared gap between the prediction and the target, averaged over a minibatch BB:

L(θ)=1∣B∣∑(s,a,r,s′,done)∈B(y−Q(s,a;θ))2.L(\theta) = \frac{1}{|B|} \sum_{(s,a,r,s',\text{done}) \in B} \Big( y - Q(s, a; \theta) \Big)^2.

Only the online weights θ\theta receive gradients. The target is treated as a constant. The 2015 paper also clipped the error term δ=y−Q(s,a;θ)\delta = y - Q(s,a;\theta) to the interval [−1,1][-1, 1] inside the update, so that a single huge error cannot dominate a step. (This is equivalent to using a Huber loss, which is quadratic for small errors and linear for large ones.) The gradient with respect to a weight, per transition and before clipping, is

∂L∂θ=−2 δ ∂Q(s,a;θ)∂θ,\frac{\partial L}{\partial \theta} = -2 \, \delta \, \frac{\partial Q(s,a;\theta)}{\partial \theta},

and in practice the δ\delta in this expression is the clipped one.

which is backpropagated through the network, the same way as in any feedforward network trained with stochastic gradient descent.

Exploration and the update schedule

The agent acts ε\varepsilon-greedily: with probability ε\varepsilon it picks a random action, otherwise the action with the largest Q(s,a;θ)Q(s, a; \theta). The value of ε\varepsilon is annealed from near 1 down to a small value over the first part of training. The online network is updated every few agent steps, and every CC steps the target weights are overwritten: θ−←θ\theta^- \leftarrow \theta.

Input for images

For Atari, the raw frame is converted to grayscale and downsampled to 84×8484 \times 84. The network input stacks the last four frames, so a single input carries motion. The first layers are convolutional, and the final layer is linear with one output per action.

Worked examples

Example
One update with a linear Q-function

To keep the arithmetic visible, use a linear approximator with one weight per action: Q(s,a;θ)=θa xQ(s, a; \theta) = \theta_a \, x, where xx is a scalar feature of the state. Take γ=0.9\gamma = 0.9, learning rate α=0.1\alpha = 0.1, and the transition: state feature x=2x = 2, action left, reward r=0r = 0, next feature x′=1x' = 1, not terminal. The weights are θleft=0.5\theta_{\text{left}} = 0.5 and θright=1.0\theta_{\text{right}} = 1.0 online, and θleft−=0.5\theta^-_{\text{left}} = 0.5 and θright−=1.5\theta^-_{\text{right}} = 1.5 in the target network.

  1. Prediction: Q(s,left)=0.5×2=1.0Q(s, \text{left}) = 0.5 \times 2 = 1.0.
  2. Target uses the target network at x′=1x' = 1: the values are 0.5×1=0.50.5 \times 1 = 0.5 for left and 1.5×1=1.51.5 \times 1 = 1.5 for right. Maximum is 1.51.5, so y=0+0.9×1.5=1.35y = 0 + 0.9 \times 1.5 = 1.35.
  3. Error: δ=y−Q=1.35−1.0=0.35\delta = y - Q = 1.35 - 1.0 = 0.35. It is within [−1,1][-1, 1], so no clipping.
  4. Gradient for θleft\theta_{\text{left}}: −2 δ x=−2×0.35×2=−1.4-2 \, \delta \, x = -2 \times 0.35 \times 2 = -1.4.
  5. Step: θleft←0.5−0.1×(−1.4)=0.64\theta_{\text{left}} \leftarrow 0.5 - 0.1 \times (-1.4) = 0.64.
  6. New prediction: Q(s,left)=0.64×2=1.28Q(s, \text{left}) = 0.64 \times 2 = 1.28.

The estimate moved from 1.0 to 1.28, toward the target 1.35. It covered 0.28 of the 0.35 gap. The step size here is α×2x2=0.8\alpha \times 2 x^2 = 0.8 of the error, because this linear model is very sensitive to xx. With a deep network the same logic holds, but the step is spread across millions of weights.

Example
A minibatch of three transitions, one of them terminal

Use γ=0.99\gamma = 0.99. Three transitions come out of the replay buffer, each with the target network's maximum next-state value already computed.

TransitionRewardDoneTarget max next valueTarget yyPredictionError δ\deltaClipped δ\delta
11no101+0.99×10=10.91 + 0.99 \times 10 = 10.99.51.41.0
20yes7000.5−0.5-0.5−0.5-0.5
31no41+0.99×4=4.961 + 0.99 \times 4 = 4.964.00.960.96

Transition 2 is terminal, so the next-state value is dropped and the target is just the reward. Forgetting this flag is a common bug, because the agent then learns that the value of a finished episode is the value of a non-existent future.

Transition 1 has an error of 1.4 and is clipped to 1.0. Without clipping it would dominate the minibatch gradient. Capping the error limits how much any single transition can move the weights. The 2015 agent also clipped every reward to [−1,1][-1, 1], and together these let it use one learning rate across games with very different reward scales.

Tradeoffs and failure modes

DQN works for discrete actions and high-dimensional observations. It is a poor fit for continuous action spaces, where you would use an actor-critic method. Its main weaknesses are the following.

SituationWhat goes wrongBetter choice
Continuous control (joint torques)Taking a max over actions is intractableActor-critic methods such as DDPG or SAC
Rare, delayed rewardsReplay is full of uninformative transitionsPrioritised replay, reward shaping with care
Maximum over noisy estimatesQ-values are systematically overestimatedDouble DQN, which selects the action with the online network and evaluates it with the target network
Long training on one environmentLittle generalisation beyond the training setupModel-based methods, or training across varied environments
Huge replay memory of old dataStale transitions from an old policySmaller buffer, or on-policy methods
Epsilon anneals too fastAgent locks onto a poor action earlySlower schedule, or a count-based exploration bonus

The overestimation row is worth a moment. The max over noisy estimates is biased upward, and the target network does not remove that bias. Double DQN is a one-line change that reduces it.

History

Q-learning was introduced by Chris Watkins in his 1989 PhD thesis, with convergence proved for the tabular case by Watkins and Dayan in 1992. Experience replay was proposed by Long-Ji Lin in 1992 as a way to reuse past transitions in neural-network reinforcement learning. Gerald Tesauro's TD-Gammon, in the early 1990s, used a neural network with temporal-difference learning to reach expert backgammon play, but it did not use a replay buffer or a target network, and it did not scale to pixels.

Attempts to combine neural networks with Q-learning often diverged. The breakthrough came from Volodymyr Mnih and colleagues at DeepMind. Their 2013 workshop paper trained one convolutional network on Atari screens and reached strong play on several games. Their 2015 Nature paper extended the approach to 49 games with one set of hyperparameters and reported more than 75 percent of a professional human tester's score on 29 of them. The two stabilisers, replay and the target network, were what made the training reliable across games. Later work refined the method. Van Hasselt's Double DQN reduced overestimation, and Hessel and colleagues combined several such improvements in Rainbow in 2018.

Check yourself

QuestionName the two additions that DQN makes to plain Q-learning with a neural network, and say what problem each one solves.Show answer

The first is a replay buffer. It stores transitions and trains on random minibatches, which breaks the correlation between consecutive frames and reuses old data. The second is a target network, a copy of the Q-network with weights held fixed for many steps. It stops the regression target from moving every time the online weights change.

QuestionIn a DQN update, r=2r = 2, γ=0.5\gamma = 0.5, the target network's largest next-state value is 6, the episode does not end, and the prediction is Q(s,a)=1Q(s, a) = 1. What is the clipped error used in the update?Show answer

The target is y=2+0.5×6=5y = 2 + 0.5 \times 6 = 5. The raw error is δ=5−1=4\delta = 5 - 1 = 4. Clipping to [−1,1][-1, 1] gives δ=1\delta = 1. The clipped error is 1.

QuestionWhy are the targets computed with the frozen target network rather than the online network being trained?Show answer

If the same weights produced both the prediction and the target, each gradient step would move the target as well, and the network would chase its own moving estimate. This tends to make training diverge. Freezing the target weights for CC steps gives the online network a fixed regression problem for that stretch, and the target is refreshed only occasionally.

QuestionA team trains a DQN on a robot task. After two days the agent repeats one action forever, and its Q-values grow steadily without bound. Name two likely causes and a change for each.Show answer

One likely cause is exploration that stopped too early, so the agent never sampled the alternatives, and the fix is a slower epsilon schedule or a warm-up period with more random actions. Another is overestimation from the max over noisy values, which can make Q-values drift upward, and the fix is Double DQN or reward scaling so that targets stay in a sensible range. A third cause, worth checking, is a replay buffer dominated by the repeated action, which calls for a larger buffer or a warm-up period before updates begin.

Sources