Home › Theme A › A4 › A4.3 › A4.3.6

A4.3.6 Learning by reward: reinforcement learning

HL onlyCommand term: Describe

1. The agent–environment loop

In reinforcement learning (RL) nobody gives the agent the right answers. It learns by trial and error: act, see what happens, get a reward, adjust. Click Next.

2. Be the agent: maximise cumulative reward

You are the penguin. Each move on the cold ice costs −1. Reaching the small fish gives +3, the big feast gives +15, and falling in a hole gives −10. Each of these ends the episode. Aim for the highest total reward, not just the nearest prize.

Choose an action:

3. Exploration vs exploitation

You have 20 lunches at a new canteen with 4 food stalls. Each meal gives a satisfaction score (0–10), but every stall is a bit random and you don't know which is best. Click a stall to eat there. Should you keep trying new stalls (explore) or stick with the best so far (exploit)?

Compare strategies (each played for 300 lunches, averaged over 300 simulations)

ε-greedy: with probability ε pick a random stall (explore); otherwise pick the stall with the best average so far (exploit). ε =

4. Spot the RL components: a self-driving car

Score: 0 /

ShelfWise AI · Hands-on lab A4.3.6: A robot learns its way to the returns desk. ShelfWise is testing a small robot that carries returned books. It must learn the best route from the entrance to the returns desk, avoiding shelves and a wet floor, without being told the map.

In this lab you practise states, actions, rewards, the Q-learning update, cumulative reward and exploration versus exploitation. Work through the sections in order: run it, read it, change it, then extend it.

1. Set up in PyCharm

  1. Open PyCharm and choose New Project (a pure Python project; any recent Python 3 works). Name it shelfwise_ai.
  2. Right-click the project folder → New → Python File, and give it the file name shown below.
  3. Press Copy code below and paste it into the empty file (or press Download .py and drag the file into the project).
  4. Right-click inside the editor and choose Run (Windows Shift+F10, Mac Ctrl+R). The output appears in the Run window at the bottom.
  5. No extra libraries are needed: the lab uses only Python's built-in modules, so you can see exactly how the algorithm works.

2. Copy and run the program

File: lab_a4_3_6.py
# ShelfWise AI - Lab A4.3.6: a robot learns its way to the returns desk (Q-learning)
import random

EPISODES = 500    # practice runs
ALPHA = 0.5       # learning rate: how much each new experience changes the Q-value
GAMMA = 0.9       # discount: how much future reward matters
EPSILON = 0.2     # exploration: chance of a random move
random.seed(0)

# S = start (entrance), D = returns desk (+10), # = shelf (cannot enter), W = wet floor (-5)
MAP = ["S...#",
       ".##.#",
       "..W..",
       "#.#.#",
       "....D"]
ROWS, COLS = len(MAP), len(MAP[0])
MOVES = {"^": (-1, 0), "v": (1, 0), "<": (0, -1), ">": (0, 1)}
start = (0, 0)
Q = {(r, c): {a: 0.0 for a in MOVES} for r in range(ROWS) for c in range(COLS)}

def step(state, action):
    r, c = state[0] + MOVES[action][0], state[1] + MOVES[action][1]
    if not (0 <= r < ROWS and 0 <= c < COLS) or MAP[r][c] == "#":
        return state, -1, False                      # bumped into a wall or shelf
    cell = MAP[r][c]
    if cell == "D":
        return (r, c), 10, True
    return (r, c), (-5 if cell == "W" else -1), False

def choose(state, explore=True):
    if explore and random.random() < EPSILON:
        return random.choice(list(MOVES))
    best = max(Q[state].values())
    return random.choice([a for a, q in Q[state].items() if q == best])

for ep in range(1, EPISODES + 1):
    state, total, done, steps = start, 0, False, 0
    while not done and steps < 100:
        action = choose(state)
        nxt, reward, done = step(state, action)
        target = reward if done else reward + GAMMA * max(Q[nxt].values())
        Q[state][action] += ALPHA * (target - Q[state][action])      # the Q-learning update
        state, total, steps = nxt, total + reward, steps + 1
    if ep in (1, 10, 50, 100, EPISODES):
        print(f"episode {ep:4}: {steps:3} steps, cumulative reward {total:4}")

print("\nLearned policy (best move in each square):")
for r in range(ROWS):
    row = ""
    for c in range(COLS):
        cell = MAP[r][c]
        row += f" {cell} " if cell in "#D" else f" {max(Q[(r, c)], key=Q[(r, c)].get)} "
    print("   " + row)

state, path, done = start, [start], False
while not done and len(path) < 30:
    state, _, done = step(state, choose(state, explore=False))
    path.append(state)
print(f"\nGreedy route from the entrance: {len(path) - 1} moves, avoids the wet floor: {(2, 2) not in path}")

3. Expected output

The program uses a fixed random seed, so with the same settings you should see exactly this output.

episode    1:  97 steps, cumulative reward  -94
episode   10:  21 steps, cumulative reward  -10
episode   50:   8 steps, cumulative reward    3
episode  100:  10 steps, cumulative reward    1
episode  500:  11 steps, cumulative reward   -4

Learned policy (best move in each square):
    >  >  >  v  # 
    v  #  #  v  # 
    >  v  >  v  < 
    #  v  #  v  # 
    >  >  >  >  D 

Greedy route from the entrance: 8 moves, avoids the wet floor: True

4. Read the output

Answer each question from your own output before you open the answer.

How does the cumulative reward change between episode 1 and later episodes?
Episode 1 wanders for 97 steps with reward -94. By episode 50 it takes 8 steps with reward +3. The agent has learned from rewards.
Why is the reward -1 for every ordinary step?
It makes long routes costly, so the agent learns the shortest route. The -5 wet floor teaches it to avoid that square, and +10 at the desk is the goal.
Why do later episodes sometimes take more than 8 steps?
EPSILON = 0.2 means 20% of moves are random exploration, even after learning. The greedy route at the end (no exploration) uses 8 moves.

5. Change it and predict

For each change: write down your prediction first, then edit the setting at the top of the program, run it, and compare. Change the setting back before the next task.

Task 1. Change EPSILON = 0.2 → EPSILON = 0.0
Set EPSILON = 0.0. Does the robot still learn?

Check your prediction

Yes, in this small map: Q-values start at 0, and every step costs -1, so untried moves look better than tried ones and the agent explores anyway. In bigger problems pure exploitation often gets stuck on a poor route.

Output with this change:

episode    1:  47 steps, cumulative reward  -44
episode   10:  14 steps, cumulative reward   -3
episode   50:   8 steps, cumulative reward    3
episode  100:   8 steps, cumulative reward    3
episode  500:   8 steps, cumulative reward    3

Learned policy (best move in each square):
    >  >  >  v  # 
    v  #  #  v  # 
    >  v  ^  v  ^ 
    #  v  #  v  # 
    ^  >  >  >  D 

Greedy route from the entrance: 8 moves, avoids the wet floor: True

Task 2. Change EPISODES = 500 → EPISODES = 20
Set EPISODES = 20. Is that enough training?

Check your prediction

Here the greedy route is already 8 moves after 20 episodes, but the early episodes were long and costly. More complex environments need many more episodes.

Output with this change:

episode    1:  97 steps, cumulative reward  -94
episode   10:  21 steps, cumulative reward  -10
episode   20:   9 steps, cumulative reward    2

Learned policy (best move in each square):
    >  >  >  v  # 
    v  #  #  v  # 
    >  v  >  v  < 
    #  v  #  v  # 
    >  >  >  >  D 

Greedy route from the entrance: 8 moves, avoids the wet floor: True

Task 3. Change GAMMA = 0.9 → GAMMA = 0.1
Set GAMMA = 0.1. What does a small discount factor mean?

Check your prediction

The agent cares mostly about immediate rewards. It still finds the desk here because the map is small, but the first episodes are longer (100 steps): the +10 reward hardly propagates back to early squares, so learning is slower.

Output with this change:

episode    1: 100 steps, cumulative reward -108
episode   10:  31 steps, cumulative reward  -20
episode   50:   8 steps, cumulative reward    3
episode  100:   8 steps, cumulative reward    3
episode  500:   8 steps, cumulative reward    3

Learned policy (best move in each square):
    v  >  >  v  # 
    v  #  #  v  # 
    >  v  >  v  < 
    #  v  #  v  # 
    >  >  >  >  D 

Greedy route from the entrance: 8 moves, avoids the wet floor: True

6. Extended activity: Design a harder library for the robot

A longer project for homework or a double lesson. Save it as a new file so you keep the original.

  1. Make the map 8 x 8 with more shelves and two wet floors. Add a 'quiet zone' square with reward -2.
  2. Track the cumulative reward of every episode and print an average every 50 episodes. When does it level off?
  3. Compare three exploration strategies: EPSILON fixed at 0.2, EPSILON = 0, and EPSILON that starts at 1.0 and decreases each episode.
  4. Write a paragraph applying exploration vs exploitation to another situation, such as a recommender system choosing which books to suggest.

Success criteria

  • Your map is solved and the route printed.
  • The three exploration strategies are compared with numbers.
  • Your paragraph explains the trade-off clearly.

Learning objectives

By the end of this page you should be able to:

  1. Describe how an agent interacts with its environment through states, actions and rewards.
  2. Describe what a policy is.
  3. Explain the principle of cumulative reward.
  4. Describe the trade-off between exploration and exploitation.
  5. Describe applications of reinforcement learning.

Reinforcement learning

An agent learns to make decisions by interacting with an environment through trial and error. There are no labelled answers; the only feedback is a numerical reward.

ConceptMeaningPenguin example
AgentThe learner / decision-makerThe penguin
EnvironmentEverything the agent interacts withThe icy grid
State (s)The current situation the agent observesThe penguin's square
Action (a)A choice the agent can make in a stateMove up / down / left / right
Reward (r)Immediate feedback (positive or negative) after an action−1 per move, +15 big feast, −10 hole
Policy (π)The agent's strategy: which action to take in each stateThe arrows on the grid
Cumulative reward (return)The total reward collected over time (an episode)Sum of all rewards until the episode ends

The loop

  1. The agent observes the current state.
  2. It chooses an action using its policy.
  3. The environment moves to a new state and gives a reward.
  4. The agent updates its policy (e.g. its estimate of how good each action is), then repeats.

Cumulative reward

The goal is to maximise the cumulative (total, long-term) reward, not the immediate reward. A good agent accepts small costs now (−1 per step) for a bigger reward later (+15), and avoids a quick small win (+3) if a better total is possible. Future rewards are often discounted, i.e. worth slightly less than immediate ones.

Exploration vs exploitation

  • Exploration: trying actions that may not seem best, to gain information and possibly discover better rewards.
  • Exploitation: using current knowledge to choose the action that currently looks best, to collect reward now.
  • Too much exploitation → may get stuck with a sub-optimal choice and never find the best. Too much exploration → wastes time on poor choices. Agents balance the two, e.g. ε-greedy (explore with small probability ε), often reducing exploration as they learn.

Applications

Game playing (chess, Go, video games), robotics and navigation, self-driving cars, traffic-light control, energy management in data centres, recommendation systems, trading.

Exam tip: describe the loop using all the key words: state → action (from policy) → reward + new state → update policy, with the goal of maximising cumulative reward.

Use the 中文 button at the top to show or hide the Chinese terms.

Term中文Meaning

Choose an answer. You get instant feedback.

Score: 0 /

Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

1. Describe how an agent learns in reinforcement learning. [4]

Award [1] for each, up to [4]: the agent observes the current state of the environment; it chooses an action according to its policy; the environment changes to a new state and returns a reward (positive or negative); the agent updates its policy / value estimates based on the reward; the process repeats over many episodes (trial and error); aiming to maximise cumulative reward.

2. Explain why an agent should aim to maximise cumulative reward rather than immediate reward. [2]

Actions that give the highest immediate reward may lead to poor states / lower total reward later [1]; accepting small costs / lower rewards now can lead to a much larger total reward over the whole task, e.g. sacrificing a piece in chess to win the game [1].

3. Explain the exploration versus exploitation trade-off. [4]

Exploration means trying new / less-known actions to gain information [1]; exploitation means choosing the action currently believed to give the highest reward [1]; too much exploitation may cause the agent to miss better actions it has never tried / get stuck in a sub-optimal policy [1]; too much exploration wastes time on poor actions, lowering reward; a balance such as ε-greedy is used [1].

4. A robot vacuum cleaner uses reinforcement learning. Identify a suitable state, action and reward. [3]

State: e.g. the robot's position / sensor readings / which areas are dirty / battery level [1]; action: e.g. move forward, turn left/right, return to charger [1]; reward: e.g. + for cleaning a dirty area, − for bumping into furniture / running out of battery [1].

5. Outline what is meant by a policy in reinforcement learning. [2]

A policy is the agent's strategy / mapping from states to actions [1]; it tells the agent which action to take in each state, and it is improved through learning to maximise cumulative reward [1].