Reinforcement Learning Basics
Reinforcement learning (RL) is machine learning by trial and error. An agent takes actions in an environment, receives rewards or penalties, and gradually learns a policy: which action to take in each situation to collect the most reward over time. Nobody shows it the right answers; it discovers them from the consequences of its own actions.
RL is how computers learned to beat world champions at Go, how robots learn to walk, and one of the steps that makes chatbots helpful (RLHF, below).
Key Terms
| Term | Description | On the campus map below |
|---|---|---|
| Agent | The learner that takes actions | A student walking to the library |
| Environment | The world the agent acts in | A 4 by 4 map |
| State | The agent's current situation | The square it is on |
| Action | A choice the agent can make | Move up, down, left or right |
| Reward | A number telling the agent how good the result was | +10 at the library, −5 in a puddle, −1 per step |
| Policy | The agent's rule for choosing actions | An arrow on each square |
| Episode | One attempt from start to finish | One walk from start to library |
Three Kinds of Learning
| Supervised | Unsupervised | Reinforcement | |
|---|---|---|---|
| Learns from | Labeled examples | Unlabeled data | Rewards from its own actions |
| Feedback | The right answer for each example | None | A score, often delayed |
| Example | Will this fee be paid late? | What kinds of learner are there? | What's the best route to the library? |
Example: Q-Learning on a Campus Map
Q-learning is a classic RL method. It keeps a table of Q-values: for each state and action, the reward the agent expects to collect from there on. Each step nudges one Q-value toward what actually happened.
import numpy as np
# A 4 x 4 campus map: start top-left (S), library bottom-right (L), two puddles (P) to avoid
MAP = ["S...",
".P..",
".P..",
"...L"]
MOVES = {"↑": (-1, 0), "↓": (1, 0), "←": (0, -1), "→": (0, 1)}
ACTIONS = list(MOVES)
def step(row, col, action):
dr, dc = MOVES[action]
row, col = min(max(row + dr, 0), 3), min(max(col + dc, 0), 3) # walls keep the agent on the map
cell = MAP[row][col]
reward = 10 if cell == "L" else -5 if cell == "P" else -1 # every ordinary step costs 1
return row, col, reward, cell == "L"
rng = np.random.default_rng(0)
Q = np.zeros((4, 4, 4)) # Q[row, col, action]: expected future reward of each action
alpha, gamma, epsilon = 0.5, 0.9, 0.2 # learning rate, how much the future counts, how often to explore
for episode in range(1, 301):
row, col, total, done = 0, 0, 0, False
while not done:
a = rng.integers(4) if rng.random() < epsilon else int(Q[row, col].argmax()) # explore or exploit
new_row, new_col, reward, done = step(row, col, ACTIONS[a])
best_next = 0 if done else Q[new_row, new_col].max()
Q[row, col, a] += alpha * (reward + gamma * best_next - Q[row, col, a]) # the Q-learning update
row, col, total = new_row, new_col, total + reward
if episode in (1, 10, 50, 300):
print(f"Episode {episode:3}: total reward {total}")
print("Learned policy (best action in each square):")
for r in range(4):
print(" ".join(MAP[r][c] if MAP[r][c] in "PL" else ACTIONS[int(Q[r, c].argmax())] for c in range(4)))
row, col, total, done, path = 0, 0, 0, False, []
while not done: # follow the learned policy, no exploring
action = ACTIONS[int(Q[row, col].argmax())]
row, col, reward, done = step(row, col, action)
total, path = total + reward, path + [action]
print("Following it:", " ".join(path), "| steps", len(path), "| reward", total)Episode 1: total reward -66
Episode 10: total reward 5
Episode 50: total reward -2
Episode 300: total reward 5
Learned policy (best action in each square):
→ → → ↓
↓ P → ↓
↓ P → ↓
→ → → L
Following it: → → → ↓ ↓ ↓ | steps 6 | reward 5Explanation:
Qholds 4 numbers for each of the 16 squares, one per action, all starting at 0.- In each step, the agent usually takes the action with the highest Q-value (exploit), but 20% of the time (
epsilon = 0.2) it picks at random (explore), so it keeps trying new routes. - The update line is the heart of Q-learning: the new estimate moves halfway (
alpha = 0.5) toward the reward just received plus the best Q-value of the next square, discounted bygamma = 0.9so sooner rewards count more. - Episode 1 scored −66: with no knowledge, the agent wandered and stepped in puddles. By episode 10 it scored 5. Episode 50 scored −2 because random exploring still sometimes walks into a puddle.
- The learned policy avoids both puddles. Following it with no exploring takes 6 steps for a reward of 5 (5 steps at −1, then +10), the best possible on this map.
Exploration and Exploitation
| Exploration | Exploitation | |
|---|---|---|
| What it means | Trying actions to learn more | Using what is already known |
| Benefit | Finds better routes | Collects reward now |
| Risk | Wastes steps, like episode 50 | Gets stuck with a route that's only good enough |
| Here | 20% random moves | 80% best-known moves |
Where Reinforcement Learning Is Used
| Area | Agent and reward |
|---|---|
| Games | Win the game: chess, Go, video games |
| Robotics | Walk, grasp or balance without falling |
| Recommendations | Suggest content that users engage with over time |
| Operations | Cool data centers or manage traffic lights with less energy |
| Chatbots (RLHF) | Write answers that people rate as helpful and safe |
RLHF (reinforcement learning from human feedback) is how many chat models are tuned after pre-training. People compare pairs of answers, a reward model learns to predict which answers people prefer, and the language model is trained with RL to earn high scores from it. Related methods train against AI feedback or automated checks, such as whether code passes its tests.
Common Mistakes
Reward hacking. Agents find loopholes. A cleaning robot rewarded for "no visible mess" might learn to cover its camera. Design rewards for what you really want.
Never exploring. An agent that always exploits can settle on a poor route forever.
Expecting fast learning. Even this tiny map took dozens of episodes; real tasks can need millions.
Using RL where supervised learning fits. If the right answers are known, learn from them directly.
Interview Corner
What is the difference between reinforcement learning and supervised learning?
Supervised learning is told the right answer for each example; reinforcement learning only receives rewards for its actions, often delayed, and must discover good actions by trial and error.
What is the exploration-exploitation trade-off?
Choosing between trying new actions to learn more and using the best-known action to collect reward. Too little exploration misses better options; too much wastes effort. Epsilon-greedy is a simple balance.
Practice
Exercise: a costlier puddle. Change the puddle reward from −5 to −1, the same as an ordinary step, and rerun. Does the learned route change? Why might the agent now walk through a puddle?
Check your understanding:
- What are the agent, state, action and reward on the campus map?
- Why did episode 50 score worse than episode 10?
- What does the −1 per step teach the agent?
Key Takeaways
Quick reference
| Idea | In the example |
|---|---|
| Q-table | Q = np.zeros((4, 4, 4)) |
| Explore or exploit | random if rng.random() < epsilon else Q[state].argmax() |
| Q-learning update | Q[s, a] += alpha * (reward + gamma * Q[next].max() - Q[s, a]) |
| Learning rate, discount | alpha = 0.5, gamma = 0.9 |
Was this tutorial helpful?