TExcelTAD

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

agent environment action a(t) next state s(t+1), reward r(t+1)

At each time step tt the agent sees a state sts_t, chooses an action ata_t, and the environment answers with a reward rt+1r_{t+1} and the next state st+1s_{t+1}. A policy π\pi 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 γ\gamma between 0 and 1:

Gt=rt+1+γ rt+2+γ2rt+3+⋯=∑k=0∞γk rt+k+1G_t = r_{t+1} + \gamma\, r_{t+2} + \gamma^2 r_{t+3} + \cdots = \sum_{k=0}^{\infty} \gamma^k\, r_{t+k+1}

With γ\gamma close to 1 the agent plans far ahead; with γ\gamma 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 ε\varepsilon-greedy strategy exploits the arm with the best average so far, except that with probability ε\varepsilon it explores a random arm.

python · try it yourself
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 (ε=0\varepsilon = 0) 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 Q(s,a)Q(s, a), an estimate of the return from taking action aa in state ss and acting well afterwards. After every step it moves the estimate towards what it just observed:

Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha \left[ r + \gamma \max_{a'} Q(s', a') - Q(s, a) \right]

Here α\alpha is the learning rate and s′s' 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 4×44 \times 4 cells. The agent starts top left; the goal at the bottom right pays +10, a pit at row 1, column 2 costs −10-10 and ends the episode, and every move costs −1-1, so short routes are better.

python · try it yourself
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 −1-1 and then +10+10 give −1−0.95−0.952−0.953−0.954+0.955⋅10≈3.21-1 - 0.95 - 0.95^2 - 0.95^3 - 0.95^4 + 0.95^5 \cdot 10 \approx 3.21. 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 4×44 \times 4 grid needed hundreds of episodes. Real tasks need millions, which is why simulators matter.

Practice

  1. 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.

  1. With γ=0.95\gamma = 0.95, compute the return of the route "five moves at −1-1, then +10+10" by hand, and compare it with the route that walks straight into the pit after two moves (−1-1, then −10-10).
Answer

Goal route: −1−0.95−0.9025−0.857−0.8145+0.7738⋅10≈−4.524+7.738=3.21-1 - 0.95 - 0.9025 - 0.857 - 0.8145 + 0.7738 \cdot 10 \approx -4.524 + 7.738 = 3.21. Pit route: −1+0.95⋅(−10)=−10.5-1 + 0.95 \cdot (-10) = -10.5. The goal route is far better, so the learned policy avoids the pit.

Test yourself

What does a reinforcement-learning agent learn from?

  1. Labelled correct actions
  2. Rewards that follow its actions
  3. Clusters in the data
  4. A test set

Why did the ε=0.1\varepsilon = 0.1 agent earn more than the greedy one?

  1. It pulled arms at random all the time
  2. Occasional exploration let it discover that arm 2 is best
  3. It had more steps
  4. Its machines paid more

In the Q-learning update, what does γ\gamma control?

  1. How fast the table is updated
  2. How much future rewards count compared with immediate ones
  3. The exploration rate
  4. 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?

  1. Overfitting
  2. Reward hacking: optimising the written reward instead of the intended goal
  3. Underfitting
  4. Data drift