Imagine guiding an agent across a frozen lake to a goal on the far side. Some squares are holes, and the slippery surface means an action may not take it where you intended. The agent can gather experience by trying moves and observing the outcomes. Q-learning uses that experience to build estimates that help it choose safer routes.
We trace how moves and rewards fill the state-action table, then check the route the agent learns. After 20,000 episodes, it reaches the goal about 67% of the time, below the slippery lake's roughly 74% maximum. Varying random exploration tests how those choices affect learning.
By the end of this post, you'll implement Q-learning from scratch, train an agent to navigate OpenAI's FrozenLake environment, and understand the Bellman equation that makes it all work. You'll also see why exploration matters, and what happens when an agent gets greedy too early.
The algorithm was introduced by Watkins (1989) in his PhD thesis and its convergence was proven by Watkins & Dayan (1992).
The Problem: FrozenLake
OpenAI's FrozenLake is a 4×4 grid world:
SFFF S = Start
FHFH F = Frozen (safe)
FFFH H = Hole (game over)
HFFG G = Goal (reward = 1)
The agent can move Left, Down, Right, Up. But on slippery ice, each action has only a 1/3 chance of going in the intended direction; there's a 1/3 chance of sliding in each perpendicular direction. The only reward is +1 for reaching the Goal. Fall in a Hole or run out of steps and you get 0.
This is a model-free problem: the agent doesn't know the transition probabilities or the reward structure. It must learn entirely from experience.
Quick Win: Run the Algorithm
Let's see Q-learning in action. Click the badge to open the interactive notebook:

The GIF shows the agent's learned policy evolving from random arrows (no idea what to do) to a coherent strategy that avoids holes and reaches the goal. The colour intensity shows : how valuable each state is.
import numpy as np
import gymnasium as gym
def q_learning(env, n_episodes=20000, alpha=0.1, gamma=0.99,
epsilon_start=1.0, epsilon_end=0.01, decay_rate=1e-3):
"""Q-learning with epsilon-greedy exploration."""
Q = np.zeros((env.observation_space.n, env.action_space.n))
rewards = []
epsilon = epsilon_start
for episode in range(n_episodes):
state, _ = env.reset()
total_reward = 0
for step in range(100):
# Epsilon-greedy action selection
if np.random.random() < epsilon:
action = env.action_space.sample()
else:
action = np.argmax(Q[state])
next_state, reward, terminated, truncated, _ = env.step(action)
done = terminated or truncated
# Q-learning update (Bellman equation)
Q[state, action] += alpha * (
reward + gamma * np.max(Q[next_state]) - Q[state, action]
)
total_reward += reward
state = next_state
if done:
break
rewards.append(total_reward)
epsilon = epsilon_end + (epsilon_start - epsilon_end) * np.exp(
-decay_rate * episode
)
return Q, rewards
# Train the agent
env = gym.make('FrozenLake-v1', is_slippery=True)
Q, rewards = q_learning(env)
# Show the learned policy
actions = ['←', '↓', '→', '↑']
policy = np.array([actions[a] for a in np.argmax(Q, axis=1)]).reshape(4, 4)
print("Learned policy:")
print(policy)
print(f"\nSuccess rate (last 1000): {np.mean(rewards[-1000:]):.1%}")
The result: After 20,000 episodes, the agent learns a policy that reaches the goal ~67% of the time. Even with a good policy, the slippery ice inevitably pushes you into holes. The theoretical maximum for this environment is about 74%.
Visualise the Learning
import matplotlib.pyplot as plt
rolling = np.convolve(rewards, np.ones(100)/100, mode='valid')
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(rolling, 'b-', linewidth=0.8)
ax.set_xlabel('Episode')
ax.set_ylabel('Success Rate (100-episode rolling avg)')
ax.set_title('Q-Learning on FrozenLake')
ax.set_ylim(0, 1)
ax.grid(True, alpha=0.3)
plt.show()

The reward curve climbs from 0% (random) to ~67% (near-optimal). The initial flat period is pure exploration: the agent is collecting experience before it starts exploiting what it's learned.
What Just Happened?
Q-learning maintains a Q-table: a lookup table mapping every (state, action) pair to a value. For FrozenLake, that's 16 states × 4 actions = 64 entries, all starting at zero.
The Bellman Equation
The core update rule is one line of code:
Q[state, action] += alpha * (
reward + gamma * np.max(Q[next_state]) - Q[state, action]
)
This implements the temporal difference (TD) update:
Let's break this apart:
- : current estimate of "how good is action a in state s?"
- : immediate reward received
- : discounted value of the best action in the next state
- : the TD target (what we think the true value is)
- : the TD error (how wrong we were)
- : learning rate (how much to correct)
Think of it like updating a GPS estimate: you have a current estimate of the distance (), you observe a new measurement (the target), and you adjust by a fraction () of the difference.
Epsilon-Greedy Exploration
if np.random.random() < epsilon:
action = env.action_space.sample() # explore: random action
else:
action = np.argmax(Q[state]) # exploit: best known action
With probability , the agent takes a random action (exploration). Otherwise, it takes the best action according to its Q-table (exploitation).
Early in training, : pure exploration. Over time, it decays exponentially:
This mirrors the exploration-exploitation trade-off in MCMC: the Metropolis-Hastings algorithm also balances proposing random moves with accepting good ones.
Off-Policy Learning
Q-learning is off-policy: it learns about the greedy policy () while following an exploratory policy (epsilon-greedy). This separation is powerful: the agent can explore freely without corrupting what it's learning about the optimal policy.
The alternative, SARSA (on-policy), updates using the action the agent actually took next, not the best possible action. SARSA is more conservative: it learns a safer policy that accounts for its own exploration.
Going Deeper
Hyperparameters
| Parameter | What it controls | FrozenLake value | Guidance |
|---|---|---|---|
alpha | Learning rate | 0.1 | Low for stochastic envs, higher for deterministic |
gamma | Discount factor | 0.99 | Close to 1 for long-horizon tasks |
epsilon_start | Initial exploration | 1.0 | Always start fully random |
epsilon_end | Final exploration | 0.01 | Small but non-zero |
decay_rate | Exploration decay | 0.001 | Slower = more exploration |
n_episodes | Training budget | 20,000 | Until convergence |
gamma is critical. It controls how much the agent values future rewards vs immediate ones:
- : only cares about immediate reward (myopic)
- : values all future rewards equally (farsighted)
- : reward 10 steps away is worth of its face value
For FrozenLake, the goal is ~6 steps away but stochastic transitions make paths longer. With , a reward 10 steps away is worth . The agent strongly values the distant goal.
Slippery vs Non-Slippery
# Deterministic: agent goes exactly where intended
env_easy = gym.make('FrozenLake-v1', is_slippery=False)
Q_easy, rewards_easy = q_learning(env_easy)
print(f"Non-slippery success rate: {np.mean(rewards_easy[-1000:]):.1%}") # ~100%
# Stochastic: 1/3 chance of sliding sideways
env_hard = gym.make('FrozenLake-v1', is_slippery=True)
Q_hard, rewards_hard = q_learning(env_hard)
print(f"Slippery success rate: {np.mean(rewards_hard[-1000:]):.1%}") # ~75%
Without slippery ice, the agent achieves ~100% success: the problem becomes trivial. The stochastic transitions are what make FrozenLake interesting: the agent must learn a policy that's robust to noise.
When NOT to Use Tabular Q-Learning
- Large state spaces: A 100×100 grid has 10,000 states × 4 actions = 40,000 Q-values. Tables don't scale. Use neural network function approximation instead (Deep Q-Networks)
- Continuous states: Temperature, position, velocity can't be tabulated. Use function approximation or discretise
- Continuous actions: Q-learning requires , which is trivial for discrete actions but requires optimisation for continuous ones. Use policy gradient methods instead
Alternatives:
- Deep Q-Networks (DQN): Replace the Q-table with a neural network
- SARSA: On-policy variant, learns a safer policy
- Policy gradient methods: Directly optimise the policy, handle continuous actions
- Monte Carlo methods: Wait until the end of the episode to update (no bootstrapping)
The Foundational Papers
Watkins (1989)
Christopher Watkins introduced Q-learning in his PhD thesis Learning from Delayed Rewards at Cambridge. The key problem he addressed: how can an agent learn optimal behaviour when rewards are delayed (you don't know if a move was good until many steps later)?
His solution was to learn the action-value function directly, rather than the state-value function . The crucial insight: by learning values, the agent can select optimal actions without needing a model of the environment: it just picks .
Convergence Guarantee
Watkins & Dayan proved in their 1992 paper that Q-learning converges to the optimal Q-function under two conditions:
- Every state-action pair is visited infinitely often
- The learning rate decays appropriately (but not too fast)
Formally, given the update:
Convergence requires:
The first condition ensures sufficient learning; the second ensures the updates eventually settle. In practice, a constant learning rate works well for tabular problems.
The Bellman Optimality Equation
Q-learning is grounded in Bellman's Dynamic Programming (1957). The optimal Q-function satisfies the Bellman optimality equation:
This is a fixed-point equation: the optimal Q-values are self-consistent. Q-learning iteratively approximates this fixed point using sampled transitions instead of computing the full expectation.
Our Implementation vs the Theory
| Theory | Our code |
|---|---|
| State space | 16 grid cells (0-15) |
| Action space | 4 directions (L, D, R, U) |
| Q-function | Q numpy array (16×4) |
| Policy | np.argmax(Q[state]) |
| Bellman update | Q[s,a] += alpha * (r + gamma * max(Q[s']) - Q[s,a]) |
| Exploration -greedy | if random() < epsilon: sample() |
Historical Context
- Bellman (1957): Dynamic programming and the Bellman equation
- Samuel (1959): Checkers-playing program, early TD learning
- Sutton (1988): TD(λ) learning framework
- Watkins (1989): Q-learning: model-free off-policy control
- Watkins & Dayan (1992): Convergence proof for Q-learning
- Mnih et al. (2013): Deep Q-Networks (DQN), Q-learning with neural nets, playing Atari
- Sutton & Barto (2018): Reinforcement Learning: An Introduction, the definitive textbook
Further Reading
- Watkins (1989): The original Q-learning thesis
- Watkins & Dayan (1992): Convergence proof
- Sutton & Barto (2018): Chapters 6 (TD Learning) and 6.5 (Q-Learning), freely available online
- Mnih et al. (2015): Human-level control through deep RL, DQN paper in Nature
Interactive Tools
- Q-Learning Visualiser: Watch Q-learning train step-by-step on grid worlds in the browser
- Multi-Armed Bandit Simulator: The same epsilon-greedy rule with the state removed, next to UCB1 and Thompson sampling. Shows what epsilon is actually buying, and what replaces it
Related Posts
- Genetic Algorithms: evolution-based optimisation (no gradient, no model, like Q-learning)
- Backpropagation Demystified: the gradient engine that powers Deep Q-Networks
- MCMC Island Hopping: another algorithm balancing exploration and exploitation
- Q-Learning for Games: Teaching an Agent Tic-Tac-Toe Through Self-Play: the same tabular Q-learning applied to a two-player self-play game
- Value Iteration vs Q-Learning: Dynamic Programming Meets RL: value iteration vs the model-free Q-learning used here
- Solving CartPole Without Gradients: Simulated Annealing: a gradient-free, value-free alternative that searches policy space directly instead of learning a Q-table
- Reward Hacking in Reinforcement Learning: Even tabular Q-learning will exploit a sloppy reward. The failure mode scales up from this frozen lake
- Monte Carlo Tree Search in Python: Beating a Heuristic Without One: acting well by searching from the current position at every move, with no table and no training
Try It Yourself
The interactive notebook includes exercises:
- Slippery vs non-slippery: Compare convergence curves for
is_slippery=TrueandFalse. How does the optimal success rate differ? - Gamma sweep: Try . How does the discount factor affect learning speed and final performance?
- SARSA comparison: Modify the update to use the actual next action instead of . How does the learned policy differ?
- 8×8 FrozenLake: Switch to
FrozenLake8x8-v1(64 states). Does Q-learning still converge? How many more episodes does it need? - Visualise exploration: Track how many times each state is visited during training. Which states are under-explored?
Understanding Q-learning opens the door to Deep Q-Networks, policy gradients, and modern RL. The core insight, learning action values from delayed rewards through bootstrapping, is the foundation of all value-based reinforcement learning.








