Level 13 · ExpertLesson 13.1 42 min read 10 question quiz 12 marks of written practice

Reinforcement Learning: Learning by Trial and Error

Learning from rewards

Supervised learning needs the right answer for every example. Reinforcement learning (RL) needs only a score. An agent acts in an environment, sees what happens, and receives a reward, and over many attempts it learns which actions lead to the most reward.

The reinforcement learning loopA robot, the agent, and a small maze, the environment, with a star as the goal. Arrows loop between them: the agent sends an action, move right; the environment sends back the new state, one cell further on, and a reward, minus 0.1 for an ordinary step and plus 10 at the star. The loop repeats for every step of every episode.Reinforcement learning: act, see what happens, collect a rewardthe agentthe environmentaction: move rightnew state: one cell further onreward: −0.1 now, +10 at the star
No one tells the agent the right move: it learns from the rewards alone.
TermMeaningIn a video game
StateThe situation the agent is inThe screen at this moment
ActionWhat the agent can doLeft, right, jump
RewardA number after each actionPoints scored
EpisodeOne attempt, from start to finishOne game
PolicyThe agent's rule for choosing actionsIts playing strategy

Nobody tells the agent which action was right. It has to work out which of its earlier actions deserve the credit for a reward that may arrive much later, the credit assignment problem.

Returns and discounting

The agent's aim is to maximise its return: the total reward from now on. Rewards further in the future are usually discounted by a factor γ (gamma) between 0 and 1 for every step of delay:

Discounted return

G = r1 + γ × r2 + γ2 × r3 + γ3 × r4 + …

Discounting future rewardsPaired bars show what a reward of 10 is worth today if it arrives on step 1 to 7. With gamma 0.9, in violet: 10, 9, 8.1, 7.29, 6.56, 5.9 and 5.31, a slow decline. With gamma 0.5, in pink: 10, 5, 2.5, 1.25, 0.63, 0.31 and 0.16, falling away fast.Discounting: a reward of 10, worth less the longer you wait for it02.557.510101019528.12.537.291.2546.560.6255.90.3165.310.167the step on which the reward arrivesγ = 0.9patientγ = 0.5short-sighted
Each step of delay multiplies the reward by γ once more.

With γ = 0.9, a reward of 10 that arrives four steps from now is worth 10 × 0.93 = 7.29 today. Discounting makes sooner rewards worth more, reflects that the future is uncertain, and keeps the sum finite in tasks that never end. A γ near 0 makes a short-sighted agent; a γ near 1, a patient one.

Policies and values

A policy says what to do in each state. To find a good one, RL estimates how good each state is:

  • The value of a state, V(s), is the return the agent can expect from there, if it then acts well.
  • The action value, Q(s, a), is the return it can expect if it takes action a in state s first.

Once the values are known, a good policy is simply: in every state, take the action that leads to the highest value.

Values in a grid worldA 4 by 5 grid world. The goal G, worth plus 10, is at the top right and a trap X, minus 10, is just below it; grey cells are walls; S is the start at the bottom left. Each open cell shows its value from value iteration, with gamma 0.9 and a cost of 0.1 per step, and an arrow for the best move. Values are highest beside the goal, 10.0, and lowest far from it, 4.8 at the start. From S the arrows lead up the left side and along the top row to G, avoiding X.Values and the policy they give: every arrow points uphill in value7.07.98.910.0+106.27.9−105.56.27.06.25.54.8S6.25.54.8Reach G: +10. Fall into X: −10.Every other step: −0.1. γ = 0.9.Bright cells are worth more:they are closer to the goal.From S the arrows lead up theleft side and along the top,keeping away from X.
Computed by value iteration with the same rules as the lesson's Python.

In this grid world, reaching G pays +10, falling into X costs −10, and every other step costs 0.1, so the agent prefers short routes. Values are highest next to the goal and fall away with distance, and the arrows, which simply point uphill in value, steer clear of the trap.

The Bellman equation

In 1957 Richard Bellman noticed that a state's value can be written in terms of its neighbours' values:

Bellman equation

V(s) = the best, over all actions, of (reward for the move + γ × V(next state))

That turns finding values into a repeated sum. Value iteration starts with every value at 0 and applies the equation to every state, again and again, until the values stop changing. Information about the reward spreads backwards one step per sweep.

Value iteration in a corridorA stepped corridor of five cells leading to a goal that pays 10 when entered, with gamma 0.9. Every value starts at 0. Sweep 1: the cell next to the goal becomes 10. Sweep 2: the cell before it becomes 9. Sweep 3: 8.1. Sweep 4: 7.29. Sweep 5: the first cell becomes 6.56. Each sweep carries the reward one cell further back, shown by an amber arrow.Value iteration: each sweep carries the reward one more cell backgoalentering pays 10V(cell) = 0.9 × V(next cell), or 10 for the cell next to the goal000010000910008.191007.298.19106.567.298.1910
After enough sweeps the values stop changing: they satisfy the Bellman equation.

In a corridor with a reward of 10 for stepping onto the goal and γ = 0.9, the cells before the goal settle at 10, 9, 8.1, 7.29 and 6.56: each is 0.9 times the next one.

Q-learning: learning without the rules

Value iteration needs to know where every move leads. Usually an agent does not: it only experiences one move at a time. Q-learning (1989) learns Q-values from experience alone. After each move from state s with action a, landing in s′ with reward r:

Q-learning update

Q(s, a) ← Q(s, a) + α × (r + γ × the best Q(s′, ·) − Q(s, a))

The bracket is the temporal difference error: how much better or worse the move turned out than expected. The learning rate α decides how far each surprise moves the estimate.

A worked step, with α = 0.5 and γ = 0.9: Q(s, right) is 2.0, the move earns r = −1, and the best Q in the new state is 6.0. The target is −1 + 0.9 × 6.0 = 4.4, the error is 4.4 − 2.0 = 2.4, and the new estimate is 2.0 + 0.5 × 2.4 = 3.2.

A Q-learning updateTwo rows of Q-values. In state s, Q(s, left) is 0.5 and Q(s, right) is 2.0. The agent took right, received a reward of minus 1, and landed in s prime, where Q is 1.5 for left and 6.0 for right, the best. The target is minus 1 plus 0.9 times 6.0, which is 4.4. The error is 4.4 minus 2.0, which is 2.4. With alpha 0.5, the new Q(s, right) is 2.0 plus 0.5 times 2.4, which is 3.2.One Q-learning update, worked throughQ(s, ·)left0.5right2.0Q(s′, ·)left1.5right6.0took “right”, reward −1target−1 + 0.9 × 6.0 = 4.4error4.4 − 2.0 = 2.4new Q(s, right)2.0 + 0.5 × 2.4 = 3.2α = 0.5: move halfwaytowards the targetγ = 0.9: the futureis worth a bit lessA positive error means“better than expected”
The same three lines of arithmetic run millions of times in a real agent.

Try it: build a maze, train an agent, and watch the values spread out from the goal.

Q-learning grid lab

Train an agent to cross a grid world from rewards alone, and watch its values spread out from the goal. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.

Explore or exploit?

An agent that always takes the action that looks best so far may never discover a better one. One that always experiments never cashes in on what it knows. This is the exploration–exploitation trade-off.

The simplest answer is ε-greedy: with probability ε (say 0.1) take a random action, otherwise take the best-looking one. Often ε starts high and shrinks as the agent learns.

A multi-armed banditFive slot machines. Under each, a bar shows the estimated payout after 1,000 pulls with epsilon-greedy, and a dashed line the true payout. Machine 0: estimate 0.17, true 0.20, 134 pulls. Machine 1: 0.37, 0.50, 19 pulls. Machine 2: 0.17, 0.35, 29 pulls. Machine 3, the best: 0.81, 0.80, 797 pulls. Machine 4: 0.14, 0.10, 21 pulls. The best machine got most of the pulls, but machine 1 was tried so rarely that its estimate is well below its true rate.A five-armed bandit after 1,000 pulls with ε-greedy (ε = 0.1)machine 0est 0.17 · true 0.20134 pullsmachine 1est 0.37 · true 0.5019 pullsmachine 2est 0.17 · true 0.3529 pulls777machine 3est 0.81 · true 0.80797 pullsmachine 4est 0.14 · true 0.1021 pullsMachine 1 was tried only 19 times, so its estimate (0.37) is well below its true rate (0.50).
Exploit too soon and you misjudge the options you rarely try.

The classic test is the multi-armed bandit: a row of slot machines with hidden payout rates. Pull too few times and you misjudge a good machine; pull a bad one too often and you waste money. Smarter rules such as UCB (upper confidence bound) add a bonus to machines that have been tried less, so uncertainty itself attracts exploration.

Deep reinforcement learning

A Q-table needs one entry for every state and action. A video game screen has more possible states than there are atoms in the universe, so a table is hopeless. Deep RL replaces the table with a neural network that estimates Q from the raw input.

A deep Q-networkA pixel game screen with rows of coloured bricks, a ball and a paddle goes into convolutional layers, then dense layers, which output one Q-value per action: move left 2.1, stay still 3.4, move right 5.8. The agent picks the highest, move right. The Q-values here are illustrative.A deep Q-network: the screen goes in, a Q-value for every action comes outthe game screen(the state)convolutional layerssee the bricks, ball, paddledense layersQ = 2.1move leftQ = 3.4stay stillQ = 5.8move rightpick the highest:move right
One network replaces a table with more rows than there are atoms in the universe.
YearSystemAchievement
1992TD-GammonLearned backgammon to expert level by playing itself
2015DQNOne network learned 49 Atari games from the pixels, matching a professional games tester on many
2016AlphaGoBeat Lee Sedol, one of the world's best Go players (Lesson 13.2)
2019AlphaStar, OpenAI FiveGrandmaster level at StarCraft II; beat the world champions at Dota 2
2022RLHFTuned language models towards answers people prefer (Level 11)

DQN needed two tricks to train stably: experience replay, which stores past moves and learns from random batches of them, and a slowly updated target network. Other methods learn the policy directly: policy gradient methods nudge the probability of actions that led to high returns, and PPO (2017) is the version used to train robots and to fine-tune language models.

When rewards go wrong

An RL agent optimises exactly the reward it is given, not what its designer meant. In 2016, OpenAI trained an agent on the boat racing game CoastRunners, rewarding points. The agent found a lagoon where three targets kept reappearing and circled there forever, catching fire and crashing into other boats, scoring more than human players without ever finishing the race.

Reward hackingA race track around a grassy island, with a finish line at the top and a dashed green route showing the intended race. In a lagoon at the lower left, a red looping arrow circles past three bonus targets again and again. Notes: the reward given was points scored; the designer wanted the race won; the agent learned to loop for points; its score beat human players; races finished: none.Reward hacking: the agent maximised points, not the racefinishintended: race round and finish+++learned: circle the lagoonhitting the same targetsReward givenpoints scoredDesigner wantedwin the raceAgent learnedloop for pointsIts scorebeat human playersRaces finishednone
Based on OpenAI's 2016 CoastRunners experiment: the reward said points, so the agent chased points.

This is reward hacking, or specification gaming. It is funny in a game and serious in the real world: a recommendation system rewarded for watch time may learn to promote outrage. Designing rewards that capture what we really want is part of the alignment problem in Level 15.

Hands-on: reinforcement learning from scratch

Value iteration on a grid world

Python
ROWS = ["....G",
        ".#.#X",
        ".....",
        "S#..."]
GAMMA = 0.9
REWARD = {"G": 10, "X": -10}
MOVES = {"^": (-1, 0), "v": (1, 0), "<": (0, -1), ">": (0, 1)}
cells = [(r, c) for r in range(len(ROWS)) for c in range(len(ROWS[0])) if ROWS[r][c] != "#"]

def step(r, c, move):
    dr, dc = MOVES[move]
    nr, nc = r + dr, c + dc
    if 0 <= nr < len(ROWS) and 0 <= nc < len(ROWS[0]) and ROWS[nr][nc] != "#":
        return nr, nc
    return r, c                                  # bumping into a wall: stay put

def score(r, c, m):
    nr, nc = step(r, c, m)
    return REWARD.get(ROWS[nr][nc], -0.1) + GAMMA * V[(nr, nc)]     # a small cost for every step

V = {cell: 0.0 for cell in cells}
for sweep in range(1, 30):
    new = {}
    for (r, c) in cells:
        if ROWS[r][c] in REWARD:                 # the episode ends on G or X
            new[(r, c)] = 0.0
        else:
            new[(r, c)] = max(score(r, c, m) for m in MOVES)
    change = max(abs(new[k] - V[k]) for k in V)
    V = new
    if change < 0.001:
        break

print("values after", sweep, "sweeps:")
for r in range(len(ROWS)):
    print(" ".join("  ###" if ROWS[r][c] == "#" else f"{ROWS[r][c]:>5}" if ROWS[r][c] in REWARD
                   else f"{V[(r, c)]:5.1f}" for c in range(len(ROWS[0]))))
print("best move in each cell:")
for r in range(len(ROWS)):
    print(" ".join(ROWS[r][c] if ROWS[r][c] in "#GX" else max(MOVES, key=lambda m: score(r, c, m))
                   for c in range(len(ROWS[0]))))

Q-learning in a corridor

The agent starts at the left of six cells and does not know where the treasure is. Every step costs 1; the treasure is worth 10.

Python
import random

random.seed(4)
N, GOAL = 6, 5                      # actions: 0 = left, 1 = right
Q = [[0.0, 0.0] for _ in range(N)]
alpha, gamma, epsilon = 0.5, 0.9, 0.2

for episode in range(1, 201):
    s, steps = 0, 0
    while s != GOAL and steps < 100:
        if random.random() < epsilon:
            a = random.randrange(2)                       # explore
        else:
            a = 0 if Q[s][0] > Q[s][1] else 1             # exploit (ties go right)
        s2 = max(0, s - 1) if a == 0 else min(N - 1, s + 1)
        r = 10 if s2 == GOAL else -1
        target = r + (0 if s2 == GOAL else gamma * max(Q[s2]))
        Q[s][a] += alpha * (target - Q[s][a])             # the Q-learning update
        s, steps = s2, steps + 1
    if episode in (1, 2, 5, 20, 200):
        print(f"episode {episode:3}: took {steps:2} steps; Q(start, right) = {Q[0][1]:6.2f}")

print("learned policy:", " ".join("<" if q[0] > q[1] else ">" for q in Q[:GOAL]), "G")

Q(start, right) settles at 3.12, exactly −1 + 0.9 × (−1 + 0.9 × (−1 + 0.9 × (−1 + 0.9 × 10))): four steps that cost 1, then the treasure.

A five-armed bandit

Python
import random

random.seed(1)
true_payout = [0.2, 0.5, 0.35, 0.8, 0.1]       # chance each slot machine pays out (hidden)
estimates = [0.0] * 5
pulls = [0] * 5
total = 0
epsilon = 0.1
for t in range(1000):
    if random.random() < epsilon:
        arm = random.randrange(5)                                  # explore
    else:
        arm = max(range(5), key=lambda a: estimates[a])            # exploit
    reward = 1 if random.random() < true_payout[arm] else 0
    pulls[arm] += 1
    estimates[arm] += (reward - estimates[arm]) / pulls[arm]       # running average
    total += reward
for a in range(5):
    print(f"machine {a}: true {true_payout[a]:.2f}  estimate {estimates[a]:.2f}  pulled {pulls[a]:4} times")
print("total reward", total, "out of 1000 pulls; always picking the best would expect", round(1000 * max(true_payout)))

Try this

  1. In the grid world, change the step cost from −0.1 to −2. Does the policy ever choose to jump into X to end the pain sooner?
  2. In the corridor, set epsilon to 0. Does the agent still find the treasure? Why does the tie-breaking rule matter?
  3. In the bandit, try epsilon = 0.01 and epsilon = 0.3. Which earns more, and why?

Level check

  • Describe the agent–environment loop: state, action, reward, episode and policy
  • Calculate a discounted return, and explain what γ does
  • Explain state values and action values, and how a policy follows from them
  • Apply the Bellman equation, and describe value iteration
  • Carry out a Q-learning update by hand
  • Explain the exploration–exploitation trade-off and ε-greedy
  • Explain why deep RL uses neural networks, and name its milestones
  • Explain reward hacking with an example

Key terms you must be able to define

Reinforcement learning
Learning which actions to take from rewards, by trial and error.
Agent
The learner that observes states and chooses actions.
Environment
Everything the agent interacts with, which responds to its actions with new states and rewards.
Reward
A number the environment gives after an action, saying how good the outcome was.
Policy
The agent's rule for choosing an action in each state.
Return
The total of the future rewards, usually discounted.
Discount factor (γ)
A number between 0 and 1 that makes later rewards count for less.
Value
The return an agent can expect from a state, or from taking an action in a state (a Q-value).
Bellman equation
A state's value equals the best immediate reward plus the discounted value of where it leads.
Q-learning
Learning action values from experience by nudging each towards reward + γ × the best next Q-value.
Exploration
Trying actions that do not currently look best, to learn more about them.
ε-greedy
Acting randomly with probability ε, and otherwise taking the best-looking action.
Reward hacking
An agent maximising its reward in a way its designers did not intend.

Flashcards

DefineReinforcement learning
AnswerLearning which actions to take from rewards, by trial and error.
DefineAgent
AnswerThe learner that observes states and chooses actions.
DefineEnvironment
AnswerEverything the agent interacts with, which responds to its actions with new states and rewards.
DefineReward
AnswerA number the environment gives after an action, saying how good the outcome was.
DefinePolicy
AnswerThe agent's rule for choosing an action in each state.
DefineReturn
AnswerThe total of the future rewards, usually discounted.
DefineDiscount factor (γ)
AnswerA number between 0 and 1 that makes later rewards count for less.
DefineValue
AnswerThe return an agent can expect from a state, or from taking an action in a state (a Q-value).

Go further: notes for future AI engineers

On-policy and off-policy

Q-learning is off-policy: its update uses the best next action, whatever the agent actually does next, so it learns the value of acting well even while it explores. SARSA, its close cousin, uses the action the agent really takes next, so it learns the value of its own exploring policy. Near a cliff, SARSA learns to keep a safe distance, because it knows it will sometimes stumble; Q-learning learns the shortest route along the edge.

Model-based RL

Q-learning is model-free: it never learns how the world works, only how good actions are. Model-based methods also learn a model that predicts the next state and reward, and then plan inside that model, which can need far less real experience. MuZero (2019) learned its own model of each game and planned with it, mastering Atari, chess and Go without being told their rules.

Misconceptions to avoid

Avoid these
  • Thinking the agent is told the right action. It only gets rewards, often long after the action that earned them.
  • Believing the highest immediate reward is always best. A move with a small cost now can lead to a far bigger return later.
  • Setting γ to exactly 1 in a task that never ends, so returns can grow without limit.
  • Never exploring. An agent that always exploits can get stuck with the first decent option it found.
  • Assuming an agent will do what you meant. It does exactly what the reward pays for.
Fun fact

In 2016 DeepMind let a reinforcement learning system control the cooling of Google's data centres. It cut the energy used for cooling by up to 40%, by finding settings no engineer had tried.

Knowledge check

0 of 10 answered
1In reinforcement learning, what does the agent receive instead of correct answers?
2With γ = 0.9, an agent's next three rewards are 0, 0 and 10. What is its discounted return?
3What does the value V(s) of a state mean?
4A corridor's goal pays 10 when entered and γ = 0.9. If the cell next to the goal has value 10, what is the value of the cell before it?
5In Q-learning, Q(s, a) = 2.0, r = −1, γ = 0.9, the best Q in the next state is 6.0 and α = 0.5. What is the new Q(s, a)?
6Why must an agent explore?
7With ε-greedy and ε = 0.1, how often does the agent take a random action?
8Why did DQN use a neural network instead of a Q-table?
9What does experience replay do in DQN?
10An agent rewarded for points circles to hit the same targets instead of finishing the race. What is this?
Score 0 / 10

Check you could explain this

12 marks
1Explain how Q-learning allows an agent to learn a good policy without knowing the rules of its environment.5 marks
Explain

Mark scheme0 / 5
  • LThe agent keeps an estimate Q(s, a) of the return for each action in each state
  • LIt acts, and observes the reward and the next state
  • LIt computes a target: reward + γ × the best Q-value in the next state
  • LIt moves Q(s, a) a fraction α towards the target / by the temporal difference error
  • LIt explores, for example with ε-greedy, so all actions are tried
  • LThe policy is to take the action with the highest Q-value in each state
Model answer

The agent keeps an estimate Q(s, a) of the return it can expect from taking each action in each state, starting from zero. Each time it acts, it observes the reward and the state it lands in, and computes a target: the reward plus γ times the best Q-value available in the new state. It then moves its estimate a fraction α of the way towards that target, so every surprise improves the estimate, and rewards gradually spread back to the states and actions that led to them. To make sure it tries every action, it explores, for example taking a random action with probability ε. Once the estimates settle, the policy is simply to take the action with the highest Q-value in each state, and none of this needs a model of the rules.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2Explain the exploration–exploitation trade-off, using the example of choosing between slot machines.3 marks
Explain

Mark scheme0 / 3
  • LExploiting means choosing the machine that currently looks best
  • LExploring means trying other machines to learn their payouts
  • LToo little exploration can miss a better machine; too much wastes pulls on bad machines
  • LA strategy such as ε-greedy or UCB balances the two
Model answer

A player who always exploits picks the machine whose estimated payout is highest so far, but that estimate may be based on only a few pulls, so a better machine may never be discovered. A player who explores tries other machines to learn their payouts, but every pull on a poor machine wastes money. The trade-off is balancing the two, for example with ε-greedy, which picks a random machine a small fraction of the time and the best-looking one otherwise.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Discuss the problem of reward hacking, with an example.4 marks
Discuss

Mark scheme0 / 4
  • LThe agent maximises the reward exactly as written, not the designer's intention
  • LExample: the boat that circled hitting targets instead of finishing the race
  • LReal-world risk: e.g. recommender optimising watch time promoting harmful or outrageous content
  • LIt shows that designing rewards / aligning goals is hard and needs testing and oversight
Model answer

Reward hacking happens because a reinforcement learning agent maximises exactly the reward it is given, not what its designers meant by it. In the boat racing game CoastRunners, an agent rewarded for points discovered it could score more by circling a lagoon to hit the same reappearing targets, crashing and catching fire, than by finishing the race. In a game this is funny, but in the real world a recommendation system rewarded for watch time might learn to promote outrage or harmful content because it keeps people watching. It shows that rewards are very hard to specify completely, so systems need careful reward design, testing for unexpected strategies, and human oversight.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 12