Advanced Topics
Reinforcement Learning - Teaching Agents to Make Decisions
Learn how agents learn optimal strategies through trial and error in interactive environments.
- Reward-based learning - optimize cumulative rewards over time
- Exploration vs exploitation - balance trying new actions and using known good ones
- Policy optimization - learn the best action for each state
The best way to predict the future is to invent it.
Reinforcement Learning — Complete Guide
Reinforcement learning trains agents to make decisions by maximizing cumulative reward through trial and error.
RL Framework
Agent-Environment Interaction Loop
How the RL interaction loop works: This diagram shows the fundamental cycle of reinforcement learning. The Agent (blue, left) maintains a policy π(a|s) — a strategy mapping states to actions — along with value functions V(s) and Q(s,a) that estimate expected rewards. At each time step, the agent observes the current state s_t, chooses an action a_t based on its policy, and sends it to the Environment (green, right). The environment responds with a new state s_{t+1} (based on transition dynamics P(s'|s,a)) and a reward signal r_t (feedback on how good the action was). The reward flows back to the agent (golden dashed lines) to update its policy. The agent's goal: learn a policy that maximizes cumulative reward over time. The bottom text summarizes the loop: observe → act → receive reward → observe new state → repeat. This trial-and-error process is how RL agents learn to play games, control robots, and make decisions.
MDP (Markov Decision Process)
A formal framework for RL:
Where:
- : State space
- : Action space
- : Transition probability
- : Reward function
- : Discount factor
MDP State Transition Diagram
How an MDP models decision-making: This state transition diagram shows the formal framework underlying RL. Each circle represents a state (s₁ through s₄) — a specific situation the agent can be in. The arrows represent actions (a₁ through a₄) that transition between states, each labeled with its transition probability P and reward R. For example, from state s₁, taking action a₁ leads to s₂ with probability 0.8 and reward +1. The agent's goal is to find the optimal policy — which action to take in each state — that maximizes cumulative reward. The terminal state (red) indicates where episodes end. The Markov property means transitions depend ONLY on the current state, not the history. The discount factor γ controls how much the agent values future rewards vs immediate ones: γ=0 means only immediate rewards matter, γ→1 means the agent plans far ahead.
Q-Learning
Q-Learning Convergence Visualization
The Update Written Out
The table update is short enough to write in full, and doing so exposes the two pieces that are easy to swap by accident. The target is the reward plus the discounted value of the best action available in the next state, and the difference between that target and the current estimate is the temporal-difference error that the learning rate scales. The maximum in the target is taken over actions the agent might take later, not over the action it actually took, and that is precisely what makes the method off-policy: it can learn an optimal policy while following an exploratory one.
import random
import numpy as np
Q = np.zeros((n_states, n_actions))
alpha, gamma, epsilon = 0.1, 0.99, 0.1
for episode in range(2000):
s = env.reset()
done = False
while not done:
if random.random() < epsilon:
a = env.action_space.sample() # explore
else:
a = int(np.argmax(Q[s])) # exploit
s2, r, done, _ = env.step(a)
target = r if done else r + gamma * Q[s2].max()
Q[s, a] += alpha * (target - Q[s, a]) # the update rule
s = s2
epsilon = max(0.01, epsilon * 0.995) # decay exploration
Decaying epsilon is what the two shaded regions in the diagram describe. Early episodes are dominated by random actions, so every state gets visited and every row of the table receives signal; later episodes mostly follow the current estimates, and the values settle toward the fixed point of the update. If epsilon is never decayed the estimates keep being pulled around by exploration forever, and if it is decayed too fast the agent commits to a policy it discovered before the table was filled in.
Deep Q-Network (DQN)
DQN Architecture
How DQN replaces the Q-table with a neural network: The Q-learning approach above uses a lookup table, which becomes impossible when states are high-dimensional (e.g., game screens with millions of pixel combinations). DQN solves this by using a neural network to approximate Q-values. The input is the state s (e.g., an 84×84×4 image stack — 4 consecutive frames for motion). The network has two convolutional layers (32 filters 8×8, then 64 filters 4×4) to extract visual features, a fully connected layer (512 units), and outputs Q(s,a) for EACH possible action simultaneously. The agent picks the action with highest Q-value. The loss function at the bottom shows how training works: the target is r + γ·max Q(s',a') (the Bellman equation), and the network learns to predict this target. The target network θ⁻ (updated periodically) stabilizes training by providing consistent targets.
Policy Gradient
The Whole Algorithm in One Loop
REINFORCE is the shortest complete policy gradient, and the loop below is the entire method: sample actions, record their log probabilities, discount the rewards that followed, and push each action's probability in proportion to how good the return turned out to be. Actions taken after a good outcome become more likely, actions taken after a bad one become less likely, and the gradient needs no model of the environment to do it.
The centreing and scaling applied to the returns are not cosmetic. A trajectory with uniformly positive returns would otherwise raise every probability it contains, including the ones that led nowhere, which adds variance without adding information. Subtracting the mean of the batch acts as a crude baseline, and normalising makes the step size comparable across episodes with very different rewards.
import torch
from torch.distributions import Categorical
def discount(rewards, gamma=0.99):
G, out = 0.0, []
for r in reversed(rewards):
G = r + gamma * G
out.append(G)
return torch.tensor(list(reversed(out)))
for episode in range(1500):
log_probs, rewards = [], []
state = torch.as_tensor(env.reset(), dtype=torch.float32)
done = False
while not done:
dist = Categorical(policy(state))
action = dist.sample()
log_probs.append(dist.log_prob(action))
state, reward, done, _ = env.step(action.item())
rewards.append(reward)
G = discount(rewards)
G = (G - G.mean()) / (G.std() + 1e-8) # baseline and scaling
loss = -(torch.stack(log_probs) * G).sum()
optimizer.zero_grad()
loss.backward()
optimizer.step()
Variance remains the weakness of this estimator: a single trajectory is a very noisy estimate of the expected return, which is why REINFORCE needs many episodes and why the critic in the next section exists.
Actor-Critic
Actor-Critic Architecture
Common Mistakes & How to Avoid Them
Common Mistakes
Evaluating the greedy policy while epsilon is still high and concluding that Q-learning has failed to learn anything
Fix: Report the return of the argmax policy measured separately from training episodes, and let epsilon finish decaying before the first evaluation
Updating the Q-network toward its own predictions with no target network in a deep setting, so the estimates chase themselves and diverge
Fix: Compute the target with a slowly updated copy of the network, and sample transitions from a replay buffer so consecutive updates are not correlated
Applying REINFORCE to raw undiscounted rewards with no baseline, then blaming the algorithm for refusing to converge
Fix: Discount the returns, centre them within the batch, and normalise the scale so the gradient step size is comparable across episodes
Key Takeaways
What to Learn Next
-> Neural Networks Deep RL combines neural nets with RL.
-> Model Evaluation Measure and compare model performance.
-> Time Series Apply RL to sequential decision making.
-> Causal Inference Understand cause and effect in data.
-> ML Ethics Consider responsible AI development.
-> ML System Design Build end-to-end ML systems.