Deep Q-network (DQN)

A deep Q-network trained live on CartPole and MountainCar: ε-greedy acting, experience replay, a target network, Double DQN, every Huber loss, and the Q function drawn as a map and a 3D surface.

Updated

  • Approximating Q with a neural network
  • Experience replay
  • Target networks
  • Double DQN and over-estimation
  • Why exploration is hard in MountainCar
y = r + γ · maxₐ′ Q_θ⁻(s′, a′)124 steps
Preparing the lab…

Intuition

Keep the pole up

CartPole: a pole stands on a cart, and each step you push the cart left or right. The episode ends when the pole tilts beyond 12° or the cart leaves the track; each step survived scores 1, up to 500 steps. The state is 4 continuous numbers (position, speed, angle, angular speed) — no table can list them, so a network has to estimate Q.

The three small labs below really train in a background thread of your browser (64 hidden units, learning rate 0.0005). On top is the current cart and pole; below, each bar is one episode's return and the dashed line is 475.

First 1000 stepsPreparing…
5000 stepsPreparing…
10,000 stepsPreparing…

Training starts only once the replay buffer holds 1000 transitions; the first gradient update happens at step 1000. Before that ε is still above 0.9 and the pushes are almost random: 47 episodes lasting 20.7 steps on average (10 to 55). At 5000 steps the last 20 episodes average 62.9, and at 10,000 steps 162.3.

Math

Loss and target

Online network QθQ_\theta, target network Qθ−Q_{\theta^-} (a copy of θ\theta taken every 500 updates). Draw 64 transitions from the replay buffer; each has the target

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

This is Double DQN: the online network picks the action, the target network values it. Plain DQN takes max⁡a′Qθ−(s′,a′)\max_{a'} Q_{\theta^-}(s', a') directly; the maximum of noisy estimates is biased upwards, so it over-estimates systematically. The loss is the Huber loss of Qθ(s,a)−yQ_\theta(s, a) - y (squared for errors below 1, absolute above, limiting the influence of outliers), with Adam and gradient-norm clipping at 10.

When an episode is cut off by the 500-step limit it does not count as terminal, and s′s' is still bootstrapped — the pole is still up; time simply ran out.

Exploration: ε shrinks over time

ε in ε-greedy falls linearly from 1 to 0.05 over the first 10,000 steps: at first almost every action is random, filling the buffer with varied situations; afterwards the agent mostly follows the network.

The learning curve: it learns, but unsteadily

Seed 1, default settings, average return of the last 20 episodes:

Steps500010,00020,00060,00070,00075,00080,000
Average return62.9162.3129.3363.25≥ 475418.5227

After 10,000 steps the return goes down rather than up, climbs again only after 60,000, first meets the bar at 70,000, then drops again. This is common with DQN: function approximation, bootstrapping (using its own estimates as targets) and off-policy learning together can make training itself unstable (Sutton and Barto's "deadly triad"). In practice people keep the best network seen so far, lower the learning rate, or enlarge the replay buffer.

How it is computed, with real numbers

Once the lab above has loaded, this panel works through the same formulas with its current numbers.

Experiment

Follow the lesson

Course

Lesson 1: a network that teaches itself to balance

5 steps · each one: set up and run → look → answer

  1. 1. Not learning yet

    Default CartPole, 500 steps. Look at "How it is computed" below.

    Why has there been no gradient update yet?
  2. 2. Learning

    Run to 10,000 steps and open "Returns".

    What has ε fallen to by now?
  3. 3. Going backwards

    Run to 20,000 steps.

    The return has fallen from 162.3 to 129.3. Isn't training always reducing the loss?
  4. 4. Meeting the bar

    Run to 70,000 steps (it takes a while).

    At 70,000 steps the last 20 episodes first average 475. Has it “learned”?
  5. 5. Switch off Double

    Change the target to plain DQN, run another 20,000 steps, and compare the target y in "How it is computed" with step 3.

    Why does plain DQN's target maxₐ′ Q_target(s′, a′) tend to be too high?

Try these settings

Exercises

Exercises

Exercise 1: don't explore for too long

When ε takes 50,000 steps to fall, the average return at 10,000 steps is only 31.6. Change the settings to reach at least 150 within 10,000 steps.

Hint

Set the ε decay back to 10,000 steps: 162.3. Or keep the 10,000-step decay and set the learning rate to 0.0001: 178.45.

  • Average return of the last 20 episodes ≥ 150
  • at most 10000 steps

Exercise 2: stay up for 475 steps

Train until the last 20 episodes average at least 475 (Gymnasium's "solved" bar for CartPole-v1).

Hint

The defaults first get there at around 70,000 steps. It goes up and down along the way; don't give up at 20,000.

  • Average return of the last 20 episodes ≥ 475

Quiz

What problem does experience replay mainly solve?
Why use a separate target network?
What does Double DQN change?

Further reading

Frequently asked questions

What is the difference between DQN and Q-learning?

The update rule is the same (the target is r + γ·the best Q of the next state); the difference is how Q is represented: Q-learning uses a table, DQN a neural network, so it handles continuous or huge state spaces. To keep the network's training stable, DQN adds experience replay and a target network.

Can DQN handle continuous actions?

Not directly: it takes a max over all actions, so the actions must be finite. Continuous actions usually call for DDPG, TD3 or SAC, or policy-gradient methods such as PPO.

Why does DQN's training curve go up and down?

The network computes its own targets (bootstrapping), so changing the network changes the targets; together with function approximation and off-policy learning, training can be unstable or even diverge. On this page, seed 1 reaches 475 at 70,000 steps and falls back to 227 by 80,000. Common remedies: keep the best model, lower the learning rate, use a larger buffer, sync the target network more slowly.

What is good about the Huber loss?

For small errors it equals the squared loss; for large errors it becomes linear, so a few outlier targets cannot produce huge gradients, and training is steadier.

Why was DQN important?

In 2015 Mnih et al. used one network architecture and one set of hyperparameters to learn dozens of Atari games straight from screen pixels, reaching human level on most of them — a milestone in combining deep learning with reinforcement learning.

Further reading