Reinforcement Learning Basics

Updated · 8 min read
mediumPython 3.13aimachine-learningreinforcement-learningq-learningrlhf

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

TermDescriptionOn the campus map below
AgentThe learner that takes actionsA student walking to the library
EnvironmentThe world the agent acts inA 4 by 4 map
StateThe agent's current situationThe square it is on
ActionA choice the agent can makeMove up, down, left or right
RewardA number telling the agent how good the result was+10 at the library, −5 in a puddle, −1 per step
PolicyThe agent's rule for choosing actionsAn arrow on each square
EpisodeOne attempt from start to finishOne walk from start to library

Three Kinds of Learning

SupervisedUnsupervisedReinforcement
Learns fromLabeled examplesUnlabeled dataRewards from its own actions
FeedbackThe right answer for each exampleNoneA score, often delayed
ExampleWill 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.

Trial and error turns into a policy: the shortest dry route
Python
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)
Output
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 5

Explanation:

  • Q holds 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 by gamma = 0.9 so 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

ExplorationExploitation
What it meansTrying actions to learn moreUsing what is already known
BenefitFinds better routesCollects reward now
RiskWastes steps, like episode 50Gets stuck with a route that's only good enough
Here20% random moves80% best-known moves

Where Reinforcement Learning Is Used

AreaAgent and reward
GamesWin the game: chess, Go, video games
RoboticsWalk, grasp or balance without falling
RecommendationsSuggest content that users engage with over time
OperationsCool 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:

  1. What are the agent, state, action and reward on the campus map?
  2. Why did episode 50 score worse than episode 10?
  3. What does the −1 per step teach the agent?

Quick check: reinforcement learning

4 questions
1What does an RL agent learn from?
2What is a policy?
3What does epsilon = 0.2 do?
4What did the learned policy achieve?

Key Takeaways

Quick reference

IdeaIn the example
Q-tableQ = np.zeros((4, 4, 4))
Explore or exploitrandom if rng.random() < epsilon else Q[state].argmax()
Q-learning updateQ[s, a] += alpha * (reward + gamma * Q[next].max() - Q[s, a])
Learning rate, discountalpha = 0.5, gamma = 0.9

Was this tutorial helpful?

Lesson 132 of 186