Lesson 15 of 188 min
Reinforcement learning
An agent learns from rewards by trying moves, mostly taking the best one so far and sometimes another, and passing each reward back to the moves that led to it.
After this lesson you can describe an agent, an environment, a reward and a policy, and explain the trade-off between exploring and exploiting.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Let the agent try another machine
Give each machine one pull before comparing its average. Keep the outcomes in one table so either policy gets the same result for a machine's first pull, its second pull, and so on. The agent can use only the coins it has seen. Run these two cells in order. The seed and the rounded policy draws match the video.
import numpy as np
rng = np.random.default_rng(38)
chances = np.array([.3, .5, .4, .7])
pays = rng.random((4, 1_000)) < chances[:, None]
explore_draw, machine_draw = rng.random((2, 1_000)).round(4)for explore in (0, .1, 1):
pulls = np.ones(4, dtype=int)
coins = pays[:, 0].astype(int)
for t in range(4, 1_000):
pick = min(3, int(machine_draw[t] * 4)) if explore_draw[t] < explore else int(np.argmax(coins / pulls))
coins[pick] += pays[pick, pulls[pick]]
pulls[pick] += 1
print(explore, int(coins.sum()))0 491 0.1 662 1 493
Pass the reward back one move
worth[s, a] stores the worth of action a at square s. On dry ice you can replace the old entry with the new estimate, as the video does. At a goal or hole there's no next move, so the entry gets only the reward. A discount of 0.9 makes the reward from one move later count nine tenths as much.
worth = np.zeros((16, 4))
def learn(s, a, next_s, reward, terminated, discount=.9):
future = 0.0 if terminated else worth[next_s].max()
worth[s, a] = reward + discount * future
learn(14, 2, 15, 1, True) # Right into the goal.
learn(10, 1, 14, 0, False) # Down to the square before it.
learn(6, 1, 10, 0, False)
print(worth[14, 2], worth[10, 1], worth[6, 1])1.0 0.9 0.81
Let the ice slip
FrozenLake is slippery by default. When you ask to go right from the first square, you can go right, slide down, or stay put when a slide up hits the edge. Use a smaller learning rate to move an estimate partway toward the new value when the same action can have several outcomes. See the FrozenLake documentation.
import gymnasium as gym
for slippery in (False, True):
env = gym.make("FrozenLake-v1", is_slippery=slippery)
observed = set()
for seed in range(100):
env.reset(seed=seed)
observed.add(env.step(2)[0]) # Ask to move right.
print(slippery, sorted(observed))
env.close()False [1] True [0, 1, 4]
Read both ways a try can end
In Gymnasium, reaching the goal or falling in a hole terminates the episode. Running out of steps truncates it. Either means you call reset before starting another try. When you update the table, a time limit outside the task still lets you use the estimated worth at the last square. See the Gymnasium Env API.
env = gym.make("FrozenLake-v1", is_slippery=False, max_episode_steps=1)
s, _ = env.reset(seed=0)
next_s, reward, terminated, truncated, _ = env.step(2)
learn(s, 2, next_s, reward, terminated)
print(next_s, terminated, truncated)
env.close()1 False True
Watch what the reward measures
An Atari agent learned from game points, AlphaGo learned from self-play, and a simulated robot can earn rewards for moving forward. In CoastRunners, circling targets earned more points than finishing. This toy check compares points with a finish reward. Atari paper, AlphaGo, CoastRunners.
trips = {"circle": (8, False), "race": (3, True)}
for trip, (points, finished) in trips.items():
print(trip, points, int(finished))circle 8 0 race 3 1
Run on Python 3.13.3, NumPy 2.5.5, Gymnasium 1.4.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: What machine learning is
On the 86 penguins kept aside, the rule by hand got 83 right and the computer's rule 82. So why learn a rule from examples at all?
2 of 3
An agent pulled four machines once each. Machine 4 paid nothing, so its average is 0. From now on, the agent always pulls the machine with the best average so far. What can go wrong?
3 of 3
On the ice, the only reward is 1, for the move into the goal. Every other move is worth 0.9 of the best move from the square it lands on. The path takes 4 moves. What is its first move worth?
The ideas in this lesson
- Agent, environment and reward
- An agent makes moves; its environment answers each with a reward, a number, and it learns to collect as much as it can.
- Explore or exploit
- Mostly take the move that has paid best so far, but now and then try another at random, or a better one is never found.
- Policy
- What the agent does in each situation; it is learned by passing each reward back to the moves that led to it.
It leans on
- Training a chatbot from feedback
Transcript
What the video says, part by part. Press a time to watch from there.
Learning from rewards
Here's a question. Nobody tells a game-playing AI which move is right. It only gets a reward when things go well. AI chat apps learn to reason this way too. So how does an AI learn from rewards?
Four machines
Here's a game. Four machines. Each one pays a coin, sometimes, and each has its own chance, which you can't see. You've pulled each machine once. Only machine two paid. You have a thousand pulls in all. Which plan wins the most coins?
Always pull the machine that has paid best so far?
Mostly that one, and now and then one at random?
Or always one at random?
Agent, environment, reward
First, what kind of learning is this? When a model learns from examples, each example comes with the right answer. Here, nobody says which move is right. An agent makes a move. Its environment answers with a reward, a number. In our game, the agent pulls a machine, and the machine pays one coin, or nothing. The agent's job is to collect as many coins as it can.
Always the best so far
Four machines pay coins, each with its own hidden chance, and an agent pulls them, one at a time.
So why not always pull the machine that has paid best so far? Keep track of each machine's average, and pull the best.
After the first four pulls, that's machine two.
A thousand pulls later, the agent has about four hundred and ninety coins. Pulling at random gets about the same. So what went wrong?
Machine four lost its one pull. Its average is zero, so it's never pulled again.
Machines one and three lost theirs too. But machine four pays seventy times out of a hundred. It's the best of the four.
Not just bad luck
Is that just bad luck, in this one run? Play two thousand runs, each with its own luck. More than one run in three gets stuck on a worse machine.
Explore
Here's the fix.
One pull in ten, pick a machine at random. The rest of the time, pull the best so far. Same luck as before. Each machine pays the same way, pull by pull. For more than eighty pulls, it still misses machine four. Then one random pull lands on machine four... and it pays. Machine four takes over. About six hundred and sixty coins. Over two thousand runs, it gets about six hundred and sixty on average. Never exploring gets about six hundred. Always at random, under five hundred. And pulling machine four every time would get about seven hundred. The random pulls are called exploring. Pulling the best so far is called exploiting. Explore too little, and you get stuck. Explore too much, and you waste pulls.
Where to eat
It's like choosing where to eat. Your favorite place most nights, and somewhere new now and then. But the agent only knows the coins.
The ice
An agent makes moves, and gets rewards. But what if the reward only comes at the very end?
Here's a small world, from a library called Gymnasium. Ice, with sixteen squares, four holes, and a goal. Each move takes the agent one square. The goal gives a reward of one. A hole ends the try with nothing. What to do depends on where the agent stands. A move for every square: that's its policy. We draw it as arrows.
Passing the reward back
Each square has four moves, and every move starts out worth zero. So at first, the agent picks at random. Twenty tries end in holes.
Try twenty-one reaches the goal, by luck.
Now the move into the goal is worth one. So how much is a move worth?
Its reward... plus nine tenths of the best move from the square it lands on. A reward further away counts a little less. So the move before is worth zero point nine, and the one before that, about zero point eight. Try after try, the reward is passed back... square by square.
The path
After three hundred tries, the start is worth about zero point six.
Follow the arrows from the start. How many moves to the goal?
Six, around the holes. The policy takes the move that's worth the most. And one move in ten, it still explores, at random.
A network as the policy
So where is the network in all this?
In a chatbot, the policy is the network. Where it stands is the text so far.
Its move is the next token, a small piece of text. The network gives every next token a chance, and picks one.
Now give it a math question.
It writes sixteen answers.
A check scores each one: one if it's right, zero if it's wrong.
Nobody writes the answer for it. The check only scores what it wrote.
So what does training do with them?
Say four are right.
Then the group's average is a quarter: that's how well it usually does on this question.
Every token of an answer above the average is made more likely. Every token of an answer below it, less likely. And the sixteen answers are not all the same. That's how it explores.
DeepSeek-R1-Zero
DeepSeek-R1-Zero learned to reason with rewards for correct answers and the right format. Its thinking grew longer, and it learned to check its own work.
Chatbots also learn from people's preferences. People pick the better of two answers, and that's the reward.
Reward hacking
So can a reward teach the wrong thing?
A model was trained to fix code. It was rewarded when a project's tests passed, and it could change the project's files. Guess what it learned.
To make the tests always say "passed". The agent collects the reward you measure, not what you meant. That's called reward hacking. So the reward has to measure what you really want.
In code
In code, reinforcement learning often uses a library called Gymnasium.
One line makes the ice world. Reset puts the agent at the start. Step makes a move, which Gymnasium calls an action. It gives back where the agent is now, the reward, and whether the try has ended. This agent moves at random. Out of a thousand tries, how many reach the goal?
Fifteen.
Every environment in Gymnasium runs this same loop. The agent sees where it is, makes a move, and gets a reward.
Learning from rewards
So, an agent learns from rewards. It explores a little, and exploits the rest of the time. Each reward is passed back to the moves that earned it. And its policy says what to do: arrows on the ice, a network in a chatbot.
The lab
That's the end of this unit. In its lab, you train a tiny word maker on a list of words, then tune it with rewards.
Explore a little
An agent learns by trying, and by exploring a little. Now try it on this lesson's page, and take the quiz. Pull the machines yourself, and find the best one.
You use this lesson in Lab 6: A tiny word maker, taught by rewards, which comes next.
Facts last checked on .
