Most machine learning learns from examples with the right answers attached. Reinforcement learning doesn’t get any answers. It tries things, collects rewards and penalties, and works out for itself what to do. Nobody tells it the right move; it learns which moves lead to reward, by trial and error. It’s how computers learned to beat champions at Go, and part of how chatbots are taught to be helpful. Here you’ll play the game yourself, then train an agent from nothing.
The vocabulary#
Six words cover most of it. Picture a mouse in a maze:
- The agent is the learner: the mouse.
- The environment is everything it acts in: the maze.
- A state is the current situation: which square the mouse is on.
- An action is a choice it can make: up, down, left or right.
- A reward is the number it gets back after acting: cheese is good, a hole is bad, most squares give nothing.
- A policy is its strategy: which action it takes in each state. Learning means improving the policy.
Explore or exploit?#
Start with the simplest version: one state, four choices. Four machines each pay out a point, or nothing, with their own hidden chance. You want as many points as possible, so you have to work out which machine is best by pulling them, and every pull you spend on a bad machine is a point you probably didn’t win. Try it.
You probably felt the pull of two instincts. Stick with the machine that’s been paying (exploit), or try the others in case one is better (explore). A common recipe for an agent, called ε-greedy, splits the difference: most of the time, pull the machine with the best record so far, and a small share of the time, ε (the Greek letter epsilon), pull one at random.
Predict first
An agent that never explores: it always pulls the machine with the best record so far. Over 300 pulls, how often does it end up mostly pulling the best machine?
The chart under the agent shows the whole trade-off, averaged over 200 games at each setting. Never exploring scores 0.53 points per pull. Exploring 10% of the time finds the best machine in 91% of games and scores 0.64. Always exploring is just pulling at random: 0.48. Too little exploring and you never find the best option; too much and you waste your time on options you already know are bad. Every reinforcement learning agent has to strike this balance, and it’s called the exploration–exploitation trade-off.
When the reward comes late#
The machines pay out instantly. Most real problems don’t: in chess, the reward is winning, and it arrives dozens of moves after the moves that earned it. So the agent has to learn which early moves lead to reward later.
Here’s a mouse on a 5 × 5 grid. Reaching the cheese gives +10, falling into a hole gives −10, and every other square gives nothing. One episode is one attempt, from the start until the mouse finds the cheese, falls in a hole, or gives up after 50 moves.
The mouse learns with Q-learning, an algorithm Chris Watkins introduced in 1989. It keeps a table with one number for every square and every move, called a Q-value: how much reward it expects if it makes that move from that square and plays well afterwards. After each move it nudges the number towards what it just saw:
Q ← Q + α × (reward + γ × best Q of the next square − Q)
α (alpha) is how big a nudge it takes, fixed at 0.5 here. γ (gamma) is how much it values the future, which you can change. Each square below shows its best Q-value, and an arrow for the move the mouse currently likes best there.
Predict first
The first time the mouse stumbles into the cheese, which of its moves get any credit?
The first few episodes usually end in holes, and the squares next to them start to look bad. The first time the mouse finds the cheese, only the square beside it lights up. Every later visit pushes the value one square further back, like a scent trail spreading out from the cheese. After a few dozen episodes, the arrows lead all the way from the start, and “Watch it” takes the shortest route: 8 moves. The start square settles at about 4.8, which is 10 × 0.9⁷: the cheese, discounted by γ once for each of the seven moves before the last.
That’s what γ, the discount factor, does: a reward one step later is worth γ times as much. Now set γ to 0, press reset and train 50 episodes a few times. Only the two squares next to the cheese ever turn green. Everywhere else, every move looks equally worthless, and the mouse wanders. γ is how far ahead the agent looks. Without it, a reward at the end can’t teach the moves at the start.
From grids to Go to chatbots#
A table works for 25 squares. Real problems have far too many states for a table, so a neural network learns to estimate the values instead. That’s deep reinforcement learning. In 2015, DeepMind showed a single network design learning to play dozens of Atari games from the pixels on screen, and in 2016 AlphaGo, which learned from human games and then from playing against itself, beat Lee Sedol, one of the world’s best Go players.
Chatbots use it too. In RLHF (reinforcement learning from human feedback), people compare pairs of answers, a separate reward model learns to predict which answers they prefer, and the chatbot is trained to earn that reward. OpenAI’s InstructGPT paper laid out the recipe in 2022. Newer methods such as DPO learn from the same comparisons without a separate reward model. And recent “reasoning” models have been trained with reinforcement learning on problems whose answers can be checked automatically, like maths and code.
Two warnings come with the power:
- It optimises exactly what you reward. In a well-known example from OpenAI, an agent playing the boat-racing game CoastRunners found it could score more points by circling in a lagoon, hitting the same targets over and over, than by finishing the race. This is called reward hacking, and it’s a real concern when the reward is a model’s guess at what people want.
- It’s hungry for practice. Our 25-square grid took dozens of episodes. Real tasks can take millions, which is why so much reinforcement learning happens in simulators and games.
In code#
Gymnasium is a widely used free library of practice environments (pip install gymnasium). FrozenLake is a grid like the mouse’s: cross the ice to the goal without falling through a hole, with a reward of 1 for reaching the goal. Here is the same Q-learning:
import gymnasium as gym
import numpy as np
env = gym.make("FrozenLake-v1", is_slippery=False) # 4x4 ice, holes, one goal
Q = np.zeros((env.observation_space.n, env.action_space.n))
alpha, gamma, epsilon = 0.5, 0.9, 0.1
rng = np.random.default_rng(0)
for episode in range(500):
state, _ = env.reset(seed=episode)
done = False
while not done:
if rng.random() < epsilon: # explore
action = rng.integers(env.action_space.n)
else: # exploit, breaking ties at random
action = rng.choice(np.flatnonzero(Q[state] == Q[state].max()))
next_state, reward, terminated, truncated, _ = env.step(action)
target = reward + gamma * Q[next_state].max() * (not terminated)
Q[state, action] += alpha * (target - Q[state, action])
state, done = next_state, terminated or truncated
print(Q.max(axis=1).reshape(4, 4).round(2)) # how good each square looks
# [[0.59 0.53 0.36 0. ]
# [0.66 0. 0.81 0. ]
# [0.73 0.81 0.9 0. ]
# [0. 0.73 1. 0. ]]The printout is the same kind of map as the mouse’s board: values rise towards the goal in the bottom right, each step back worth 0.9 of the one after it, and the holes stay at zero.
What to remember
- Reinforcement learning learns from rewards, not answers: an agent acts, sees what happens, and improves its policy.
- It has to balance exploring new options with exploiting what it knows; ε-greedy does that by acting at random a small share of the time.
- Q-learning spreads late rewards back to earlier moves one step at a time, and the discount factor γ sets how far ahead the agent looks.