Velamuvi AIAcademy

Lesson 8 of 12 · Classic Methods

Solving a Grid World

Build a GridWorld class in Python with walls, traps and a slippery floor, solve it with value iteration and Q-learning, and use reward shaping safely.

  • 16 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Build a GridWorld environment class with walls, traps, a goal and optional slippery moves
  • Solve it by planning with value iteration and by learning with Q-learning, and compare the two
  • Print a policy as arrows and explain how a slippery floor changes it
  • Use reward shaping safely, and spot a bonus that an agent can farm

The task

A warehouse robot must drive from its charging dock (S) to a packing station (G). Shelves (#) block some cells, and there are open hatches in the floor (T, for trap): a robot that drives into one is stuck, and the run is over. Sometimes the floor is wet, and then the robot can slide sideways.

. . . . . . . .
. # # # # # # .
. # T T T T # .
S . . . . . . G
. # T T T T # .
. . . # . . . .

Every move costs −1, reaching G earns +10 and falling into a trap −10. Both G and T end the episode, and the discount factor is γ = 0.95. There are two sensible routes: the bridge along the middle row, 7 moves with traps on both sides, and the long way round the top, 13 moves with shelves between the robot and the traps. You'll build the world as a class, solve it by planning and by learning, see what a wet floor changes, and find out how a "helpful" extra reward can backfire.

Step 1: the GridWorld class

The class, at the top of both programs below, has two faces:

  • reset() and step(action) are what an agent experiences: it moves, then sees its new position, the reward and whether the episode is over. Gymnasium, the standard Python library of RL environments, uses the same two methods, and they are all Q-learning needs.
  • outcomes(position, action) is the model: every result an action can have, with its probability. Value iteration needs it.

With slip=0.2 the floor is wet: 80% of the time the robot moves the way it wants, and 10% of the time each it slides to the left or to the right of that direction. Walls and the edge of the map block a move, so the robot stays put and still pays −1.

Step 2: solve it by planning and by learning

Value iteration uses the model to work out the value of every cell, applying the Bellman equation from Value Functions again and again:

repeat until no value changes:
    for every cell s and every action a:
        Q(s, a) = Σ over the outcomes of  probability × (reward + γ × V(next cell))
    V(s) = the largest Q(s, a)
the policy: in every cell, take the action with the largest Q(s, a)

Each repetition is a sweep: the first sweep gets the goal's neighbours right, the second the cells two moves away, and so on. Q-learning, from Q-Learning, never looks at the model: it only calls reset and step, and updates one Q-value after every real move. The program solves the dry floor both ways, then solves the wet floor both ways and tests every policy on it:

Try it yourselfPython
import numpy as np

class GridWorld:
    """S start, G goal (+10), T trap (-10), # wall. Every other move costs 1."""
    MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]                     # up, right, down, left

    def __init__(self, layout, slip=0.0, seed=0):
        self.layout, self.slip, self.rng = layout, slip, np.random.RandomState(seed)
        self.rows, self.cols = len(layout), len(layout[0])
        self.cells = [(r, c) for r in range(self.rows) for c in range(self.cols)]
        self.start = next(p for p in self.cells if self.kind(p) == "S")

    def kind(self, pos):                                            # "S", ".", "#", "T" or "G"
        return self.layout[pos[0]][pos[1]]

    def move(self, pos, a):                                         # -> (new position, reward, done)
        r, c = pos[0] + self.MOVES[a][0], pos[1] + self.MOVES[a][1]
        if not (0 <= r < self.rows and 0 <= c < self.cols) or self.layout[r][c] == "#":
            r, c = pos                                              # walls and edges block a move
        return (r, c), {"G": 10, "T": -10}.get(self.layout[r][c], -1), self.layout[r][c] in "GT"

    def outcomes(self, pos, a):                                     # the model: [(probability, result)]
        sideways = [((a + 1) % 4, self.slip / 2), ((a + 3) % 4, self.slip / 2)] if self.slip else []
        return [(p, self.move(pos, b)) for b, p in [(a, 1 - self.slip)] + sideways]

    def reset(self):
        self.pos = self.start
        return self.pos

    def step(self, a):                                              # a real move: it may slip sideways
        if self.rng.rand() < self.slip:
            a = (a + 1 + 2 * self.rng.randint(2)) % 4
        self.pos, reward, done = self.move(self.pos, a)
        return self.pos, reward, done

LAYOUT = ["........",
          ".######.",
          ".#TTTT#.",
          "S......G",
          ".#TTTT#.",
          "...#...."]

def value_iteration(env, gamma=0.95):
    V = np.zeros((env.rows, env.cols))
    for sweep in range(1, 1000):
        Q = np.zeros((env.rows, env.cols, 4))
        for pos in env.cells:
            if env.kind(pos) not in "#TG":                          # walls and end cells: no decisions
                for a in range(4):                                  # expected reward + discounted value
                    Q[pos][a] = sum(p * (r + gamma * V[nxt] * (not done))
                                    for p, (nxt, r, done) in env.outcomes(pos, a))
        if np.abs(Q.max(axis=2) - V).max() < 1e-6:                  # stop when the values settle
            return V, Q.argmax(axis=2), sweep
        V = Q.max(axis=2)

def q_learning(env, episodes, alpha=0.5, gamma=0.95, eps=0.1, seed=0):
    rng, Q, moves = np.random.RandomState(seed), np.zeros((env.rows, env.cols, 4)), 0
    for _ in range(episodes):
        pos, done = env.reset(), False
        while not done:
            a = rng.randint(4) if rng.rand() < eps else int(np.argmax(Q[pos]))
            nxt, r, done = env.step(a)                              # real experience, no model
            target = r if done else r + gamma * Q[nxt].max()
            Q[pos][a] += alpha * (target - Q[pos][a])
            pos, moves = nxt, moves + 1
    return Q, moves

def arrows(env, policy):                                            # the policy as text, row by row
    return [" ".join(k if k in "#TG" else "↑→↓←"[policy[r, c]] for c, k in enumerate(row))
            for r, row in enumerate(env.layout)]

def evaluate(env, choose, episodes=1000):                          # run episodes, count the endings
    goals = traps = total = 0
    for _ in range(episodes):
        pos, done, moves = env.reset(), False, 0
        while not done and moves < 100:
            pos, reward, done = env.step(choose(pos))
            total, moves = total + reward, moves + 1
        goals, traps = goals + (env.kind(pos) == "G"), traps + (env.kind(pos) == "T")
    return goals / episodes, traps / episodes, total / episodes

# ---- 1. A dry floor: plan with value iteration, learn with Q-learning ----
env = GridWorld(LAYOUT, seed=1)
V, planned, sweeps = value_iteration(env)
print(f"Value iteration: values after {sweeps} sweeps")
for r, row in enumerate(LAYOUT):
    print(" ".join(f"{k:>5}" if k in "#TG" else f"{V[r, c]:5.1f}" for c, k in enumerate(row)))
Q, moves = q_learning(env, episodes=300)
learned = Q.argmax(axis=2)
print("\nvalue iteration    Q-learning")
for a, b in zip(arrows(env, planned), arrows(env, learned)):
    print(a + "    " + b)
free = [p for p in env.cells if env.kind(p) in "S."]
print(f"\nsame action in {sum(planned[p] == learned[p] for p in free)} of {len(free)} cells")
print(f"value of the start: {V[env.start]:.2f} planned, {Q[env.start].max():.2f} learned")
print(f"cost: {sweeps} sweeps through the model, or {moves} real moves")

# ---- 2. A wet floor: plan again, then test both plans on it ----
wet = GridWorld(LAYOUT, slip=0.2, seed=2)
_, wet_plan, _ = value_iteration(wet)
Q_wet, moves = q_learning(GridWorld(LAYOUT, slip=0.2, seed=1), episodes=3000, alpha=0.1)
print("\nvalue iteration    Q-learning      (both on a wet floor)")
for a, b in zip(arrows(wet, wet_plan), arrows(wet, Q_wet.argmax(axis=2))):
    print(a + "    " + b)
print(f"Q-learning needed 3,000 episodes and {moves} real moves")
rng = np.random.RandomState(1)
print("\nTested on the wet floor, 1,000 episodes each:")
for name, choose in [("random moves", lambda pos: rng.randint(4)), ("dry plan", lambda pos: planned[pos]),
                     ("wet plan", lambda pos: wet_plan[pos]), ("Q-learning", lambda pos: np.argmax(Q_wet[pos]))]:
    goal, trap, reward = evaluate(wet, choose)
    print(f"  {name:<13} goal {goal:4.0%}   trap {trap:4.0%}   average reward {reward:6.2f}")
Output
Value iteration: values after 12 sweeps
 -1.1  -0.1   1.0   2.1   3.2   4.4   5.7   7.1
 -0.1     #     #     #     #     #     #   8.5
  1.0     #     T     T     T     T     #  10.0
  2.1   3.2   4.4   5.7   7.1   8.5  10.0     G
  1.0     #     T     T     T     T     #  10.0
 -0.1  -1.1  -2.0     #   4.4   5.7   7.1   8.5

value iteration    Q-learning
→ → → → → → → ↓    → ← ↓ ← ↓ → → ↓
↓ # # # # # # ↓    ↑ # # # # # # ↓
↓ # T T T T # ↓    ↓ # T T T T # ↓
→ → → → → → → G    → → → → → → → G
↑ # T T T T # ↑    ↑ # T T T T # ↑
↑ ← ← # → → → ↑    ↓ ← ← # ↑ ↑ ↑ ↑

same action in 19 of 28 cells
value of the start: 2.05 planned, 2.05 learned
cost: 12 sweeps through the model, or 2609 real moves

value iteration    Q-learning      (both on a wet floor)
→ → → → → → → ↓    → → → → → → → ↓
↑ # # # # # # ↓    ↑ # # # # # # ↓
↑ # T T T T # ↓    ↑ # T T T T # ↓
↑ → → → → → → G    ↑ → → → → → → G
↑ # T T T T # ↑    ↑ # T T T T # ↑
↑ ← ← # → → → ↑    ↑ ↓ → # ↑ ↑ ↑ ↑
Q-learning needed 3,000 episodes and 49168 real moves

Tested on the wet floor, 1,000 episodes each:
  random moves  goal   3%   trap  81%   average reward -47.27
  dry plan      goal  39%   trap  61%   average reward  -7.36
  wet plan      goal  94%   trap   6%   average reward  -5.46
  Q-learning    goal  94%   trap   6%   average reward  -5.57

On a dry floor

The values fall step by step away from the goal, because each extra move costs 1 and the future is discounted by 0.95: 10.0 next to the goal, then 8.5, 7.1, and so on to 2.1 at the start. From the far corners the trip costs more than the discounted +10 is worth, so their values are below zero. The policy sends the robot straight across the bridge, and every arrow follows the shortest route from its own cell.

Q-learning found the same route and the same value for the start (2.05), but it needed 2,609 real moves, where value iteration needed 12 sweeps through a model. On a real robot, that's a lot of driving. The two disagree in 9 of the 28 cells, all places that Q-learning rarely or never visited. The bottom-right corner can't even be reached from the start without passing the goal or a trap, so its Q-values are still the starting zeros, and np.argmax of four zeros picks the first action: up, straight into a trap. Value iteration sweeps every cell, so it is right everywhere.

On a wet floor

On a wet floor every move along the bridge has a 20% chance of sliding into a trap, and the plan changes: up the left side, along the top and down to the goal. (Its arrows on the bridge still point right: once the robot has slid onto the bridge, crossing beats turning back.) Tested on the wet floor, the dry plan reaches the goal only 39% of the time and ends in a trap 61% of the time, while the wet plan reaches the goal 94% of the time. Its average reward, −5.46, beats the dry plan's −7.36 even though its route is almost twice as long.

Q-learning learned the long way too, and does just as well (94%), but it needed 3,000 episodes, a smaller α of 0.1 and 49,168 real moves, because every result is now random. Same walls, same traps, a different floor, a different best policy: the right policy depends on how the world responds to actions, not just on the map.

Step 3: reward shaping and its pitfalls

On the dry floor, Q-learning spent its first episodes wandering, because the only signal was −1 per move until it stumbled onto the goal.

The program trains Q-learning for 1,000 episodes with three rewards: no bonus, the obvious bonus of +4 for every move that brings the robot closer to the goal, and a potential-based bonus, explained below. It counts the moves in the first 30 episodes, then follows each learned policy from the start:

Try it yourselfPython
import numpy as np

# ---- The GridWorld class and map from Step 2, unchanged ----
class GridWorld:
    """S start, G goal (+10), T trap (-10), # wall. Every other move costs 1."""
    MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]                     # up, right, down, left
    def __init__(self, layout, slip=0.0, seed=0):
        self.layout, self.slip, self.rng = layout, slip, np.random.RandomState(seed)
        self.rows, self.cols = len(layout), len(layout[0])
        self.cells = [(r, c) for r in range(self.rows) for c in range(self.cols)]
        self.start = next(p for p in self.cells if self.kind(p) == "S")
    def kind(self, pos):                                            # "S", ".", "#", "T" or "G"
        return self.layout[pos[0]][pos[1]]
    def move(self, pos, a):                                         # -> (new position, reward, done)
        r, c = pos[0] + self.MOVES[a][0], pos[1] + self.MOVES[a][1]
        if not (0 <= r < self.rows and 0 <= c < self.cols) or self.layout[r][c] == "#":
            r, c = pos                                              # walls and edges block a move
        return (r, c), {"G": 10, "T": -10}.get(self.layout[r][c], -1), self.layout[r][c] in "GT"
    def outcomes(self, pos, a):                                     # the model: [(probability, result)]
        sideways = [((a + 1) % 4, self.slip / 2), ((a + 3) % 4, self.slip / 2)] if self.slip else []
        return [(p, self.move(pos, b)) for b, p in [(a, 1 - self.slip)] + sideways]
    def reset(self):
        self.pos = self.start
        return self.pos
    def step(self, a):                                              # a real move: it may slip sideways
        if self.rng.rand() < self.slip:
            a = (a + 1 + 2 * self.rng.randint(2)) % 4
        self.pos, reward, done = self.move(self.pos, a)
        return self.pos, reward, done

LAYOUT = ["........",
          ".######.",
          ".#TTTT#.",
          "S......G",
          ".#TTTT#.",
          "...#...."]

env, GAMMA = GridWorld(LAYOUT), 0.95
goal = next(p for p in env.cells if env.kind(p) == "G")
distance = lambda pos: abs(pos[0] - goal[0]) + abs(pos[1] - goal[1])  # moves to the goal, ignoring walls

def no_bonus(pos, nxt): return 0.0
def closer_bonus(pos, nxt): return 4.0 if distance(nxt) < distance(pos) else 0.0   # +4 if closer
def potential(pos): return 0.0 if env.kind(pos) in "GT" else -distance(pos)       # 0 at end cells
def potential_bonus(pos, nxt): return GAMMA * potential(nxt) - potential(pos)

def q_learning(bonus, episodes=1000, alpha=0.5, eps=0.1, seed=0):
    rng, Q, lengths = np.random.RandomState(seed), np.zeros((env.rows, env.cols, 4)), []
    for _ in range(episodes):
        pos, done, moves = env.reset(), False, 0
        while not done and moves < 200:
            a = rng.randint(4) if rng.rand() < eps else int(np.argmax(Q[pos]))
            nxt, r, done = env.step(a)
            r += bonus(pos, nxt)                                    # the shaped reward
            target = r if done else r + GAMMA * Q[nxt].max()
            Q[pos][a] += alpha * (target - Q[pos][a])
            pos, moves = nxt, moves + 1
        lengths.append(moves)
    return Q, lengths

def route(Q, max_moves=16):                                         # follow the greedy policy from the start
    pos, path, done = env.start, "", False
    while not done and len(path) < max_moves:
        a = int(np.argmax(Q[pos]))
        path, (pos, _, done) = path + "↑→↓←"[a], env.move(pos, a)
    return path + (" reaches " + env.kind(pos) if done else " ... never arrives")

print(f"{'bonus':<16}{'moves in episodes 1-30':>23}   greedy route after 1,000 episodes")
for name, bonus in [("none", no_bonus), ("+4 if closer", closer_bonus), ("potential-based", potential_bonus)]:
    Q, lengths = q_learning(bonus)
    print(f"{name:<16}{sum(lengths[:30]):>23}   {route(Q)}")
Output
bonus            moves in episodes 1-30   greedy route after 1,000 episodes
none                                686   →→→→→→→ reaches G
+4 if closer                        394   →→→→→→←→←→←→←→←→ ... never arrives
potential-based                     230   →→→→→→→ reaches G

The +4 bonus speeds up the first episodes (394 moves instead of 686), but the finished policy drives to the cell next to the goal and then dances back and forth forever. Driving into the goal from there earns 10 + 4 = 14 and ends the episode. Stepping back (−1) and forward again (−1 + 4 = +3) earns about 2 and returns the robot to the same cell, ready to do it again. With γ = 0.95, dancing forever is worth about 19, more than the 14 for finishing. The agent did exactly what the reward asked for, and nothing the designer wanted.

The potential-based bonus gives every cell a score Φ, here minus its distance to the goal (and 0 in the goal and the traps), and rewards the change in score:

bonus for a move from s to s' = γ × Φ(s') − Φ(s)

Moving closer earns a little and moving away costs a little, so a loop gains nothing. Over a whole episode the discounted bonuses add up to −Φ(start), the same for every route, so they can't change which route is best: Andrew Ng, Daishi Harada and Stuart Russell proved in 1999 that shaping of this form never changes the optimal policy. It still points the agent the right way from the start: 230 moves instead of 686, and the same route as with no bonus. Two more pitfalls:

  • Rewarding a stand-in for the goal. A bonus for speed or distance covered can teach the agent to chase the stand-in and ignore the real task, a form of reward hacking that Where RL Is Used returns to.
  • Watching only the shaped reward. It can rise while the agent gets worse at the real task. Always measure the real result too, such as how often the goal is reached.

Plan or learn?

Value iteration (planning)Q-learning (learning)
Needsthe model: every outcome and its probabilityonly the ability to act and see what happens
Cost here12 sweeps through the model2,609 real moves, and 49,168 on the wet floor
Resultthe best action in every cell, even unreachable onesgood actions where it explored, guesses elsewhere
Scales tosmall worlds with a known modelunknown worlds, and huge ones with a neural network

When a trustworthy model exists, such as a game's rules or a good simulator, planning is often far cheaper than trial and error. Usually the model is unknown or too big to sweep, which is why learning methods dominate RL.

Limitations and next steps

  • Tables don't scale. A table needs a row for every state, and a warehouse with several robots, doors and parcels has far too many. Deep Q-Networks, next, replaces the table with a neural network.
  • Models can be wrong. If the real slip rate is 40%, not 20%, the "safe" plan was made for the wrong world. Measure the model, or learn without one.
  • Experiment. Change the map, the slip, γ or the trap reward, and predict the new policy before you run the program.

Common mistakes

Practice

Practice exercise

Run value iteration on a corridor with a small goal at one end and a big goal at the other. Fill in the values of moving left and right, then print the four floor values and the policy.

Your solutionPython
import numpy as np

# A corridor of 6 cells. Cell 0 is a small goal (+5) and cell 5 a big goal (+10):
# arriving at either ends the episode. Cells 1 to 4 are floor, and moving onto floor costs 1.
reward = [5, -1, -1, -1, -1, 10]
gamma = 0.9
V = np.zeros(6)                         # the goals keep V = 0: nothing comes after them

for sweep in range(50):
    new_V = V.copy()
    for s in range(1, 5):
        # The value of moving to cell n is reward[n] + gamma x V[n]. Compute it for
        # moving left (to s - 1) and right (to s + 1), and keep the larger one.
        go_left = 0.0
        go_right = 0.0
        new_V[s] = max(go_left, go_right)
    V = new_V

policy = ["←" if reward[s - 1] + gamma * V[s - 1] > reward[s + 1] + gamma * V[s + 1] else "→"
          for s in range(1, 5)]
print("values:", " ".join(f"{v:.2f}" for v in V[1:5]))
print("policy:", " ".join(policy))
Knowledge check

With a bonus of +4 for every move that gets closer to the goal, the robot learned to step back and forth next to the goal instead of finishing. What is the root cause?

Summary

  • An environment class needs reset and step for learning agents; a model, such as outcomes listing every result with its probability, makes planning possible.
  • Value iteration plans with the model and gets every cell right in a few sweeps; Q-learning needs no model, but thousands of real moves, and only knows the places it explored.
  • A slippery floor changes the best policy: the wet plan takes the long, safe way and reaches the goal 94% of the time, against 39% for the dry plan.
  • Reward shaping can speed learning up, but a bonus that can be collected repeatedly gets farmed; potential-based shaping, γ × Φ(s') − Φ(s), is safe.

Next: Deep Q-Networks.

Finished reading? Tick it off to track your progress.