Q-learning step by step
A treasure hunt with rocks and traps. Build the Q-learning update line by line, see why it passes reward backwards, and read the map your agent learns.
In 60 seconds
Q-learning step by step
A treasure hunt with rocks and traps. Build the Q-learning update line by line, see why it passes reward backwards, and read the map your agent learns.
Q[state][action]: the agent's estimate of the total discounted reward it will collect if it takes that action in that state and then plays well afterwards.The update, one piece at a time
- 1
Act
In state s, take action a. See reward r and the next state s2. - 2
Build a target
If the game ended, target = r. Otherwise target = r + gamma x (the best Q in s2). - 3
Measure the surprise
error = target - Q[s][a]. Positive means "better than I thought". - 4
Nudge
Q[s][a] = Q[s][a] + alpha x error. Alpha (0 to 1) is the learning rate: how big the nudge is. - 5
Move on
s = s2 and repeat until the episode ends.
alpha, gamma = 0.5, 0.9
Q_here = 0.0 # Q[s][a]: what we believed before
reward = -1.0 # one step cost us a point
best_next = 5.0 # the best Q in the next state, s2
target = reward + gamma * best_next # -1 + 0.9 * 5 = 3.5
error = target - Q_here # 3.5: better than we thought!
Q_here = Q_here + alpha * error # 0 + 0.5 * 3.5 = 1.75
print("target", target, "error", error, "new Q", Q_here)
best_next) instead of waiting for the end of the game. Learning from your own next guess is called temporal-difference (TD) learning. It is why the reward from the treasure spreads backwards, one square per visit.gamma * max(Q[s2]) for the treasure square, the agent believes the game continues after it has finished.Why Q-learning can learn from exploring
Reading the table
| Setting | What it controls | If too small | If too large |
|---|---|---|---|
| alpha (learning rate) | How far each update moves Q | Learning is very slow | Estimates jump around with every lucky or unlucky step |
| gamma (discount) | How much later rewards count | Agent is short-sighted and may not value a far treasure | Values grow large and learning can be slower |
| epsilon (exploring) | How often to act randomly | May never find the treasure | Keeps stumbling into traps while learning |
| episodes | How many games to practise | Values have not spread back to the start yet | Wasted time, but no harm in a small game |
gamma = 0.1 and train again. Print Q[START]. Why are the numbers near the start so small, and does the agent still find the treasure?Watch and read more
Lab
A Q-learning agent that learns a safe, short route to the treasure on a 6 x 5 map with rocks and traps.
The problem
The map has a start S, a treasure T (+10), traps X (-10, game over) and rocks # you cannot enter. Every move costs -1. The training loop, the map and the epsilon-greedy choice are ready. Only the learning is missing.
- Press Run.
q_updatedoes nothing, so the Q table stays at zero and the learned route goes nowhere. - Write
q_update: build the target (justrifdone, elser + gamma * max(Q[s2])), then moveQ[s][a]toward it byalphatimes the error. - Run again. Read the arrow map and the route. Does it reach
Twithout touching anX? - Press Check. (It uses the original map, so you may experiment freely afterwards.)
- Experiments: train with only 20 episodes; then with
gamma = 0.1. Write what changed and why.
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1The shortest route to the treasure passes right next to a trap. Q-learning takes it. Why might a real robot prefer a slightly longer route?Reveal
Q-learning learns the value of playing perfectly. In real life, a robot's moves can slip, or it may still explore, and one slip next to the trap costs -10. A longer route away from the trap is safer when actions are unreliable. SARSA, or adding random slips to training, tends to learn that safer route. For real robots, safety limits should also be enforced outside the learned policy.
Q2After training, the best Q value at the start is about -1.4. Can you explain that number?Reveal
The best route takes 9 moves: eight moves costing -1 and a final +10. With gamma = 0.9 the discounted return is -1 - 0.9 - 0.81 - ... (eight terms) + 0.9^8 x 10. The eight costs add up to about -5.70 and the prize is worth about 4.30, so the total is about -1.4. If your number differs a little, the values may not have fully settled yet. Working this out by hand is a great way to check that your update is right.
Questions people ask
Why is it called Q?
It comes from the original research, where Q stood for the "quality" of an action in a state. People still use the letter.
Does Q-learning always find the best route?
In a small game like this, with enough exploring, enough episodes and a sensible learning rate, it reliably finds it. The theory has conditions, such as trying every action in every state again and again. With too few episodes or too little exploring, it may settle for a worse route.
Why do all the Q values start at zero?
Zero is a simple, neutral guess. Some people start values high to encourage exploring early, like the optimistic trick from the bandit lesson. With a -1 cost per step, zero is already a little optimistic, which helps.
What is the difference between Q-learning and SARSA?
SARSA is a close cousin. Its target uses the action the agent actually takes next, including random exploring ones, instead of the best one. So SARSA learns the value of the way it really behaves, and near traps it often learns a safer route that stays further away.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.