Search

Search papers and lessons

Reinforcement Learning

Level 3 · 16 min read

Reinforcement learning trains an agent to choose actions by trial and error, guided only by a reward signal, so that it earns the most total reward over time.

On this page

  • Colour = topic mix
  • Probability
  • Linear algebra
  • Reinforcement learning
  • Stochastic processes
  • Discrete math
  • Sign in to see your progress

TL;DR

Reinforcement learning (RL) is learning by trial and error. An agent acts in an environment, the environment answers with a new situation and a number called the reward, and the agent adjusts its behaviour to collect more reward over time. Nobody tells it which action was correct. It has to discover that from the rewards.

The hard part is that an action's payoff often arrives late. A move in chess looks harmless until twenty turns later, so the agent must learn to credit the right earlier decisions for later outcomes.

Where you'll see it: in game-playing systems such as AlphaGo, in robot locomotion and control, in recommendation and ad-bidding systems, and in the fine-tuning step that teaches language models to follow human preferences.

Intuition

Learning a dog trick with treats

Think about teaching a dog to sit. Nobody writes down the muscle movements that make a sit. You wait, the dog tries things, and when it happens to sit you give a treat. Over many repetitions the dog connects the action to the reward and does it more often. It never saw a list of correct answers. It only saw which of its own actions led to good outcomes.

RL formalises that loop. The agent is the learner (the dog). The environment is everything outside it (the room, the owner). At each step the agent observes a state, picks an action, and receives a reward and the next state. The agent's goal is not the reward at one step. It is the total reward over the whole interaction, which is why the same loop can teach patience: giving up a small treat now can earn a bigger one later.

flowchart LR
  A[Agent] -- action --> E[Environment]
  E -- next state --> A
  E -- reward --> A

Why it is different from the other kinds of learning

In supervised learning someone supplies the right answer for every input. In RL the agent gets only a score, and that score is often sparse (zero for thousands of steps, then a win or a loss) and delayed. Two things follow. The agent must explore, trying actions it is unsure about to find out whether they are better. It must also exploit, using what it already knows to collect reward. Every RL method is a way of balancing these two.

The problem is shaped like a Markov decision process, which gives the states, actions, transition probabilities and rewards a precise meaning. RL is what you do when you do not know the transition probabilities or the reward function in advance and must learn from experience.

The math

Setting

The agent follows a policy π(a∣s)\pi(a \mid s), the probability of choosing action aa in state ss. The environment, at each step, moves to a new state s′s' with probability P(s′∣s,a)P(s' \mid s, a) and emits a reward Rt+1R_{t+1}. Time is indexed by t=0,1,2,…t = 0, 1, 2, \dots

The return

The quantity to maximise is the return, the total discounted reward from time tt onward:

Gt=Rt+1+γRt+2+γ2Rt+3+⋯=∑k=0∞γkRt+k+1.G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}.

Here γ\gamma (gamma) is the discount factor, a number between 0 and 1. It sets how much a reward kk steps away is worth today: γk\gamma^k. With γ\gamma close to 1 the agent plans far ahead. With γ\gamma close to 0 it cares mostly about the next step. The discount also keeps the sum finite when the interaction never ends.

The return has a simple recursive form, which is the root of most RL algorithms:

Gt=Rt+1+γ Gt+1.G_t = R_{t+1} + \gamma\, G_{t+1}.

Value functions

The state-value function is the expected return when starting in ss and following π\pi:

vπ(s)=Eπ[Gt∣St=s].v_\pi(s) = \mathbb{E}_\pi\left[ G_t \mid S_t = s \right].

The action-value function (also called the Q-function) conditions on the first action as well:

qπ(s,a)=Eπ[Gt∣St=s,At=a].q_\pi(s, a) = \mathbb{E}_\pi\left[ G_t \mid S_t = s, A_t = a \right].

If you know qπq_\pi, acting well is easy: in each state, pick the action with the largest value. The value function is how the agent stores its judgement of how good each situation is, and learning it from experience is most of the work.

Learning from a single step

The agent cannot average over infinitely many futures, so it learns from one step at a time. Suppose the current estimate of q(s,a)q(s, a) is off. The temporal-difference error compares the reward just received, plus the discounted estimate of what follows, with the current estimate:

δt=Rt+1+γmax⁡a′q(St+1,a′)−q(St,At).\delta_t = R_{t+1} + \gamma \max_{a'} q(S_{t+1}, a') - q(S_t, A_t).

Nudge the estimate a fraction α\alpha (the learning rate) toward the target:

q(St,At)←q(St,At)+α δt.q(S_t, A_t) \leftarrow q(S_t, A_t) + \alpha\, \delta_t.

This is the update rule of Q-learning. It is a sample-based version of the Bellman optimality equation, which says that the best value of a state equals the best immediate reward plus the discounted best value of the next state.

Learning the policy directly

Instead of learning values and then acting greedily, a policy-gradient method adjusts the parameters θ\theta of the policy πθ\pi_\theta to make high-return actions more likely. Let J(θ)=Eπθ[G0]J(\theta) = \mathbb{E}_{\pi_\theta}[G_0] be the expected return of the policy, the number we want to increase. The basic gradient of JJ (the REINFORCE form) is

∇θJ(θ)=Eπθ[∇θlog⁡πθ(At∣St) Gt].\nabla_\theta J(\theta) = \mathbb{E}_{\pi_\theta}\left[ \nabla_\theta \log \pi_\theta(A_t \mid S_t)\, G_t \right].

Actions followed by a high return get their probability pushed up, and actions followed by a poor return get pushed down. Actor-critic methods combine both ideas: a critic learns values and an actor learns the policy.

The exploration rule

A simple way to balance exploration and exploitation is ε\varepsilon-greedy action selection. With probability 1−ε1 - \varepsilon the agent picks the action with the highest estimated value. With probability ε\varepsilon it picks an action uniformly at random. Each action's value can be estimated as a running average of its rewards. After nn pulls, with reward RnR_n on the latest pull, the average updates as

Qn=Qn−1+1n(Rn−Qn−1).Q_n = Q_{n-1} + \frac{1}{n}\left(R_n - Q_{n-1}\right).

This is the same update as the learning rule above, with learning rate α=1/n\alpha = 1/n.

0102030405000.20.40.60.81update count tlearning rate α
  • α = 1 / (1 + 0.1 t)
  • α = 1 / t
A learning rate that shrinks over time lets early updates move estimates a lot and late updates settle them down. Both curves shrink toward zero.

Worked examples

Example
The discounted return

An agent receives rewards R1=1R_1 = 1, R2=0R_2 = 0, R3=2R_3 = 2 and then the episode ends. Use γ=0.5\gamma = 0.5 and compute G0G_0.

  1. G0=R1+γR2+γ2R3G_0 = R_1 + \gamma R_2 + \gamma^2 R_3.
  2. =1+0.5×0+0.25×2= 1 + 0.5 \times 0 + 0.25 \times 2.
  3. =1+0+0.5=1.5= 1 + 0 + 0.5 = 1.5.
  4. The reward of 2 arrives two steps late, so it counts for a quarter of its face value. With γ=0.9\gamma = 0.9 it would count for 0.81 and G0G_0 would be 2.62, so a more patient agent values the delayed reward more.
Example
One Q-learning update

A robot is in state ss, takes action aa, gets reward 1 and lands in s′s'. Its current estimates are q(s,a)=0q(s, a) = 0 and max⁡a′q(s′,a′)=2\max_{a'} q(s', a') = 2. Take α=0.5\alpha = 0.5 and γ=0.9\gamma = 0.9.

  1. Target: R+γmax⁡a′q(s′,a′)=1+0.9×2=2.8R + \gamma \max_{a'} q(s', a') = 1 + 0.9 \times 2 = 2.8.
  2. Temporal-difference error: δ=2.8−0=2.8\delta = 2.8 - 0 = 2.8.
  3. New estimate: q(s,a)←0+0.5×2.8=1.4q(s, a) \leftarrow 0 + 0.5 \times 2.8 = 1.4.
  4. The estimate moved halfway toward the target. Repeating this as the agent revisits (s,a)(s, a) would drive it toward the true value.
Example
Learning which slot machine pays

An agent tries two arms and starts with estimate Q=0Q = 0 for arm A. It pulls A three times and gets rewards 1, 0, 1.

  1. Pull 1, reward 1: Q=0+11(1−0)=1Q = 0 + \frac{1}{1}(1 - 0) = 1.
  2. Pull 2, reward 0: Q=1+12(0−1)=0.5Q = 1 + \frac{1}{2}(0 - 1) = 0.5.
  3. Pull 3, reward 1: Q=0.5+13(1−0.5)=0.6667Q = 0.5 + \frac{1}{3}(1 - 0.5) = 0.6667.
  4. The estimate equals the average of the three rewards, 2/32/3. With ε=0.1\varepsilon = 0.1 the agent still tries arm B about one time in ten, so it can notice if B turns out better.

Tradeoffs and failure modes

RL is powerful but demanding. It needs a lot of interaction, and the interaction is often the expensive part (a robot wearing out, a real customer seeing a bad ad). Most of the practical pain comes from the reward and the environment, not from the algorithm.

SituationWhat goes wrongBetter choice
You can label the right answer for each inputRL wastes samples discovering what you already knowSupervised learning
Rewards are sparse and far awayThe agent never sees a useful signal and learns nothingReward shaping, demonstrations, or curriculum
The agent can exploit a flaw in the rewardIt scores well without doing the task (reward hacking)Better reward design, reward models with checks
The state space is hugeTables of values do not fit or never fill inFunction approximation with a neural network (deep RL)
Learning is unstable with neural networksEstimates diverge because targets move with the estimateExperience replay, target networks, or policy-gradient methods with a baseline
You can simulate the environment cheaplyReal-world trials are slow and riskyTrain in simulation first, then transfer

A common failure is judging an agent by its training reward alone. The agent may learn a narrow trick that breaks outside the situations it saw, so evaluate on fresh episodes and on variations of the environment.

History

The idea of learning from reward is older than the computer. In the 1890s and early 1900s, psychologists such as Edward Thorndike described the law of effect: actions followed by satisfaction become more likely. Richard Bellman's work on dynamic programming in the 1950s gave the mathematical backbone, with value functions and the recursive equation that now bears his name. Arthur Samuel's checkers program in the late 1950s learned from play and is often cited as an early example.

The modern field came together in the late 1980s. Richard Sutton formalised temporal-difference learning, which learns from the difference between successive predictions, and Chris Watkins introduced Q-learning in his 1989 thesis. Gerald Tesauro's TD-Gammon in the early 1990s reached expert-level backgammon play with a neural network trained by self-play, which showed that the approach could work on a hard problem. Sutton and Barto's textbook, first published in 1998, gave the field a shared language.

It caught on widely in the 2010s, when deep networks made it possible to handle raw images. The 2013 Atari paper by Mnih and colleagues learned to play several games from pixels, and AlphaGo's 2016 win over a top Go professional drew broad attention. These results combined the old ideas with large-scale function approximation.

Check yourself

QuestionRecall: what does the discount factor γ\gamma control?Show answer

It sets how much future rewards count compared with immediate ones. A reward kk steps away is multiplied by γk\gamma^k. A value near 1 makes the agent plan far ahead; a value near 0 makes it focus on the next step.

QuestionComputation: with γ=0.8\gamma = 0.8, what is the return G0G_0 if the rewards are R1=0R_1 = 0, R2=1R_2 = 1, R3=1R_3 = 1, and then the episode ends?Show answer

G0=R1+γR2+γ2R3=0+0.8×1+0.64×1=1.44G_0 = R_1 + \gamma R_2 + \gamma^2 R_3 = 0 + 0.8 \times 1 + 0.64 \times 1 = 1.44. Each term is the reward multiplied by the discount for how many steps away it is.

QuestionWhy: why does RL need exploration, when the agent could simply keep doing whatever has worked so far?Show answer

The agent only learns the value of actions it tries. If it never tries an action, its estimate of that action stays wrong, and a better option may remain hidden forever. Exploration pays a short-term cost to gain information that can improve the long-term return. Pure exploitation locks in an early guess.

QuestionApplied: a delivery robot is rewarded only when it finishes a delivery, which can take 200 steps. What problem does this create, and what could help?Show answer

The reward is sparse and delayed. Early random behaviour almost never reaches the goal, so the agent gets little signal to learn from, and credit for the final reward is hard to assign to the earlier moves. Helpful options include shaping the reward with small intermediate rewards (for example, for getting closer to the pickup point), starting from demonstrations, or using a discount and a value function so that each step gets a useful estimate of what follows. Each option has a risk: shaped rewards can teach the robot to chase the intermediate signal instead of finishing the delivery.

Sources