Level 3 In-Depth AI · Reinforcement Learning
Reinforcement Learning: The Basics
How a machine learns by trial and error. An agent acts in an environment, collects rewards, and gradually learns which actions lead to the most reward over time.
- Level
- ●●●●● Easy
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 3 concepts →
- Quiz
- 4 questions ↓
The full path from zero — 3 concepts before this one
- What Is AI?
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Reinforcement Learning: The Basics
Read them roughly in this order. See it on the concept map →
Why it matters
Most of machine learning learns from a fixed table of examples with the right answers attached. Supervised learning is told "this photo is a cat". But many problems have no answer key. Nobody can write down the correct move in every chess position, the right motor command for every instant of a robot's walk, or the perfect reply to every message. What we can do is say how well things went afterwards: you won, you fell over, the user liked the answer.
Reinforcement learning (RL) is learning from that kind of feedback. A learner acts, sees what happens, receives a score, and adjusts its behaviour so that, over time, it collects as much score as possible. It is how AlphaGo learned to beat the world's best Go players (Monte Carlo Tree Search and AlphaGo), how DeepMind's DQN learned dozens of Atari games from raw pixels (Deep Q-Networks), how robots learn to walk in simulation, and how chat models are polished to give answers people prefer (RLHF and Preference Optimization) or to reason step by step before answering (Reasoning Models and Test-Time Compute).
This chapter sets up the vocabulary and the one picture that every later RL chapter builds on. It uses a tiny gridworld, a board game simple enough to work out by hand, which we will reuse in Markov Decision Processes, Value Functions and Bellman Equations and Q-Learning.
The intuition
Think of training a dog. You can't explain to the dog what "sit" means. Instead, when it happens to sit, you give it a treat. When it jumps on the sofa, no treat. Over many tries the dog works out which behaviour earns treats in which situation. You never showed it the right answer. You only scored what it did.
Reinforcement learning has exactly this shape, and every piece has a name:
- The agent is the learner and decision-maker: the dog, a game-playing program, a robot's controller.
- The environment is everything outside the agent that it interacts with: the room and the owner, the game, the physical world.
- A state is a description of the current situation: where the agent is, the board position, the robot's joint angles.
- An action is a choice the agent can make: sit, move left, push the cart right.
- A reward is a number the environment sends back after each action, saying how good that step was. Treat: +1. Nothing: 0. Fell into the pit: −1.
- A policy is the agent's behaviour: a rule that says which action to take in each state. Learning means improving the policy.
These pieces interact in a loop. The agent looks at the state, picks an action, and the environment responds with a new state and a reward. Then it goes round again.
Two things make this harder than it sounds.
- Delayed reward. The reward for a good move often comes much later. In chess only the final position is scored. So which of your 40 moves deserves the credit for the win? This is the credit assignment problem, and most of RL is clever ways of solving it.
- Exploration. The agent only learns about actions it actually tries. If it always repeats the first thing that worked, it may never discover something much better. It has to balance trying new things (exploring) against using what it already knows (exploiting). Multi-Armed Bandits and Exploration studies this trade-off on its own.
Key idea In reinforcement learning nobody gives the right action. The agent tries actions, receives rewards, and learns a policy that maximises the total reward it collects over time, not just the next one.
How it works
The loop, step by step
Time moves in discrete steps . At each step:
- The agent observes the state .
- It chooses an action .
- The environment returns a reward and a new state .
Capital letters mean these are random variables: they can come out differently each time. The notation follows the standard textbook, Sutton and Barto's Reinforcement Learning: An Introduction, and so does every RL chapter in this guide. Note that the reward that follows action is written , not . It arrives together with the next state, so it gets the next time index.
One run of the loop from a starting state to an end is an episode: one game of chess, one attempt to cross the grid. The state that ends it is a terminal state. The record of everything that happened is a trajectory:
Some tasks never end (a thermostat, a stock-trading agent). They are called continuing tasks, as opposed to episodic tasks.
The policy
The policy is written (the Greek letter "pi"; nothing to do with 3.14). Policies may be random. is the probability that the agent picks action when it is in state . A deterministic policy always picks the same action in a given state. A random agent's policy gives each of four moves probability 0.25. Most RL algorithms learn a policy that starts nearly random and becomes more decisive as the agent learns.
The return: adding up future rewards
The agent's goal is not to grab the biggest next reward. It is to maximise the total reward from now on. That total is called the return, written :
In words: the return at time is the next reward, plus the reward after that shrunk by a factor , plus the one after that shrunk by , and so on. The Greek letter ("gamma") is the discount factor, a number between 0 and 1 that you choose.
Why shrink future rewards?
- Sooner is better. With a reward of 1 that arrives 10 steps from now counts as today. An agent that discounts prefers short routes to the goal.
- It keeps sums finite. In a continuing task an undiscounted sum of rewards could grow forever. With it stays bounded.
- The far future is uncertain. Rewards far ahead are less reliable, so trusting them less is sensible.
makes the agent short-sighted: only the next reward counts. close to 1 (0.99 is common) makes it far-sighted.
The return has a handy recursive form. Pull out the first reward and what's left is times the return from the next step:
This one-line identity is the seed of the Bellman equations, the backbone of RL.
The reward hypothesis is the bet underneath the whole field: that every goal we care about can be expressed as maximising the expected return of a single scalar reward signal. It works remarkably often, and when it fails, it fails in interesting ways. Agents become very good at exploiting a badly designed reward, as reward hacking shows.
A gridworld walk-through
Here is the small world we will use throughout this part of the guide. It is a 4 × 4 board. The agent starts at the bottom-left. Each step it chooses up, down, left or right. Moving into the edge of the board or the grey wall leaves it where it is. Reaching the goal square (top-right) gives reward +1 and ends the episode. Falling into the pit just below the goal gives reward −1 and also ends it. Every other move gives reward 0. The discount is .
Worked example 1: the green path. Up, up, up, right, right, right. The rewards are 0, 0, 0, 0, 0, +1. Only the last one is non-zero, and it arrives at the sixth step, so it is discounted five times:
Worked example 2: the red path. Right, right, up, right, up, and the agent lands in the pit. The rewards are 0, 0, 0, 0, −1, so
Worked example 3: the recursion. One step into the green path, the agent stands one square up from the start, with five steps to go. Its return from there is . Check the recursive form: . ✓
Notice what discounting does. A longer route to the goal, say 10 steps, would earn only . So the agent has a reason to be quick even though no step costs anything.
What "learning" means here
The agent does not see this picture. It does not know where the pit is or that the wall exists. It only gets states and rewards, one step at a time. Learning means using that stream of experience to improve the policy, so that eventually it walks the green route every time.
There are three broad families of methods, and the rest of this part of the guide covers each:
- Value-based methods learn how good each state or action is (its expected return) and act greedily on those estimates: Value Functions and Bellman Equations, Q-Learning, Deep Q-Networks.
- Policy-based methods adjust the policy directly to make high-return actions more likely: Policy Gradients, Actor-Critic Methods, Proximal Policy Optimization.
- Model-based methods learn how the environment works and plan inside that model: Monte Carlo Tree Search and AlphaGo, Model-Based RL and World Models.
In code
An environment is just an object with two methods. reset() starts an episode and returns the first state. step(action) applies an action and returns the next state, the reward, and whether the episode is over. Here is the gridworld, plus a loop that runs a policy and computes the discounted return.
import random
class GridWorld:
"""4x4 grid. Start bottom-left, goal top-right (+1), pit below it (-1)."""
MOVES = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}
def reset(self):
self.pos = (3, 0)
return self.pos
def step(self, action):
dr, dc = self.MOVES[action]
r, c = self.pos[0] + dr, self.pos[1] + dc
if 0 <= r < 4 and 0 <= c < 4 and (r, c) != (1, 1): # (1,1) is a wall
self.pos = (r, c)
if self.pos == (0, 3): return self.pos, +1.0, True # goal
if self.pos == (1, 3): return self.pos, -1.0, True # pit
return self.pos, 0.0, False
def run_episode(env, policy, gamma=0.9, max_steps=100):
state, G, discount = env.reset(), 0.0, 1.0
for t in range(max_steps):
action = policy(state)
state, reward, done = env.step(action)
G += discount * reward # G = R1 + γR2 + γ²R3 + ...
discount *= gamma
if done: break
return G, t + 1
random.seed(0)
env = GridWorld()
random_policy = lambda s: random.choice(list(GridWorld.MOVES))
def sensible_policy(s): # up the left edge, then right
return "up" if s[1] == 0 and s[0] > 0 else "right"
for name, pol in [("random", random_policy), ("sensible", sensible_policy)]:
results = [run_episode(env, pol) for _ in range(1000)]
avg_G = sum(g for g, _ in results) / len(results)
avg_len = sum(n for _, n in results) / len(results)
print(f"{name:9s} average return {avg_G:+.3f} average length {avg_len:.1f} steps")
# random average return -0.065 average length 40.8 steps
# sensible average return +0.590 average length 6.0 steps
The random agent wanders for about 41 steps on average. It falls into the pit far more often than it finds the goal (about 690 times against 230 in these 1,000 episodes, with the rest timing out), but most of those endings come many steps in, so discounting shrinks them and its average return ends up just below zero. The hand-written policy scores 0.590 every time, exactly the number we worked out by hand. Every RL algorithm in the following chapters is a way of getting from the first line to the second without a human writing the policy.
The next step: Gymnasium
Real RL code uses Gymnasium, the standard Python library of environments (the maintained successor of OpenAI's Gym). Its interface is the one above with two refinements. reset also returns an info dictionary. step splits "done" into terminated (the task really ended, for example the pole fell) and truncated (a time limit cut the episode short). This snippet needs pip install gymnasium, so it isn't run here:
import gymnasium as gym
env = gym.make("CartPole-v1") # balance a pole on a moving cart
obs, info = env.reset(seed=0) # obs: 4 numbers (position, velocity, angle, angular velocity)
total = 0.0
for _ in range(500):
action = env.action_space.sample() # a random policy: 0 = push left, 1 = push right
obs, reward, terminated, truncated, info = env.step(action)
total += reward # +1 for every step the pole stays up
if terminated or truncated:
break
print("episode return:", total) # a random policy usually lasts only a couple of dozen steps
env.close()
Swap "CartPole-v1" for "LunarLander-v3", "FrozenLake-v1" or an Atari game and the same loop works. Any agent you write against this interface can be tested on hundreds of environments.
Common pitfalls
- Confusing reward with return. The reward is one step's score. The return is the discounted sum of all future rewards. An agent that maximised the next reward alone would happily walk past the goal to avoid a small cost now.
- Off-by-one time indices. In this notation the reward for action is . Libraries and papers differ (some write ). When you compute returns in code, check which reward goes with which action.
- Badly designed rewards. The agent optimises exactly what you reward, not what you meant. A famous OpenAI demo (2016) showed a boat-racing agent that learned to circle forever collecting bonus targets instead of finishing the race, because the bonuses gave more points.
- Too small a discount. With a reward 10 steps away is worth , so the agent effectively can't see it. Long tasks need close to 1.
- Treating
truncatedasterminated. When an episode is cut off by a time limit, the world didn't end. The agent could have kept collecting reward. Learning algorithms that treat a time-out as a true end learn biased values.
Watch out Reward design is where most real RL projects go wrong. If there is a loophole that scores well without doing the task, a good optimiser will find it. Watch what your agent actually does, not just the reward curve.
Where it leads
The gridworld problem has a precise mathematical form, the Markov decision process, covered in Markov Decision Processes. Once you have that, Value Functions and Bellman Equations shows how to compute the value of every square exactly when the rules are known, and Q-Learning shows how to learn the same thing purely from experience. Deep Q-Networks replaces the lookup table with a neural network so the idea scales to video games. Policy Gradients, Actor-Critic Methods and Proximal Policy Optimization learn the policy directly, and PPO is the algorithm behind classic RLHF and Preference Optimization. Monte Carlo Tree Search and AlphaGo and Model-Based RL and World Models add planning. Before any of that, Multi-Armed Bandits and Exploration isolates the exploration problem in its simplest setting.
A bit of history
RL has two roots. One is the psychology of animal learning: Edward Thorndike's "law of effect" (1911) said that behaviours followed by satisfaction become more likely. The other is optimal control. Richard Bellman's dynamic programming (1950s) gave the equations for planning when the rules are known. In 1959 Arthur Samuel's checkers program improved by playing against itself, an early ancestor of AlphaGo. In the 1980s Richard Sutton and Andrew Barto joined the two threads into the modern field. Sutton introduced temporal-difference learning (1988), and Chris Watkins introduced Q-learning (1989). Their textbook (first edition 1998, second edition 2018) is still the standard reference, and they received the 2024 Turing Award (announced in March 2025) for this work. In 1992 Gerald Tesauro's TD-Gammon reached near-expert backgammon by self-play. The modern era of deep RL began with DeepMind's Atari-playing DQN in 2013–2015 and AlphaGo in 2016.
Try it
- In the code, change
gammato 0.5 and to 0.99. How do the two average returns change? Why does the sensible policy's return depend on but not on luck?- Write a policy that goes right first, along the bottom row, then up column 3. What happens, and why?
- Count how often the random agent reaches the goal versus the pit in 1,000 episodes.
Hint for 2: column 3 contains the pit, one square below the goal.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Reinforcement Learning: An Introduction
The foundational RL textbook by the field's founders. Free PDF.
Hugging Face Deep RL Course
A hands-on deep reinforcement learning course from Q-learning to PPO. You train agents in games.
Spinning Up in Deep RL
OpenAI's short, precise introduction to deep RL: key concepts and notation, the policy-gradient derivation, and clean reference implementations of VPG, PPO, DDPG, TD3 and SAC.
UCL Course on Reinforcement Learning
Ten recorded lectures with slides by the lead researcher behind AlphaGo. Covers MDPs, dynamic programming, TD learning, function approximation, policy gradients and planning; follows Sutton & Barto closely.
Gymnasium documentation
The standard Python API for RL environments (the maintained successor of OpenAI Gym): CartPole, LunarLander, Atari, MuJoCo and a tutorial on writing your own environment.
A (Long) Peek into Reinforcement Learning
A dense, well-organised tour of the core ideas: MDPs, Bellman equations, dynamic programming, Monte Carlo and TD methods, Q-learning, DQN and policy gradients.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/rl-basics.md