1. Home
  2. AI & Machine Learning
  3. Q-Learning (Reinforcement Learning)

Q-Learning (Reinforcement Learning)

An agent learns which action is best in every situation from rewards alone. Q-values spread backwards from the goal until a good path appears.

Interactive 3DIntermediate13 min readAI/MLUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

An agent (yellow) must find the goal without falling into pits, but nobody gives it a map or rules — only rewards. Q-learning lets it learn which action is best in every cell by trial and error. Press Train.

Pseudocode

  1. Q(s, a) ← 0 for every state and action
  2. for each episode: s ← start
  3. repeat until s is the goal or a pit:
  4. with probability ε pick a random action (explore), else the best one (exploit)
  5. take action a → reward r, new state s′
  6. Q(s, a) ← Q(s, a) + α · [ r + γ · max Q(s′, ·) − Q(s, a) ]
  7. s ← s′
Read this model as text · 17 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. An agent (yellow) must find the goal without falling into pits, but nobody gives it a map or rules — only rewards. Q-learning lets it learn which action is best in every cell by trial and error. Press Train.
  2. The agent knows nothing: every Q-value (expected future reward of an action in a cell) is 0. Each step costs −1, the goal gives +10, a pit gives −10 and ends the episode. Learning rate α = 0.5, discount γ = 0.9, exploration ε = 0.2.
  3. Episode 1, step 1: in (4,0) the agent explores (random) and goes up → reward -1. Update: Q = 0 + 0.5 × (-1 + 0.9 × 0 − 0) = -0.5.
  4. Episode 1, step 2: in (3,0) the agent exploits (best known) and goes down → reward -1. Update: Q = 0 + 0.5 × (-1 + 0.9 × 0 − 0) = -0.5.
  5. Episode 1, step 3: in (4,0) the agent exploits (best known) and goes down (bumps into a wall and stays put) → reward -1. Update: Q = 0 + 0.5 × (-1 + 0.9 × 0 − 0) = -0.5.
  6. Episode 1, step 4: in (4,0) the agent exploits (best known) and goes right → reward -1. Update: Q = 0 + 0.5 × (-1 + 0.9 × 0 − 0) = -0.5.
  7. Episode 1, step 5: in (4,1) the agent exploits (best known) and goes down (bumps into a wall and stays put) → reward -1. Update: Q = 0 + 0.5 × (-1 + 0.9 × 0 − 0) = -0.5.
  8. Episode 1, step 6: in (4,1) the agent exploits (best known) and goes up → reward -10. Update: Q = 0 + 0.5 × (-10 + 0.9 × 0 − 0) = -5.
  9. Episode 1 ended in the pit after 6 steps. Only the last move learned something big — rewards spread backwards one step per visit.
  10. After 2 episodes: average 6.5 steps per episode recently. The goal's value flows backwards through the grid — tiles near the goal rise first, then the ones before them.
  11. After 5 episodes: average 34.7 steps per episode recently. The goal's value flows backwards through the grid — tiles near the goal rise first, then the ones before them.
  12. After 10 episodes: average 21.4 steps per episode recently. The goal's value flows backwards through the grid — tiles near the goal rise first, then the ones before them.
  13. After 20 episodes: average 17.6 steps per episode recently. The goal's value flows backwards through the grid — tiles near the goal rise first, then the ones before them.
  14. After 40 episodes: average 10.1 steps per episode recently. The goal's value flows backwards through the grid — tiles near the goal rise first, then the ones before them.
  15. After 80 episodes: average 8.9 steps per episode recently. The goal's value flows backwards through the grid — tiles near the goal rise first, then the ones before them.
  16. After 150 episodes: average 9.3 steps per episode recently. The goal's value flows backwards through the grid — tiles near the goal rise first, then the ones before them.
  17. Following the arrows (always the best action) now reaches the goal in 8 steps and avoids every pit. Nobody told the agent the rules — it learned them from rewards alone. That is reinforcement learning.

Try this in the 3D model

  • Press Train and read the first few updates. Why do most early Q-values become negative?
  • Watch the checkpoints. Which tiles rise first — the ones near the start or near the goal?
  • Set exploration to 0.05 and train again. Does the agent still find a good path?
  • Switch to the Maze world. How does the learned path get around the walls?

Learning from rewards

Most machine learning needs labelled examples: “this photo is a cat”. In reinforcement learning there are no labels. An agent acts in an environment, receives rewards or penalties, and must work out by itself which actions lead to good outcomes. This is how game-playing programs such as AlphaGo learned, and how robots learn to walk in simulation.

The grid world in the 3D model is the classic small example:

  • States: the cells of the grid.
  • Actions: up, right, down, left. Walking into a wall leaves you where you are.
  • Rewards: −1 per step (hurry up!), +10 at the goal, −10 in a pit. Both end the episode.

The Q-table

Q(s, a) is the agent’s estimate of the total future reward if it takes action a in state s and then behaves as well as it can. If you know all the Q-values, acting well is easy: in every state, pick the action with the highest Q. In the model, a tile’s height shows its best Q-value and the arrow shows the best action.

The update rule

After every step (state s, action a, reward r, new state s′), Q-learning nudges its estimate towards a better one:

Q(s, a) ← Q(s, a) + α · [ r + γ · max over a′ of Q(s′, a′) − Q(s, a) ]
  • r + γ · max Q(s′, ·) is the target: the reward we just got plus the discounted value of the best thing we can do next.
  • α (learning rate, 0.5 here) controls how far we move towards the target.
  • γ (discount, 0.9 here) makes future rewards worth a bit less than immediate ones.

At first everything is 0, so the steps only learn “walking costs −1”. When the agent finally stumbles into the goal, the last move gets a big positive value. On later episodes the move before it sees that value through max Q(s′), and so on. The reward spreads backwards one step at a time, which is why the tiles near the goal rise first.

Explore or exploit?

If the agent always takes its current best action, it might never discover a better route. ε-greedy fixes this: with probability ε take a random action (explore), otherwise take the best one (exploit). With too little exploration the agent can get stuck; with too much, it wanders around and learns slowly.

Code

import random

def q_learning(step, start, n_states, episodes=150, alpha=0.5, gamma=0.9, eps=0.2):
    Q = {(s, a): 0.0 for s in range(n_states) for a in range(4)}
    for _ in range(episodes):
        s, done = start, False
        while not done:
            if random.random() < eps:
                a = random.randrange(4)                      # explore
            else:
                a = max(range(4), key=lambda x: Q[(s, x)])   # exploit
            s2, r, done = step(s, a)                         # environment answers
            best_next = 0 if done else max(Q[(s2, x)] for x in range(4))
            Q[(s, a)] += alpha * (r + gamma * best_next - Q[(s, a)])
            s = s2
    return Q

The step function is the environment: given a state and an action, it returns the new state, the reward and whether the episode ended. For real problems the Q-table is replaced by a neural network that predicts Q-values. That is Deep Q-Learning (DQN), which learned to play Atari games from the screen pixels.

Q-learning vs other methods

Q-learning SARSA Minimax / search
Needs a model of the world ❌ No (model-free) ❌ No ✅ Yes
Learns from Best next action (off-policy) Action actually taken (on-policy) Looking ahead in a game tree
Behaviour near danger Bold (learns the optimal path) Cautious (accounts for its own exploring) Exact if the tree fits

Common mistakes

  • Using the action actually taken next in the target. That is SARSA. Q-learning uses the max over next actions.
  • Forgetting that terminal states have no future: their max Q is 0.
  • Setting ε = 0 from the start. The agent may never find the goal.
  • Expecting convergence after a few episodes. Values need many visits before they stop changing.

Complexity at a glance

Case / operationTimeWhy
One Q-learning updateO(|A|)Look up max over the actions of the next state.
Q-table sizeO(|S| · |A|)One value per state–action pair (here 25 × 4).
Episodes to convergegrows with the state spaceEvery pair must be tried many times.
Extra spaceO(|S| · |A|)

Quick check

Test yourself — pick an answer to see if you got it.

1. What does Q(s, a) estimate?

2. Why does the agent sometimes take a random action (ε-greedy)?

3. In the update Q ← Q + α(r + γ · max Q(s′) − Q), what does γ (gamma) control?

4. Q(s, a) = 2, the reward is −1, max Q(s′, ·) = 6, α = 0.5, γ = 0.9. What is the new Q(s, a)?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Q-Learning (Reinforcement Learning). Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.