Q-Learning Gridworld, Explained

After reading this you will know how a Q-learning agent turns rewards into a table of action values, how to reproduce the numbers by hand for a tiny grid, and how to read the heatmap and policy arrows the tool draws.

What Q-learning does

Q-learning is a method for finding good behavior by trial and error. You place an agent in a grid. Some cells give reward (a goal), some punish (a trap or a cliff), and every step usually costs a small penalty. The agent does not know the layout in advance. It walks around, remembers what happened, and slowly builds a table that says: from this cell, taking this action, how much total reward can I expect if I keep acting well afterward.

That table is called Q(s, a): the value of action a in state s. Once the table is accurate, the best policy is simple. In each cell, take the action with the highest Q value. The tool draws those choices as arrows, and it colors each cell by its best Q value, so a warm cell is a valuable cell.

The hook to try first is the cliff walk. Load it and press Play. The agent learns to sprint along the very edge of the cliff, one cell above the drop, because that path is shortest. It does this even though a single exploratory misstep near the edge is expensive. The reason lies in the update rule, which we derive below.

When to use it, and when not

Tabular Q-learning fits problems with a small, countable set of states and actions, where you can afford one table entry per state-action pair. A 6-by-6 grid with 4 actions has 36 \times 4 = 144 entries. That is trivial to store and fast to fill.

It stops being practical when the state space explodes. A chess board or a camera image has more states than atoms in the observable universe, so you cannot store a row per state. Those problems need function approximation, which replaces the table with a learned function. That is a different tool with different failure modes.

Q-learning assumes the environment is a Markov decision process: the next state and reward depend only on the current state and action, not on the full history. A gridworld satisfies this exactly. Many real problems only approximate it.

Two nearby ideas are worth separating. If your problem has one state and you only choose among fixed options, that is a bandit, explored in the Multi-Armed Bandit Lab. If your state is continuous and physical, like a pole angle, see the CartPole Balancing AI.

The update rule and why it works

Every time the agent takes action a in state s, lands in state s', and collects reward r, it nudges one table entry:

Q(s,a) \leftarrow Q(s,a) + \alpha\left[r + \gamma \max_{a'} Q(s',a') - Q(s,a)\right]

Read the bracket as an error. The term r + \gamma \max_{a'} Q(s',a') is the target: the reward you just got, plus the discounted value of the best you can do from the new cell. The term Q(s,a) is your current guess. The difference is how wrong you were. You move your guess a fraction \alpha of the way toward the target.

learning rate \alpha
How far you step toward each new target. At 0.5 you close half the error per visit. At 1.0 you overwrite the old value entirely.
discount \gamma
How much future reward is worth now. At \gamma = 0.9, a reward two steps away counts for 0.9^2 = 0.81 of its face value.
exploration \varepsilon
The chance of taking a random action instead of the greedy one, so the agent keeps sampling paths it currently thinks are worse.

The key word is \max. The target uses the best next action regardless of what the agent actually does next. That makes Q-learning off-policy: it learns the value of the greedy path even while it wanders randomly to explore. Its on-policy cousin SARSA plugs in the action actually taken, which is why SARSA plays safer on the cliff.

A worked example on a five-cell line

To check the arithmetic by hand, shrink the world to one row of five cells, numbered 0 to 4. Cell 4 is the goal and pays +1. Every step costs -0.04. Use \alpha = 0.5, \gamma = 0.9. Actions are left and right. All Q values start at 0.

Backing up value from the goal

  1. The agent is in cell 3 and moves right into the goal (cell 4). Reward is -0.04 + 1 = 0.96 for entering the goal, and the goal is terminal so \max_{a'} Q(4, \cdot) = 0. Target = 0.96 + 0.9 \times 0 = 0.96. Update: Q(3,\text{right}) \leftarrow 0 + 0.5(0.96 - 0) = 0.48.
  2. Next episode, in cell 2 the agent moves right to cell 3. Reward is -0.04. Best next value is \max Q(3,\cdot) = 0.48. Target = -0.04 + 0.9 \times 0.48 = 0.392. Update: Q(2,\text{right}) \leftarrow 0 + 0.5(0.392) = 0.196.
  3. The agent visits cell 3 again and moves right into the goal. Target is again 0.96. Update: Q(3,\text{right}) \leftarrow 0.48 + 0.5(0.96 - 0.48) = 0.72.

Notice the value seeps backward one cell per visit. The goal cell learns first, then its neighbor, then the neighbor's neighbor. Given enough episodes, Q(3,\text{right}) converges toward 0.96, and Q(2,\text{right}) toward -0.04 + 0.9 \times 0.96 = 0.824.

The chart below shows the fully converged right-action value per cell, computed as Q(i) = -0.04 + 0.9\,Q(i+1) anchored at the goal. This is exactly the fading gradient the heatmap paints.

Value is highest next to the goal and fades with distance, because each step back multiplies by \gamma = 0.9 and subtracts the step cost.

Watching value spread as episodes accumulate

Because value backs up one cell per successful visit, the number of episodes controls how far the signal has reached. Early on, only cells near the goal are warm. Later, the whole reachable grid warms up and the arrows stop flickering.

On the five-cell line with \alpha = 0.5, \gamma = 0.9 and step cost 0.04, after 1 successful pass only cell 3 holds value (0.48), after 2 passes cell 3 reaches 0.72 and cell 2 reaches 0.196, and after roughly 15 passes every cell sits near its converged value of 0.647, 0.741, 0.824, 0.960.

Reading the heatmap, arrows and raw numbers

The tool gives you four views of the same table. Use them together.

  • Heatmap: each cell colored by \max_a Q(s,a). A smooth warm-to-cool gradient pointing toward the goal means learning is progressing. Isolated warm cells far from the goal usually mean a lucky path that has not yet spread.
  • Policy arrows: the greedy action per cell. When arrows form a consistent flow into the goal with no loops, the policy has stabilized.
  • Raw Q numbers: the four action values per cell. Toggle these to confirm the arrow really reflects a clear winner and not a near-tie.
  • Visit counts: how often each cell was entered. Cells with very low counts have unreliable values, because their entries were updated only a handful of times.

The reward-per-episode chart is your convergence signal. It rises from deeply negative (the agent wandering and paying step costs) toward a plateau near the best achievable return. On the cliff walk that plateau reflects the short edge path, which earns more than the safe detour because it takes fewer steps.

Common mistakes

Setting \varepsilon = 0 from the start is the classic trap. With no exploration the agent commits to the first rewarding path it stumbles on and never tests alternatives. The reward chart flatlines early at a mediocre level. Start high, near \varepsilon = 0.3, and decay toward a small floor.

A learning rate that is too high makes values thrash. At \alpha = 1.0 each update overwrites the entry, so a single unlucky exploratory step near the cliff can wipe out a good value. Values then bounce and the arrows flicker episode to episode. Lowering \alpha to 0.1 or 0.2 averages over more experience and smooths the table.

Setting \gamma = 1 in a grid with no penalty removes any pressure to reach the goal quickly, so many different paths score the same and the arrows wander. A step penalty of -0.04 or a discount below 1 breaks the tie in favor of short paths. Finally, do not read a cell's value before it has been visited enough times: an entry touched twice carries almost no information, whatever color it happens to show.

Frequently asked questions

Why does Q-learning learn the risky cliff-edge path?

Because the update target uses \max_{a'} Q(s',a'), the best future action, not the random one exploration might take. It evaluates the greedy edge path as short and therefore high value, and it learns that value even while it occasionally falls in during exploration. SARSA, which uses the action actually taken, folds in those exploratory falls and prefers the safe detour.

How many episodes do I need?

Enough that value has spread from the goal to the start and the reward curve has plateaued. On a small grid that is often a few hundred episodes. Watch the reward-per-episode chart: when it stops rising and levels off, you are close to convergence.

What is the difference between Q-learning and a bandit?

A bandit has a single state, so there is no s' and no discounting: you only estimate the value of each fixed action. Q-learning adds state transitions and future value, which is why the \gamma \max Q(s') term appears.

Does the starting value of the table matter?

The tool starts every entry at 0. Optimistic initial values (starting high) encourage early exploration because untried actions look attractive until visited. With \varepsilon-greedy exploration already in place, the starting value mostly affects the first few episodes and washes out as updates accumulate.