Q-Learning
Q-learning and its deep variants were central to game-playing AI in the 2010s, and it still runs underneath modern DQN, Rainbow, and offline RL. Five lines of update rule. Yet understanding it is the difference between memorizingQ(s,a) ← Q(s,a) + α[r + γ max Q − Q]and actually grokking why bootstrapped value propagation converges. Once it clicks, the rest of RL is variations on this theme.
After this lesson, you will be able to:
- Understand the Bellman equation: how it breaks a big, long-term problem into simple one-step decisions using the recursive Q(s,a) ← Q(s,a) + α[r + γ max Q(s',a') - Q(s,a)] update
- Code Q-learning from scratch and watch it learn the best path through a grid maze
- Distinguish Q-learning (off-policy: always updates toward the max Q of the next state) from SARSA (on-policy: updates toward the Q of the action actually taken)
- Know when Q-learning converges and why the tabular approach fails catastrophically at large state spaces, and what Deep Q-Networks do instead
Before you start
#A Map of Value
#The Bellman Equation: The Foundation
The Bellman equation is the recursive relationship at the heart of Q-learning. It says: the value of being in a state and taking an action equals the immediate reward plus the discounted value of the best action in the next state.
#Why Does This Work?
Consider a two-step problem. The return is R1 + gamma * R2. The optimal Q-value is:
The recursion telescopes: at every step, the optimal Q-value accounts for all future optimal decisions. This is the magic of the Bellman equation, it lets us solve a multi-step problem by solving many one-step problems.
#The Q-Learning Algorithm
Where:
- alpha is the learning rate (how much to update per experience)
- R_ + gamma * max Q(S_, a) is the TD target (what the Bellman equation says Q should be)
- Q(S_t, A_t) is the current estimate
- The difference is the temporal difference (TD) error: the surprise
The TD error is more than a surprise. Averaged over what the environment can do next, it is exactly how far Q is from satisfying the Bellman optimality equation, which is what the derivation below shows. The Bellman optimality equation itself is derived in the Markov Decision Processes lesson of the Math track.
After one Q-learning update, will Q(s, a) exactly equal the Bellman target?
The learning rate alpha (typically 0.01 to 0.1) controls what fraction of the TD error to apply. With alpha = 1.0, Q would jump to the target immediately, but this causes instability because the target itself changes as Q changes. Small alpha values ensure smooth, stable convergence.
#Step-by-Step: Q-Learning on a Gridworld
#Step 1: Agent in State s, Q-Table Initialized
Create a table with one row per state and one column per action. Initialize all Q-values to zero (or small random values). Our gridworld has 16 states (4x4 grid) and 4 actions (up, down, left, right). The Q-table has 16 x 4 = 64 entries, all starting at zero.
The agent starts at the top-left corner. It knows nothing, every state-action pair looks equally worthless. The Q-table is a blank map waiting to be filled with experience.
#Step 2: Epsilon-Greedy, Explore or Exploit
Early in training, all Q-values are zero, so even the "greedy" choice is effectively random. As Q-values develop, the greedy choice becomes increasingly informed. Epsilon-greedy ensures the agent never stops exploring entirely.
#Step 3: Take Action a, Observe r and s'
The agent executes its chosen action. It moves right. The environment responds with a new state (the next cell) and a reward (-0.04 step penalty). The agent now has its first experience tuple: (s=0, a=right, r=-0.04, s'=1).
This single experience contains everything needed for a Q-learning update: where it was, what it did, what it got, and where it ended up.
#Step 4: Q(s,a) = Q(s,a) + alpha[r + gamma * max Q(s',a') - Q(s,a)]
Apply the Bellman update. Target = r + gamma * max Q(s', a') = -0.04 + 0.99 * 0 = -0.04. The TD error is target - current = -0.04 - 0 = -0.04. Update: Q[0][right] = 0 + 0.1 * (-0.04) = -0.004.
#Step 5: Move to s'
The agent transitions to state s' and the loop repeats. From this new state, it again chooses an action via epsilon-greedy, takes the action, observes the result, and updates Q. Each update propagates value information one step backward through the state space.
After reaching the goal (reward +1), that reward signal slowly backs up through the Q-table, first to states adjacent to the goal, then to states two steps away, then three, and so on. After 100 episodes, states near the goal have high Q-values. After 1000 episodes, the value gradient reaches the start.
#Step 6: Q-Table Converges
After enough episodes, every Q-value converges to satisfy the Bellman equation. The Q-table is now a complete "value map" of the environment. The optimal policy is trivially extracted: at each state, pick the action with the highest Q-value.
The agent has discovered the shortest path from start to goal, entirely through trial and error. No teacher told it the layout of the grid. No planner computed the path. Q-learning built the map one experience at a time.
Observe Q-learning in action on a grid world. Each cell displays Q(s,a) for all four actions as colored triangles. Brighter colors mean higher values. As the agent explores, Q-values propagate backward from the goal, eventually revealing the optimal path through policy arrows.
#Convergence: When Does Q-Learning Work?
Q-learning is guaranteed to converge to the optimal Q-function Q* under certain conditions:
- Every state-action pair is visited infinitely often. The agent must keep exploring (epsilon-greedy with a decaying but non-zero epsilon ensures this).
- The learning rate decays appropriately. It must satisfy the Robbins-Monro conditions: the sum of learning rates diverges (sum alpha_t = infinity) but the sum of squared learning rates converges (sum alpha_t^2 < infinity). In practice, a fixed small learning rate works well enough.
- The MDP has finite states and actions. The tabular approach requires enumeration.
The first condition lets the estimate travel any distance. The second damps the noise. The running average, where alpha is 1/n, shows both at once.
#The max in the target is biased upward
Convergence is a statement about the limit. In the meantime the max in the target does something subtle: when the table entries are noisy, the max of the noisy numbers is larger on average than the max of the true ones. Deep Q-Networks fixes this with Double DQN, but the Deep Q-Networks lesson only describes the effect, so here is the short derivation.
#Q-Learning vs. SARSA
When does this matter? In "cliff walking" problems, Q-learning finds the shortest path along the cliff edge (optimal but risky). SARSA finds a safer path farther from the cliff because it accounts for the chance that epsilon-greedy exploration will cause a fall.
Why can Q-learning use data from any behaviour policy b, while SARSA cannot? The answer is in what each target averages over.
#Expected SARSA
Expected SARSA keeps SARSA's policy dependence but removes the noise from sampling A'. It replaces the sampled Q(S', A') by its average under the policy pi that is being learned about:
Its target has the same mean as SARSA's when A' is drawn from pi, by the fifth step of the derivation above. By the law of total variance, Var(Y) = E[Var(Y | S', R)] + Var(E[Y | S', R]), and Expected SARSA is the second term alone, so it is never noisier than SARSA. When pi is greedy the sum collapses to the max and the update is Q-learning (Sutton and Barto, section 6.6).
#Why epsilon-greedy exploration still improves the policy
Q-learning and SARSA need to keep exploring, so the policy they follow is epsilon-greedy. A policy is epsilon-soft if it gives every action probability at least epsilon divided by the number of actions. The claim below says that acting epsilon-greedily on Q^pi never makes things worse, so the exploration does not break the improvement idea. It uses the policy improvement theorem, derived in the Markov Decision Processes lesson.
#The Curse of Dimensionality
Tabular Q-learning stores one value per state-action pair. This works beautifully for small problems:
- Gridworld (16 states, 4 actions): 64 Q-values: trivial
- Tic-tac-toe (~5,000 states, 9 actions): ~45,000 Q-values: easy
- Backgammon (~10^20 states): impossible to store a table
- Atari games (210 x 160 pixels, 256 values each = 10^80,000 possible states): laughably impossible
An Atari game screen has 210 x 160 pixels, each with 256 possible color values. How many possible states exist?
#Try It Yourself
Tests: After training, verify Q[0][1] > Q[0][0] (right is better than left at start). Verify Q[3][1] > Q[3][0] (right is better at state 3, which is adjacent to the goal).
Sparse rewards are slow to learn from. Here two real Q-learning agents train on the same grid so you can measure the difference yourself.
Both agents get reward at the goal. The second one also gets a small bonus for each step that moves closer to it. Press Train and compare the episode counters.
Do: Press Train and wait until both counters show a number. Press Reset and train again.Notice: The shaped agent reaches 10 goals in a row in far fewer episodes, and the page prints the ratio. Reset picks a new random seed, so the counts change each time. Cells far from the route can stay blank on the sparse map.Why: With zero reward everywhere except the goal, the sparse agent has nothing to learn from until a random walk lands on the goal. The bonus here is based on distance to the goal in a potential-based form, which leaves the best path unchanged. Both agents are real tabular Q-learning with identical settings, run live in your browser. Only the reward differs.
#Key Takeaways
- The Bellman equation decomposes long-horizon problems. The value of a state-action pair equals the immediate reward plus the discounted value of the best next state, turning a complex sequential problem into iterative one-step updates
- Q-learning updates values by bootstrapping. Instead of waiting for complete episodes, Q-learning updates Q(s,a) after each step using the estimated value of the next state, enabling online learning
- Tabular Q-learning converges under specific conditions. Every state-action pair must be visited infinitely often and the learning rate must decay appropriately; in practice, this limits Q-tables to small, discrete state spaces
- The discount factor gamma controls time horizon. High gamma (near 1) values long-term rewards, low gamma values immediate rewards; this single parameter fundamentally changes the learned behavior
Interactive Lab
Step through Q-learning on a small grid one transition at a time, watch the Bellman update propagate value from the goal back toward the start, cell by cell, until the optimal policy emerges from the table.
Interactive Lab
Slide γ from 0 to 1 and watch the agent's behavior shift from greedy short-sightedness to long-horizon planning, the single hyperparameter that defines what the agent considers 'the future'.
#Quick Check
What does the Bellman equation decompose the optimal Q-value into?