Reinforcement Learning
Nobody shows a child the correct muscle commands for riding a bike. The child tries, wobbles, falls, and gradually does more of what keeps the bike upright. Reinforcement learning (RL) learns the same way: an agent acts in an environment, receives rewards, and improves its behaviour to collect as much reward as possible over time. There are no labelled correct actions, only consequences.
The loop
At each time step the agent sees a state , chooses an action , and the environment answers with a reward and the next state . A policy is the agent's rule for choosing actions. The goal is a policy that maximises the return, the total reward collected, where future rewards are usually discounted by a factor between 0 and 1:
With close to 1 the agent plans far ahead; with close to 0 it cares only about the next reward.
Three things make RL different from supervised learning:
- No correct answers, only rewards. The agent is told how good an outcome was, not which action would have been best.
- Delayed consequences. A move in chess may win or lose the game 40 moves later. The agent must work out which earlier actions deserve the credit.
- The data depends on the agent. What the agent experiences depends on what it does, so it must balance exploration (trying actions to learn about them) and exploitation (using what it already knows works).
Exploration vs exploitation: the multi-armed bandit
The simplest RL problem has one state and several actions. Picture three slot machines ("one-armed bandits") with unknown win probabilities. Each pull gives reward 1 (a win) or 0. The -greedy strategy exploits the arm with the best average so far, except that with probability it explores a random arm.
import numpy as np
# A 3-armed bandit: three slot machines with hidden win probabilities.
true_p = np.array([0.30, 0.55, 0.45])
rng = np.random.default_rng(0)
def play(epsilon, steps=2000):
q = np.zeros(3) # estimated value of each arm
n = np.zeros(3) # how often each arm was pulled
total = 0
for t in range(steps):
if rng.random() < epsilon:
arm = int(rng.integers(3)) # explore: try a random arm
else:
arm = int(np.argmax(q)) # exploit: the best arm so far
reward = float(rng.random() < true_p[arm])
n[arm] += 1
q[arm] += (reward - q[arm]) / n[arm] # running average of the rewards
total += reward
return q, n, total
for eps in [0.0, 0.1]:
q, n, total = play(eps)
print(f"epsilon {eps}: estimates {q.round(2)}, pulls {n.astype(int)}, average reward {total / 2000:.3f}")
print("best possible average reward:", true_p.max())epsilon 0.0: estimates [0.29 0. 0. ], pulls [2000 0 0], average reward 0.289
epsilon 0.1: estimates [0.33 0.54 0.47], pulls [ 96 1775 129], average reward 0.523
best possible average reward: 0.55
The purely greedy agent () pulled the first arm once, won, and never tried anything else: it is stuck on the worst machine with an average reward of 0.289. With 10 % exploration the agent estimated all three arms well, put 1775 of its 2000 pulls on the best one, and earned 0.523 per pull, close to the best possible 0.55. A little exploration is worth a lot.
Learning a policy: Q-learning in a grid world
With many states, the agent needs to learn the value of each action in each state. Q-learning keeps a table , an estimate of the return from taking action in state and acting well afterwards. After every step it moves the estimate towards what it just observed:
Here is the learning rate and the next state. The bracket is the surprise: reward received plus the best value of the next state, minus what was expected.
The world below is cells. The agent starts top left; the goal at the bottom right pays +10, a pit at row 1, column 2 costs and ends the episode, and every move costs , so short routes are better.
import numpy as np
# Grid world: 4 x 4 cells, start top-left, goal bottom-right (+10), a pit at (1, 2) (-10), -1 per move.
SIZE, GOAL, PIT = 4, (3, 3), (1, 2)
MOVES = {"^": (-1, 0), "v": (1, 0), "<": (0, -1), ">": (0, 1)}
ACTIONS = list(MOVES)
def step(state, action):
r, c = state
dr, dc = MOVES[action]
nr, nc = min(max(r + dr, 0), SIZE - 1), min(max(c + dc, 0), SIZE - 1) # walls stop you
if (nr, nc) == GOAL:
return (nr, nc), 10.0, True
if (nr, nc) == PIT:
return (nr, nc), -10.0, True
return (nr, nc), -1.0, False
rng = np.random.default_rng(0)
Q = np.zeros((SIZE, SIZE, 4))
alpha, gamma, epsilon = 0.5, 0.95, 0.2
for episode in range(500):
state, done = (0, 0), False
while not done:
a = int(rng.integers(4)) if rng.random() < epsilon else int(np.argmax(Q[state]))
nxt, reward, done = step(state, ACTIONS[a])
target = reward if done else reward + gamma * Q[nxt].max()
Q[state][a] += alpha * (target - Q[state][a]) # the Q-learning update
state = nxt
print("learned policy (best move in each cell):")
for r in range(SIZE):
row = ""
for c in range(SIZE):
row += "G" if (r, c) == GOAL else "X" if (r, c) == PIT else ACTIONS[int(np.argmax(Q[r, c]))]
print(" ", " ".join(row))
state, path = (0, 0), [(0, 0)]
for _ in range(10):
state, reward, done = step(state, ACTIONS[int(np.argmax(Q[state]))])
path.append(state)
if done:
break
print("greedy path:", path)
print("value of the start cell:", round(Q[0, 0].max(), 2))learned policy (best move in each cell):
v v > v
> v X v
v v v v
> > > G
greedy path: [(0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (3, 2), (3, 3)]
value of the start cell: 3.21
After 500 episodes of trial and error the agent walks to the goal in 6 moves, the shortest possible, and stays away from the pit (the cell above the pit points away from it). No one told it the route. The learned value of the start cell is 3.21, which matches the discounted return of the best route exactly: five moves at and then give . Follow the arrows from any cell and you reach the goal: the agent learned a complete policy, not just one route. In bigger worlds, states the agent rarely visits are learned poorly, which is one reason exploration matters.
Where RL is used
- Games: from Atari games to Go and StarCraft, often combined with search and self-play.
- Robotics: walking, grasping and flying, usually trained in simulation first.
- Operations: data-centre cooling, traffic-light timing, inventory and ad bidding.
- Language models: reinforcement learning from human feedback (RLHF) tunes chat models towards answers people prefer.
RL needs many interactions, a reward that really captures the goal, and safe exploration. When labelled examples of good actions exist, supervised learning is usually simpler. The Markov Decision Processes lesson of the probability course and the MDP and Bellman lesson of math-deep-learning give the theory.
Pitfalls
- Reward hacking. Agents optimise the reward you wrote, not the one you meant. A cleaning robot rewarded for "no dirt visible" may learn to cover its camera.
- Too little exploration. As the greedy bandit shows, an agent can lock onto a poor action forever.
- Sample hunger. Even the grid needed hundreds of episodes. Real tasks need millions, which is why simulators matter.
Practice
- In the bandit, why did the greedy agent estimate arms 2 and 3 at exactly 0?
Answer
It never pulled them. Their estimates stayed at the initial value 0, below the first arm's estimate once that arm had won, so argmax never chose them. Initial values plus no exploration decided the outcome.
- With , compute the return of the route "five moves at , then " by hand, and compare it with the route that walks straight into the pit after two moves (, then ).
Answer
Goal route: . Pit route: . The goal route is far better, so the learned policy avoids the pit.
Test yourself
What does a reinforcement-learning agent learn from?
- Labelled correct actions
- Rewards that follow its actions
- Clusters in the data
- A test set
Why did the agent earn more than the greedy one?
- It pulled arms at random all the time
- Occasional exploration let it discover that arm 2 is best
- It had more steps
- Its machines paid more
In the Q-learning update, what does control?
- How fast the table is updated
- How much future rewards count compared with immediate ones
- The exploration rate
- The size of the grid
An agent rewarded for points in a boat-racing game learns to circle forever collecting bonus items instead of finishing. What is this?
- Overfitting
- Reward hacking: optimising the written reward instead of the intended goal
- Underfitting
- Data drift