
2024-02-18
Deep Q-Learning is one of the techniques that kicked off the modern wave of reinforcement learning: the same family of ideas behind agents that learned to play Atari games from raw pixels, and a precursor to the systems that later mastered Go and Dota 2. In this post, we'll build up the math behind it piece by piece — starting from a simple grid-world example, and working up to why "deep" Q-learning needs a couple of extra tricks to actually work in practice.
In reinforcement learning, an agent interacts with an environment over a series of time steps. At each step, the agent observes a state , picks an action , and receives a reward in return, landing in a new state . The agent's goal is to learn a policy — a strategy for picking actions — that maximizes the total reward it collects over time, not just the immediate reward at each step.
This is where Q-learning comes in: instead of learning a policy directly, it learns the value of taking a given action in a given state, and lets the agent act greedily with respect to that value.
The Q-function, , represents the expected total future reward of taking action in state , and then acting optimally from there on. If we knew the true for every state-action pair, acting optimally would be trivial: just pick the action with the highest Q-value.
The Q-function satisfies the Bellman equation, which breaks the problem down recursively — the value of a state-action pair is the immediate reward, plus the discounted value of the best action from the state you land in:
Here, is the discount factor, controlling how much the agent cares about future rewards versus immediate ones.
Let's make this tangible with a tiny grid world. Mario starts in the top-left cell and can move between cells; some cells carry a reward, most don't:
A grid-world example: Mario starts at (0,0), a Goomba gives -5, and reaching Peach gives +5
Suppose Mario takes the path highlighted in the image: down, right, right, up, right — ending on Peach for a reward of , with every other step along the way giving . With a discount factor of , we can compute the Q-value of each step by working backward from the goal:
Notice how the value decays the further back we go — a reward five steps away is worth less than the same reward one step away. Compare this to stepping directly onto the Goomba instead: . Even without knowing anything else, the agent can already tell that heading toward Peach () is a far better idea than heading toward the Goomba ().
In practice, we don't know these values ahead of time — the agent learns them through trial and error, using the Q-learning update rule. After each transition , it nudges its current estimate of toward the value implied by the Bellman equation:
where is a learning rate, and the bracketed term is the TD (temporal difference) error — the gap between what the agent currently believes and what it just observed. Here's that exact update rule, run on the grid above until it converges — notice the learned values land on the same numbers we just computed by hand:
import random rewards = { (0, 1): -5, # Goomba (0, 3): 5, # Peach } terminal_states = {(0, 1), (0, 3)} transitions = { (0, 0): {"down": (1, 0), "right": (0, 1)}, (1, 0): {"right": (1, 1)}, (1, 1): {"right": (1, 2)}, (1, 2): {"up": (0, 2)}, (0, 2): {"right": (0, 3)}, } gamma = 0.9 alpha = 0.5 Q = {s: {a: 0.0 for a in actions} for s, actions in transitions.items()} for episode in range(500): state = (0, 0) while state not in terminal_states: action = random.choice(list(transitions[state].keys())) next_state = transitions[state][action] reward = rewards.get(next_state, 0) next_max = 0.0 if next_state in terminal_states else max(Q[next_state].values()) td_target = reward + gamma * next_max Q[state][action] += alpha * (td_target - Q[state][action]) state = next_state for state, actions in Q.items(): for action, value in actions.items(): print(f"Q({state} -> {action}) = {value:.3f}") # Q((0, 0) -> down) = 3.280 # Q((0, 0) -> right) = -5.000 # Q((1, 0) -> right) = 3.645 # Q((1, 1) -> right) = 4.050 # Q((1, 2) -> up) = 4.500 # Q((0, 2) -> right) = 5.000
The example above works because the grid is tiny — we can store a Q-value for every state-action pair in a table. But real environments (think: raw pixels from a video game, or a robot's sensor readings) have far too many possible states to enumerate.
This is where the "deep" part comes in: instead of a table, we approximate with a neural network, , where are the network's weights. The network takes a state as input and outputs a Q-value for every possible action — exactly the kind of forward pass we covered in the neural networks post.
There's a subtlety here that trips a lot of people up: the Bellman equation's target, , itself depends on the network we're trying to train. If we update the same network we're using to compute the target, we're chasing a moving target — small updates to shift the target on every single step, which makes training unstable.
The fix used by Deep Q-Networks (DQN) is to keep two networks: a Q-network that's updated every step, and a target network — a periodically-refreshed copy of the Q-network — that's used only to compute the target value:
Two networks with the same architecture: the Q Network, updated every step, and the Target Network, used only to compute stable targets
Given a batch of stored transitions — sampled from a buffer of past experience rather than just the most recent step, a trick called experience replay — the network is trained to minimize the squared TD-error:
Here are the Q-network's weights (updated every step via gradient descent, exactly as we covered in the neural networks post), and are the target network's weights, copied over from every few thousand steps rather than every step. That lag is what keeps the target still long enough for training to actually converge.
Training stability — plot
Illustrative curves, not measured from a real run — but this is the shape of the problem: when the same network supplies both the prediction and its own target, small updates keep shifting the target and the loss can spiral instead of settling. A separate, lagged target network breaks that feedback loop.

The full training loop looks like this: the agent observes a state, picks an action (occasionally at random, to keep exploring), and stores the resulting transition in a replay buffer. Periodically, it samples a batch from that buffer and takes a gradient step to reduce the loss above. Every so often, it syncs the target network's weights to match the Q-network's. Repeat for millions of steps, and the Q-network gradually converges toward the true Q-function — able to look at a state it's never seen before and estimate which action is worth taking.
I hope this gave you a clearer picture of what's actually happening under the hood of Deep Q-Learning. If you enjoyed this post, check out the neural networks post for a refresher on the forward and backward pass that powers the Q-network itself.
References: