Contents/ Part XX · Reinforcement Learning/ Chapter 122

Reinforcement Learning Primer

The third paradigm needs neither labels nor a fixed dataset. An agent simply acts in a world, collects rewards, and discovers good behavior by trial and error, the same way you learned to ride a bike. We build a maze, teach an agent to solve it, and meet the dilemma at RL's core.

⏱️ ~20 min read
🐍 Notebook included
📊 Chapter 122

Supervised learning had an answer key; unsupervised learning had unlabeled structure. Reinforcement learning has neither. An agent is dropped into an environment, takes actions, and receives rewards, and from that feedback alone it must figure out how to behave. No one demonstrates the right move; the agent learns from consequences.

🎮
Reinforcement learning trains an agent to maximize cumulative reward by acting in an environment. It learns a policy (what to do in each state) guided by a value function (how good each state is), balancing exploration and exploitation.
🕹️
The chapter in one line

An agent acts in an environment to maximize reward: Q-learning discovers a policy and a value function from pure trial and error, and every RL system must balance exploring new actions against exploiting the best one it knows.

1

A Third Way to Learn

RL reframes learning as a loop. At each step the agent observes the current state, chooses an action, and the environment replies with a reward and the next state. Repeat. The agent's job is to pick actions that maximize reward over the long run, not just the next step.

The agent-environment loop AGENT chooses actions to maximize reward ENVIRONMENT returns reward and the next state action a reward r, next state s′

This tiny loop is astonishingly general. A game-playing agent sees the board (state), makes a move (action), and wins or loses (reward). A robot senses its joints, sends motor torques, and is rewarded for walking. A recommendation engine shows an item and is rewarded by a click. Same skeleton every time, which is why one set of ideas covers them all.

2

States, Actions, Rewards & the Goal

The agent does not maximize the next reward, it maximizes the return: the total reward collected from now until the episode ends. Because a reward now is usually worth more than the same reward later, future rewards are shrunk by a discount factor gamma (say 0.95) per step. A high gamma makes the agent far-sighted, willing to accept small costs now (each step in our maze costs -0.1) to reach a big payoff later (the goal, +10).

Two objects capture what the agent knows. The policy is its behavior, which action to take in each state. The value function grades states: how much return can I expect starting here, if I act well? Learning good values lets the agent compare actions ("this move leads somewhere valuable"), and the best policy simply picks the highest-value action in every state. Getting these from experience is the job of Q-learning.

3

Q-learning & the Policy It Finds

Q-learning keeps a table of action-values Q(state, action): an estimate of the return from taking that action, then behaving well afterward. Every experience nudges the table toward reality with a single rule, move Q(s,a) a little toward reward + gamma × (best Q of the next state). Run enough episodes and the estimates converge, no model of the world required.

In our 5×5 GridWorld, a random agent averages a return of about -10 (it blunders into the trap). After a few hundred episodes of Q-learning the same agent scores about +9, and the table it built encodes a clean policy: in every cell, take the highest-value action.

The learned policy: best action in every cell S GOAL TRAP # # #

The arrows form a flow that runs along the top row and down the far column, threading past the trap and walls to the goal, a route nobody programmed. The matching value function (highest near the goal, lowest by the trap) and this policy are two views of the same learned knowledge.

4

Real-World Example: Exploration vs Exploitation

Every RL agent faces one dilemma: should it exploit the best option it has found, or explore others that might be better? The cleanest place to see it is the multi-armed bandit, and a perfect real-world case is choosing which ad to show.

📂 Dataset · reinforcement-learning-primer--bandit.xlsx

Six ad variants (ad_id, headline), each with a hidden true click-through rate. The agent never sees the rate, it only observes clicks (reward 1 or 0) and must learn which ad wins. AD2 is best at 11.2%.

Turn each ad into a bandit "arm" and let different strategies choose who sees what:

StrategyHow it exploresResult
Pure greedynever, always shows the current bestcan lock onto a loser forever
Epsilon-greedyrandom 10% of the timefinds AD2, sent it ~82% of traffic
UCBfavors options it is uncertain aboutfinds AD2 fast, explores smartly

Pure greedy is a cautionary tale: commit to whatever looked best after a few noisy clicks and you may never gather the evidence to know better. A little exploration, random (epsilon-greedy) or uncertainty-driven (UCB), pays a small short-term cost to find the truly best ad, then exploits it. This same trade-off drives A/B testing, recommendation, and clinical-trial design.

5

Reinforcement Learning in Machine Learning & AI

RL powers some of the most striking results in modern AI, precisely where decisions unfold over time.

IdeaWhere it is used
Q-learning / value methodsgame AI, navigation, inventory and pricing control
Bandits (explore/exploit)ad and content selection, A/B testing, adaptive trials
Policy methodsrobotics, continuous control, self-driving simulation
Deep RLAtari, Go and chess (AlphaGo/AlphaZero), data-center energy
RLHFaligning large language models to human preferences
🤖
Why this matters for AI research

Reinforcement learning is how AI systems learn to act, not just predict. It powered the superhuman game players (AlphaGo, AlphaZero) that first showed machines could out-plan people, and it drives robotics and control, where the goal is a sequence of good decisions rather than a single label. Most visibly today, RLHF, reinforcement learning from human feedback, is a key step in aligning large language models: the model's helpful, harmless responses are shaped by a reward signal learned from human preferences. The core ideas from this chapter, reward, policy, value, and the exploration-exploitation balance, are exactly what the next chapter scales up with neural networks.

🐍

Train an agent in Python

The companion notebook builds a GridWorld from scratch, trains an agent with the Q-learning update, visualizes the learned policy and value function, and runs a multi-armed bandit on the ad data to show why exploration pays, all in pure numpy, each cell explained.

📓 View Notebook (code & outputs) ▶ Open in Colab ⬇ View / Download on GitHub

View opens the rendered notebook instantly. Open in Colab runs it live. To run locally, install numpy, pandas, matplotlib, and openpyxl.

🎓 Key Takeaways

  • RL is the third paradigm: an agent learns from rewards by acting, no labels and no fixed dataset.
  • Agent, environment, state, action, reward form a loop; the goal is to maximize cumulative discounted return.
  • The policy says what to do in each state; the value function says how good each state is.
  • Q-learning learns action-values from experience with one update rule; the greedy policy falls out of it.
  • Exploration vs exploitation is the central dilemma, you must try new actions to learn what to exploit.
6

Practice Challenges

Five short challenges. Try them in numpy before checking the solutions.

1

Random baseline

Run a random agent in the GridWorld for 200 episodes and report its average return.

Hint: pick rng.integers(4) each step; sum the rewards.
2

Train with Q-learning

Train a Q-table and report the trained agent's average return.

Hint: Q[s,a] += alpha*(r + gamma*max(Q[s2]) - Q[s,a]).
3

Read the policy

Extract the greedy policy and name the best action at the start cell.

Hint: Q.argmax(axis=2) gives the action per state.
4

Discount factor

Compare a myopic agent (gamma=0) with a far-sighted one (gamma=0.95).

Hint: retrain with each gamma; compare average returns.
5

Exploration pays

On the ad bandit, compare pure-greedy vs epsilon-greedy traffic sent to the best ad.

Hint: track N[best] / T for each strategy.
Check your work

A fully-worked solutions notebook walks through all five challenges, each verified in code. Try them yourself first, then compare.

📓 View Solutions ▶ Open Solutions in Colab ⬇ View / Download on GitHub
7

Quiz: Test Yourself

Eight quick questions on reinforcement learning. Answer them, hit Check Answers, and keep refining until you score 100%. Your progress is saved, so you can hop back to the chapter and return anytime.

➡️
Up next

Q-learning used a table, one entry per state, which cannot scale to a video game screen or a robot's cameras. Deep RL & Applications replaces the table with neural networks (DQN, policy gradients, actor-critic), and shows how RLHF uses these ideas to align large language models.