Skip to content

MLDay 43 of 50Deep Learning

Reinforcement Learning Basics

A mouse in a maze gets no label saying which way to turn at each square.

8 min read

A mouse in a maze gets no label saying which way to turn at each square. It only finds out at the end, when it reaches the cheese or springs a trap. Reinforcement learning turns that late reward into a guide for every single move.

The idea

Reinforcement learning (RL) has five parts:

  • the agent, the learner that acts: the mouse;
  • the environment, the world it acts in: the maze;
  • a state, where the agent is now: one square;
  • an action, a choice it makes: up, right, down or left;
  • a reward, a number the environment pays back: +10 for cheese, −10 for a trap.

The agent wants the most reward in total, and sooner beats later. The discounted return captures both: add up the rewards, but shrink each one by a factor γ\gamma (gamma, the discount) for every step you wait.

A state's value is the return you can expect from it if you act well from then on. Once every square has a value, acting is easy: move to the neighbour with the highest value. That's acting greedily, and the move it picks in each square is the policy.

Value iteration finds the values. Start every square at 0, except the reward squares, which hold their reward. Then sweep: every other square becomes γ\gamma times the value of its best neighbour, while the reward squares keep their reward. Each sweep pushes value one square further from the rewards. Like the steps of gradient descent (D09), you repeat one update until it stops changing.

Value iteration reads the map: it knows where every move lands. A real agent often doesn't, so it must try moves to find out. Trying something new is exploration; taking the best move you know is exploitation. A mouse that only exploits may eat the same crumb forever and never find the cheese.

A tiny example

Take the maze's top row: squares A, B and C, then the cheese, worth 10. Use γ=0.9\gamma = 0.9; a move by itself pays nothing.

After sweep A B C cheese
0 0 0 0 10
1 0 0 0.9 × 10 = 9 10
2 0 0.9 × 9 = 8.1 9 10
3 0.9 × 8.1 = 7.29 8.1 9 10

A fourth sweep changes nothing, so the values have settled. The cheese loses 10% per move of distance, and the greedy policy in every square is "move right".

The formula

The discounted return adds the rewards, each shrunk once per step of waiting:

G=r1+γr2+γ2r3+…G = r_1 + \gamma r_2 + \gamma^2 r_3 + \dots
Symbol Meaning
GG the return: the total, discounted reward from now on
r1,r2,r3r_1, r_2, r_3 the rewards from the next move, the one after, and so on
γ\gamma the discount, between 0 and 1; lower means the future counts for less

Worked: rewards of 1, 1 and 1 with γ=0.9\gamma = 0.9 give G=1+0.9+0.81=2.71G = 1 + 0.9 + 0.81 = 2.71.

The Bellman update is one sweep's rule for one square:

V(s)←max⁡a[ r+γV(s′) ]V(s) \leftarrow \max_a \left[\, r + \gamma V(s') \,\right]
Symbol Meaning
V(s)V(s) the value of state ss
aa an action; max⁡a\max_a tries every move and keeps the best
s′s' the next state: where action aa lands
rr the reward the move itself pays (0 here: a reward square's prize sits in its value, V(s′)V(s'))
←\leftarrow "replace with"

Worked, square C: r=0r = 0 and the cheese is worth 10, so V(C)=0+0.9×10=9V(C) = 0 + 0.9 \times 10 = 9. If each move paid r=1r = 1, it would be 1+9=101 + 9 = 10.

Try it

The full maze: cheese (10) in the top-right corner, a trap (−10) below it, a crumb (1) in the bottom-left corner and a wall. Reaching any of the three ends the run.

Sweep the maze until the values settle

Coloured cells hold a reward and end the episode. Press One sweep a few times: every other cell takes γ times the value of its best neighbour, so value spreads out from the rewards. Arrows show the best move from each cell.

0.00row 0, column 0: V = 0.000.00row 0, column 1: V = 0.000.00→row 0, column 2: V = 0.00, best move right10.00row 0, column 3: V = 10.00 (reward, ends here)0.00row 1, column 0: V = 0.00row 1, column 1: wall0.00↑row 1, column 2: V = 0.00, best move up-10.00row 1, column 3: V = -10.00 (reward, ends here)0.00↓row 2, column 0: V = 0.00, best move down0.00row 2, column 1: V = 0.000.00row 2, column 2: V = 0.000.00→row 2, column 3: V = 0.00, best move right1.00row 3, column 0: V = 1.00 (reward, ends here)0.00←row 3, column 1: V = 0.00, best move left0.00row 3, column 2: V = 0.000.00row 3, column 3: V = 0.00

sweeps 0biggest change last sweep –

Run keeps sweeping until no value moves. Lower γ and run again: far-away rewards count for less.

Press One sweep six times. For three sweeps, the two squares beside the crumb point at it. On the fourth, the cheese's value reaches their neighbours, and both arrows turn away from the crumb. The sixth sweep changes nothing. Then drag γ to 0.5 and press Run. Now the cheese, five moves away, is worth only 0.55×10≈0.310.5^5 \times 10 \approx 0.31, less than the crumb's 0.5, so those two squares settle for the crumb.

In code

Value iteration on the same maze in NumPy. A move that hits the wall or the edge leaves the mouse in place.

# script_id: day_043_reinforcement_learning_basics/value_iteration
import numpy as np

rewards = {(0, 3): 10.0, (1, 3): -10.0, (3, 0): 1.0}  # cheese, trap, crumb: each ends the run
wall, gamma = (1, 1), 0.9
moves = {"↑": (-1, 0), "→": (0, 1), "↓": (1, 0), "←": (0, -1)}


def land(r, c, dr, dc):
    nr, nc = r + dr, c + dc
    inside = 0 <= nr < 4 and 0 <= nc < 4 and (nr, nc) != wall
    return (nr, nc) if inside else (r, c)


V = np.zeros((4, 4))
for cell, reward in rewards.items():
    V[cell] = reward
free = [s for s in np.ndindex(4, 4) if s not in rewards and s != wall]
for sweep in range(1, 100):
    new = V.copy()
    for r, c in free:                                 # Bellman update, with r = 0 per move
        new[r, c] = max(0 + gamma * V[land(r, c, *d)] for d in moves.values())
    change, V = np.abs(new - V).max(), new
    if change < 1e-4:
        break

policy = {(r, c): max(moves, key=lambda m: V[land(r, c, *moves[m])]) for r, c in free}
print(f"settled after {sweep} sweeps")
for r in range(4):
    print(" ".join(f"{V[r, c]:6.2f} {policy.get((r, c), ' ')}" for c in range(4)).rstrip())
settled after 6 sweeps
  7.29 →   8.10 →   9.00 →  10.00
  6.56 ↑   0.00     8.10 ↑ -10.00
  5.90 ↑   6.56 →   7.29 ↑   6.56 ←
  1.00     5.90 ↑   6.56 ↑   5.90 ↑

The sixth sweep is the one that changes nothing, as in the playground. The 0.00 is the wall. Every arrow leads to the cheese, and the trap's −10 never spreads: the max ignores bad moves.

The greedy policy, drawn as arrows:

# script_id: day_043_reinforcement_learning_basics/value_iteration
import os
from pathlib import Path

import matplotlib.pyplot as plt

FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
shown = V.copy()
shown[wall] = np.nan                                  # NaN cells are left blank
fig, ax = plt.subplots(figsize=(6, 4))
ax.imshow(shown, cmap="RdYlGn", vmin=-10, vmax=10)
names = {(0, 3): "cheese", (1, 3): "trap", (3, 0): "crumb", wall: ""}
for r, c in np.ndindex(4, 4):
    label = "wall" if (r, c) == wall else f"{V[r, c]:.2f}\n{policy.get((r, c)) or names[r, c]}"
    ax.text(c, r, label, ha="center", va="center", fontsize=11)
ax.set(xticks=[], yticks=[], title="With γ = 0.9, every square heads for the cheese")
fig.tight_layout()
fig.savefig(FIG_DIR / "greedy_policy.png", dpi=120)
plt.close(fig)

With γ = 0.9, every square heads for the cheese

Quick check

Quick check

1. Rewards of 2, 2 and 2 arrive on the next three moves, with γ = 0.5. What is the discounted return?

2. A square's best neighbour is worth 8, γ = 0.9 and a move pays 0. What does one Bellman update give?

3. A mouse has always eaten the nearby crumb and never tried the long path to the cheese. What is it missing?

Next

Phase 5 starts with D44: From Notebook to Reproducible, Tracked Training, which turns a training script into one command that gives the same model on every run.

Next · Day 44 · 7 minFrom Notebook to Reproducible, Tracked Training← Previous: Day 42 · Self-Supervised Learning and Foundation Models
Not tapped yet