A4.3.6 Learning by reward: reinforcement learning
HL onlyCommand term: Describe1. 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.
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 /
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
- Open PyCharm and choose New Project (a pure Python project; any recent Python 3 works). Name it
shelfwise_ai. - Right-click the project folder → New → Python File, and give it the file name shown below.
- Press Copy code below and paste it into the empty file (or press Download .py and drag the file into the project).
- Right-click inside the editor and choose Run (Windows Shift+F10, Mac Ctrl+R). The output appears in the Run window at the bottom.
- 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
# 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?
Why is the reward -1 for every ordinary step?
Why do later episodes sometimes take more than 8 steps?
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: TrueTask 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: TrueTask 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: True6. 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.
- Make the map 8 x 8 with more shelves and two wet floors. Add a 'quiet zone' square with reward -2.
- Track the cumulative reward of every episode and print an average every 50 episodes. When does it level off?
- Compare three exploration strategies: EPSILON fixed at 0.2, EPSILON = 0, and EPSILON that starts at 1.0 and decreases each episode.
- 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:
- Describe how an agent interacts with its environment through states, actions and rewards.
- Describe what a policy is.
- Explain the principle of cumulative reward.
- Describe the trade-off between exploration and exploitation.
- 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.
| Concept | Meaning | Penguin example |
|---|---|---|
| Agent | The learner / decision-maker | The penguin |
| Environment | Everything the agent interacts with | The icy grid |
| State (s) | The current situation the agent observes | The penguin's square |
| Action (a) | A choice the agent can make in a state | Move 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 state | The 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
- The agent observes the current state.
- It chooses an action using its policy.
- The environment moves to a new state and gives a reward.
- 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.
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]
2. Explain why an agent should aim to maximise cumulative reward rather than immediate reward. [2]
3. Explain the exploration versus exploitation trade-off. [4]
4. A robot vacuum cleaner uses reinforcement learning. Identify a suitable state, action and reward. [3]
5. Outline what is meant by a policy in reinforcement learning. [2]