Reinforcement Learning Algorithms Reference Which
You’re staring at a blank Python file. The environment is loaded. The agent is… well, it doesn’t exist yet. You’ve read the tutorials. You know what a Q-table is. You’ve seen policy networks dance across blog posts. But now, with a real problem in front of you, the list of algorithms feels like a firehose: Q-learning, DQN, PPO, A2C, A3C, SAC, TD3. They all claim to work. They all have papers with impressive graphs. But which one won’t waste three weeks of your time on a dead end?
That frozen moment is exactly what this article is for. It’s not a textbook chapter. It’s a decision-making reference card. By the time you finish reading, you’ll know which algorithm to reach for first, and—more importantly—why. We’ll build the intuition from the ground up, starting not with the algorithms themselves, but with the three questions that actually decide your choice.
The Three Questions That Actually Decide Your Algorithm
Before we name a single algorithm, we need to name the axes that separate them. Otherwise, you’re memorizing names without knowing why they differ—like learning the names of every screwdriver without knowing whether your screw is flathead or Phillips. Let’s fix that.
Think of it this way: choosing an RL algorithm is like choosing a vehicle. You wouldn’t pick a semi-truck to get groceries, and you wouldn’t pick a bicycle to move furniture. The job dictates the tool. In RL, the job is defined by three questions.
Question 1: What does your action space look like?
Are you pressing discrete buttons, or turning continuous dials? Choosing a chess move is discrete—there are exactly 64 squares, and you pick one. Steering a car is continuous—the wheel can be turned 15.3 degrees, or 15.31, or any value in a range. This distinction alone rules out entire families of algorithms. Q-learning, for instance, needs to find the best action by comparing every possible action. That’s fine when you have 64 options. It’s impossible when you have infinitely many.
Question 2: Do you have a simulator, or are you learning from a fixed dataset?
This is the online vs. offline divide. Online learning means you can interact with the environment live—you tell the agent to try something, the world responds, and you learn from that response. Think playing a video game in real time. Offline learning means you’re handed a recording of someone else playing and told to learn from that. You can’t ask “what if I’d turned left instead?” You can only study what actually happened. The algorithms we’ll cover today assume online interaction. If you’re stuck with a fixed dataset, you need offline RL—a different beast entirely.
Question 3: How much implementation complexity can you tolerate?
Be honest with yourself. Are you prototyping an idea at 11 PM and want something that works in 50 lines? Or are you deploying a system where a 10% performance gain justifies 500 lines of code and three neural networks? Some algorithms are elegant and simple but brittle. Others are robust and high-performing but require infrastructure you might not want to build. The right choice is the one you’ll actually implement correctly.
These three axes—action space, data access, and complexity tolerance—map directly onto the classic RL taxonomy. The field divides algorithms into value-based methods (they learn how good each action is), policy-based methods (they learn to output actions directly), and actor-critic methods (they do both). But we’ll introduce that taxonomy only after the intuition lands. First, let’s see how these questions play out in a decision tree you can actually use.
The Algorithm Map: A Visual Decision Tree
Here’s the moment where everything snaps into focus. The diagram below is a decision tree you can screenshot and keep. It’s a simplification—real problems blur the boundaries—but it’ll get you to the right starting point 90% of the time. We’ll flag the edge cases as we go.
# This is a readable reference artifact, not executable code.
# It encodes the decision logic you should run in your head.
def recommend_algorithm(action_space, state_space_size, need_stability, parallel_cpu):
"""
A decision tree for picking a first RL algorithm to try.
Returns a string recommendation with a one-sentence justification.
"""
if action_space == "discrete":
if state_space_size == "small":
return (
"Tabular Q-Learning: Your state space is small enough to store "
"a table. No neural networks needed. Start here."
)
else:
return (
"DQN (or extensions like Double DQN): Your state space is large "
"or continuous, so you need a function approximator. DQN is the "
"standard first choice for discrete-action problems with pixels "
"or high-dimensional sensors."
)
elif action_space == "continuous":
if need_stability and not parallel_cpu:
return (
"PPO: You need stable, reliable training on continuous actions. "
"PPO's clipping trick prevents destructive updates. It's the "
"default choice for robotics and continuous control."
)
elif parallel_cpu:
return (
"A3C: You want to train on a multi-core CPU without a GPU. "
"A3C's parallel actor-learners break correlation without a replay buffer."
)
else:
return (
"A2C: The synchronous, simpler cousin of A3C. Easier to debug, "
"often just as good. A solid baseline for continuous control."
)
else:
return (
"Hybrid action space? You're in advanced territory. Consider "
"hierarchical approaches or separate discrete/continuous policies."
)
# Example usage:
print(recommend_algorithm("discrete", "large", False, False))
print(recommend_algorithm("continuous", "large", True, False))
This tree answers one question at every branch: “What problem does this algorithm solve that the previous one couldn’t?” Q-learning solves small, discrete problems with a table. DQN solves large, discrete problems by replacing the table with a neural network. A2C/A3C solve continuous-action problems by learning a policy directly. PPO solves the instability problem that plagues vanilla policy gradients. Each step is a response to a specific failure mode. Now let’s walk through each algorithm in detail, with code you can run and outputs you can interpret.
Algorithm 1: Q-Learning — The One That Started It All
Imagine you’re learning to navigate a new city. Every time you make a turn, you jot down a note: “Turning left at the big intersection got me stuck in traffic—bad. Turning right got me to the park quickly—good.” Over time, your notebook fills with entries for every intersection and every possible turn. That notebook is a Q-table.
Q-learning is exactly that: a cheat sheet you update every time you try something. The “Q” stands for “quality”—as in, “what’s the quality of taking this action in this state?” When the agent is in state 3 and turns left, it observes the outcome, then updates its note: “My old estimate for (state 3, turn left) was 0.5, but I just got a reward of -1 and ended up in a state where my best future action is worth 0.8. Let me move my estimate a little bit toward that new information.”
Here’s the update rule. In plain English first: Move my estimate a small step toward the reward I just got plus my best guess about the future. Now in notation:
Q(s,a) ← Q(s,a) + α[r + γ·max Q(s',a') - Q(s,a)]
α(alpha) is the learning rate—how much you trust new information over old.γ(gamma) is the discount factor—how much you care about future rewards vs. immediate ones.ris the reward you just got.max Q(s',a')is your best guess about the value of the next state you landed in.
It was shown back in 1992 that, given enough visits to every state-action pair, this simple update rule converges to the optimal policy. That’s a remarkable guarantee. But it comes with a catch: you need to visit every state-action pair many times. If your state space is huge—say, every possible arrangement of pixels on a screen—you’ll never visit them all. That’s where the next algorithm comes in. But for small, discrete problems, Q-learning is still the right tool.
Let’s see it in action on a 4×4 gridworld. The agent starts in the top-left corner and needs to reach the bottom-right corner, getting a reward of +1 when it arrives. Every other step gives a small penalty of -0.01 to encourage efficiency.
import numpy as np
# --- Build a 4x4 gridworld ---
GRID_SIZE = 4
ACTIONS = ["up", "down", "left", "right"]
ACTION_TO_DELTA = {
"up": (-1, 0),
"down": (1, 0),
"left": (0, -1),
"right": (0, 1),
}
# Initialize Q-table: 4x4 grid, 4 actions per state — all zeros
Q = np.zeros((GRID_SIZE, GRID_SIZE, len(ACTIONS)))
# Hyperparameters
ALPHA = 0.1 # learning rate
GAMMA = 0.95 # discount factor
EPSILON = 0.1 # exploration rate
EPISODES = 500
def step(state, action):
"""Take an action, return (next_state, reward, done)."""
row, col = state
delta_row, delta_col = ACTION_TO_DELTA[action]
new_row = max(0, min(GRID_SIZE - 1, row + delta_row))
new_col = max(0, min(GRID_SIZE - 1, col + delta_col))
next_state = (new_row, new_col)
# Goal condition
if next_state == (GRID_SIZE - 1, GRID_SIZE - 1):
return next_state, 1.0, True
else:
return next_state, -0.01, False
print("Q-table before training (state (0,0)):")
print(Q[0, 0]) # All zeros — the agent knows nothing
# --- Training loop ---
for episode in range(EPISODES):
state = (0, 0)
done = False
while not done:
row, col = state
# Epsilon-greedy action selection
if np.random.random() < EPSILON:
action_idx = np.random.randint(len(ACTIONS))
else:
action_idx = np.argmax(Q[row, col])
action = ACTIONS[action_idx]
next_state, reward, done = step(state, action)
next_row, next_col = next_state
# The Q-learning update rule
best_next = np.max(Q[next_row, next_col])
td_target = reward + GAMMA * best_next
td_error = td_target - Q[row, col, action_idx]
Q[row, col, action_idx] += ALPHA * td_error
state = next_state
print("\nQ-table after training (state (0,0)):")
print(Q[0, 0])
print("\nPlain-English interpretation:")
print(f" Up: {Q[0, 0, 0]:.3f} — moving up hits the wall, so value stays low")
print(f" Down: {Q[0, 0, 1]:.3f} — moving down is the first step toward the goal")
print(f" Left: {Q[0, 0, 2]:.3f} — moving left hits the wall, low value")
print(f" Right: {Q[0, 0, 3]:.3f} — moving right is also a step toward the goal, but down is more direct")
Look at those numbers. Before training, every action had a value of 0.0—the agent was blind. After 500 episodes, the Q-table tells a clear story: from the starting corner, “down” and “right” have high values because they move toward the goal. “Up” and “left” have values near zero because they run into walls and waste time. The agent has learned a policy without anyone telling it the rules of the grid. That’s the magic of Q-learning. But notice the limitation: we stored a value for every single state-action pair. What if we had a million states? That’s where the table breaks.
Algorithm 2: Deep Q-Networks (DQN) — When the Cheat Sheet Won’t Fit in Memory
Here’s the crisis. An Atari game screen, downsampled to 84×84 pixels and stacked over 4 frames, has about 84×84×4 = 28,224 dimensions. If each pixel were binary, the number of possible states would be 2^28224—a number with over 8,000 digits. A Q-table would need more entries than atoms in the observable universe. You can’t build a table. You need a function approximator: something that can look at a state it’s never seen before and guess the Q-values based on patterns it learned from similar states.
A neural network is that function approximator. But here’s the catch: if you just plug a neural network into Q-learning, it fails catastrophically. Why? Because standard supervised learning assumes your training examples are independent—shuffled photos of cats and dogs, say. In RL, consecutive experiences are highly correlated. The agent sees frame 1, then frame 2 (nearly identical), then frame 3. If you train on this stream in order, the network overfits to the most recent experiences and forgets everything it learned earlier. This is called catastrophic forgetting.
DQN—introduced by DeepMind to solve this—uses two specific tricks. They’re the reason DQN works, and they’re what you need to understand to implement it correctly.
Trick 1: Experience Replay. Instead of learning from experiences in the order they happened, store every (state, action, reward, next_state) tuple in a buffer. When it’s time to learn, randomly sample a batch from that buffer. In plain English: shuffle the deck of experiences so the network doesn’t overfit to recent patterns. This breaks the correlation between consecutive samples.
Trick 2: Target Network. The Q-learning update uses max Q(s', a') as the target. But that Q-value comes from the same network you’re training. It’s like trying to hit a target that moves every time you adjust your aim. The solution: keep a frozen copy of the Q-network, update it only periodically (say, every 1,000 steps), and use that frozen copy to compute the target. Now you’re aiming at a stationary target, and learning stabilizes.
Let’s see DQN on CartPole—a classic problem with discrete actions (push left or right) but a continuous state space (cart position, cart velocity, pole angle, pole angular velocity). You can’t tabulate that.
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from collections import deque
import random
# --- A simple Q-network for CartPole ---
class QNetwork(nn.Module):
def __init__(self, state_dim, action_dim):
super().__init__()
self.net = nn.Sequential(
nn.Linear(state_dim, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, action_dim),
)
def forward(self, x):
return self.net(x)
# --- Hyperparameters ---
STATE_DIM = 4
ACTION_DIM = 2
BUFFER_SIZE = 10000
BATCH_SIZE = 64
GAMMA = 0.99
LR = 1e-3
TARGET_UPDATE_FREQ = 100
EPSILON_START = 1.0
EPSILON_END = 0.01
EPSILON_DECAY = 500
EPISODES = 300
env = gym.make("CartPole-v1")
q_network = QNetwork(STATE_DIM, ACTION_DIM)
target_network = QNetwork(STATE_DIM, ACTION_DIM)
target_network.load_state_dict(q_network.state_dict()) # Start as a copy
optimizer = optim.Adam(q_network.parameters(), lr=LR)
replay_buffer = deque(maxlen=BUFFER_SIZE)
# For tracking progress
episodes_rewards = []
epsilon = EPSILON_START
step_counter = 0
for episode in range(EPISODES):
state, _ = env.reset()
total_reward = 0
done = False
while not done:
# Epsilon-greedy action selection
if random.random() < epsilon:
action = env.action_space.sample()
else:
state_tensor = torch.FloatTensor(state).unsqueeze(0)
q_values = q_network(state_tensor)
action = q_values.argmax().item()
next_state, reward, terminated, truncated, _ = env.step(action)
done = terminated or truncated
total_reward += reward
# Store experience in replay buffer
replay_buffer.append((state, action, reward, next_state, done))
state = next_state
step_counter += 1
# Train only when we have enough experiences
if len(replay_buffer) >= BATCH_SIZE:
batch = random.sample(replay_buffer, BATCH_SIZE)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.FloatTensor(np.array(states))
actions = torch.LongTensor(actions).unsqueeze(1)
rewards = torch.FloatTensor(rewards).unsqueeze(1)
next_states = torch.FloatTensor(np.array(next_states))
dones = torch.FloatTensor(dones).unsqueeze(1)
# Current Q-values for taken actions
current_q = q_network(states).gather(1, actions)
# Target Q-values: use the TARGET network for stability
with torch.no_grad():
max_next_q = target_network(next_states).max(1, keepdim=True)[0]
target_q = rewards + GAMMA * max_next_q * (1 - dones)
loss = nn.MSELoss()(current_q, target_q)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Periodically copy Q-network weights to target network
if step_counter % TARGET_UPDATE_FREQ == 0:
target_network.load_state_dict(q_network.state_dict())
# Decay epsilon
epsilon = max(EPSILON_END, EPSILON_START - (EPSILON_START - EPSILON_END) * (episode / EPSILON_DECAY))
episodes_rewards.append(total_reward)
if episode % 50 == 0:
avg_reward = np.mean(episodes_rewards[-50:])
print(f"Episode {episode:3d} | Avg reward (last 50): {avg_reward:.1f} | Epsilon: {epsilon:.3f}")
env.close()
print(f"\nFinal average reward (last 50 episodes): {np.mean(episodes_rewards[-50:]):.1f}")
print("\nWhat's actually happening here:")
print(" - The replay buffer shuffles experiences so the network doesn't overfit to recent frames.")
print(" - The target network freezes the learning target so the network has a stable aim.")
print(" - Without these two tricks, DQN on CartPole would be wildly unstable or fail entirely.")
Watch the average reward climb. In the first few episodes, the agent is flailing—epsilon is high, so it’s exploring randomly. But as epsilon decays and the replay buffer fills, the agent starts to consistently balance the pole. The two tricks are doing the heavy lifting. Without the target network, the Q-values would oscillate wildly because the target moves every update. Without experience replay, the network would overfit to the most recent trajectory and forget how to recover from rare situations. DQN is Q-learning’s answer to the crisis of scale—but it still only works for discrete actions. For continuous control, we need a fundamentally different approach.
Algorithm 3: Advantage Actor-Critic (A2C/A3C) — Two Networks, One Goal
Now here’s the interesting part. Q-learning—and by extension DQN—has a fundamental limitation: to pick the best action, it needs to compute the maximum over all possible actions. When you have 2 actions (left/right), that’s trivial. When you have a continuous dial with infinitely many positions, you can’t take the max. You need a method that outputs actions directly, without comparing every option.
This is where policy-based methods enter the picture. Instead of learning “how good is each action?” and then picking the best one, a policy network learns to output the action itself. For a self-driving car, it might output “steer 15.3 degrees left.” No max required.
But pure policy gradients have a problem: high variance. The signal the policy uses to learn—the total reward from an episode—can fluctuate wildly just because of randomness in the environment. Actor-critic methods solve this by adding a second network: the critic. The actor says, “I think I should steer 15 degrees left.” The critic says, “Being in this state is worth about -0.3.” The actor uses the critic’s feedback to adjust: “Oh, the critic says this situation is worse than I expected. I’ll try something different next time.”
This is the hardest part: understanding why the advantage function matters. The advantage is simply A(s,a) = Q(s,a) - V(s). In plain English: “How much better is this specific action compared to the average action I could take in this state?” If turning left has a Q-value of 0.8 and the average value of being in this state is 0.5, the advantage of turning left is +0.3. The actor uses this advantage signal—not the raw Q-value—to decide how to update. Actions that are better than average get reinforced; actions that are worse than average get suppressed.
One practical breakthrough involved parallelism. Instead of using a replay buffer to break correlation (like DQN does), multiple copies of the agent run in parallel environments. Each copy computes gradients independently and sends them to a global network. Because the copies are experiencing different states at different times, their updates are naturally decorrelated. And this runs fast on a single multi-core CPU—no GPU required. A2C is the synchronous simplification: wait for all parallel agents to finish their episodes, then apply one big update. It’s simpler to implement and often just as good.
Let’s see A2C on a continuous control task. We’ll use Pendulum—the agent must swing a pendulum up and keep it balanced by applying a continuous torque.
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Normal
# --- Actor-Critic network with a shared feature extractor ---
class ActorCritic(nn.Module):
def __init__(self, state_dim, action_dim):
super().__init__()
self.shared = nn.Sequential(
nn.Linear(state_dim, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
)
# Actor outputs: mean and log_std for a Normal distribution
self.actor_mean = nn.Linear(64, action_dim)
self.actor_log_std = nn.Parameter(torch.zeros(action_dim))
# Critic outputs: a single value V(s)
self.critic = nn.Linear(64, 1)
def forward(self, x):
features = self.shared(x)
mean = self.actor_mean(features)
std = self.actor_log_std.exp().expand_as(mean)
value = self.critic(features)
return mean, std, value
# --- Hyperparameters ---
STATE_DIM = 3 # Pendulum: cos(theta), sin(theta), theta_dot
ACTION_DIM = 1 # Continuous torque in [-2, 2]
GAMMA = 0.99
LR = 3e-4
EPISODES = 500
ROLLOUT_STEPS = 2048 # Collect this many steps before updating (A2C style)
env = gym.make("Pendulum-v1")
model = ActorCritic(STATE_DIM, ACTION_DIM)
optimizer = optim.Adam(model.parameters(), lr=LR)
episodes_rewards = []
for episode in range(EPISODES):
state, _ = env.reset()
log_probs = []
values = []
rewards = []
total_reward = 0
done = False
while not done:
state_tensor = torch.FloatTensor(state).unsqueeze(0)
mean, std, value = model(state_tensor)
# Sample an action from the policy distribution
dist = Normal(mean, std)
action = dist.sample()
log_prob = dist.log_prob(action).sum(dim=-1)
# Clamp action to the environment's range
action_clamped = torch.clamp(action, -2.0, 2.0)
next_state, reward, terminated, truncated, _ = env.step(action_clamped.numpy()[0])
done = terminated or truncated
log_probs.append(log_prob)
values.append(value)
rewards.append(reward)
total_reward += reward
state = next_state
# Update when we've collected enough rollout steps
if len(rewards) >= ROLLOUT_STEPS or done:
# Compute returns and advantages
returns = []
R = 0 if done else model(torch.FloatTensor(state).unsqueeze(0))[2].item()
for r in reversed(rewards):
R = r + GAMMA * R
returns.append(R)
returns.reverse()
returns = torch.FloatTensor(returns)
values = torch.cat(values)
# Advantage = returns - values (the "how much better than average" signal)
advantages = returns - values.detach()
# Actor loss: encourage actions with positive advantage
actor_loss = -(torch.stack(log_probs) * advantages).mean()
# Critic loss: make V(s) closer to the actual return
critic_loss = nn.MSELoss()(values, returns)
total_loss = actor_loss + 0.5 * critic_loss
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
# Reset buffers
log_probs, values, rewards = [], [], []
episodes_rewards.append(total_reward)
if episode % 50 == 0:
avg_reward = np.mean(episodes_rewards[-50:])
print(f"Episode {episode:3d} | Avg reward (last 50): {avg_reward:.1f}")
env.close()
# --- Inspect the policy for a sample state ---
test_state = torch.FloatTensor([0.5, 0.8, -0.2]).unsqueeze(0) # Some pendulum state
mean, std, value = model(test_state)
print(f"\nPolicy output for a sample state:")
print(f" Mean torque: {mean.item():.3f} — the actor's best guess at the right torque")
print(f" Std deviation: {std.item():.3f} — how confident the actor is (lower = more confident)")
print(f" State value V(s): {value.item():.3f} — the critic's estimate of how good this state is")
print(f"\nInterpretation: The actor outputs a distribution over actions, not a single action.")
print(f"The critic evaluates the state, and the advantage (not shown here) tells the actor")
print(f"whether its chosen action was better or worse than the critic expected.")
Watch the average reward climb from deeply negative (the pendulum hanging down and swinging randomly) toward less negative values (the pendulum swinging up and balancing). The actor and critic are learning together—the actor gets better at choosing torques, and the critic gets better at predicting how good each state is. The advantage function is the bridge between them: it tells the actor not just “this was good” but “this was better than what you’d normally expect here.” That’s the key insight of actor-critic methods.
But there’s still a problem lurking. Policy gradient methods—including A2C—can take steps that are too large. One bad update, where the policy changes too aggressively based on noisy data, can collapse performance and the agent never recovers. That’s the problem PPO was built to solve.
Algorithm 4: Proximal Policy Optimization (PPO) — The One That Just Works
Here’s a scenario that keeps RL practitioners up at night. Your agent is training beautifully. The reward curve is climbing. Then, between one episode and the next, performance falls off a cliff. The policy took a big update based on a lucky (or unlucky) trajectory, changed too much, and now it’s producing terrible actions. Because it’s now collecting data from a broken policy, the next update is based on bad data, and the spiral continues. This is the “destructive large update” problem, and it’s why vanilla policy gradients can be so brittle.
TRPO (Trust Region Policy Optimization) solved this in 2015 with a hard mathematical constraint: the new policy can’t diverge too far from the old policy, measured by KL divergence. But TRPO is notoriously hard to implement—it requires a constrained optimization with conjugate gradient, which is the kind of thing that makes even experienced engineers reach for aspirin.
PPO, introduced by Schulman and colleagues in 2017, asked a brilliant question: what if you could get most of TRPO’s stability with a much simpler trick? The answer is clipping. Here’s how it works.
The policy gradient update depends on the ratio of the new policy’s probability of an action to the old policy’s probability: r(θ) = π_new(a|s) / π_old(a|s). If the action was good (positive advantage), we want to increase this ratio—make the action more likely. If the action was bad (negative advantage), we want to decrease it. But PPO says: you’re allowed to adjust this ratio, but only within a narrow band around 1.0—say, [0.8, 1.2]. If the update tries to push the ratio outside that band, we clip it and ignore the excess.
In plain English: “You’re allowed to become a little more confident or a little less confident in an action, but not radically so. If the data suggests a huge change, we assume it’s noise and cap the update.” This clipping trick is the entire secret to PPO’s success. It’s simple, it’s effective, and it’s why PPO became the default algorithm at OpenAI and across much of the deep RL community.
Let’s see PPO on BipedalWalker—a challenging continuous control task where a two-legged agent must learn to walk across rough terrain.
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Normal
# --- Actor-Critic network (same architecture as A2C, different update rule) ---
class ActorCritic(nn.Module):
def __init__(self, state_dim, action_dim):
super().__init__()
self.shared = nn.Sequential(
nn.Linear(state_dim, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
)
self.actor_mean = nn.Linear(64, action_dim)
self.actor_log_std = nn.Parameter(torch.zeros(action_dim))
self.critic = nn.Linear(64, 1)
def forward(self, x):
features = self.shared(x)
mean = self.actor_mean(features)
std = self.actor_log_std.exp().expand_as(mean)
value = self.critic(features)
return mean, std, value
# --- PPO Hyperparameters ---
STATE_DIM = 24 # BipedalWalker observation space
ACTION_DIM = 4 # Hip and knee torques for both legs
GAMMA = 0.99
LAMBDA = 0.95 # GAE lambda
CLIP_EPSILON = 0.2
LR = 3e-4
EPISODES = 1000
UPDATE_EPOCHS = 10
BATCH_SIZE = 64
env = gym.make("BipedalWalker-v3")
model = ActorCritic(STATE_DIM, ACTION_DIM)
optimizer = optim.Adam(model.parameters(), lr=LR)
episodes_rewards = []
for episode in range(EPISODES):
state, _ = env.reset()
states, actions, log_probs_old, rewards, values, dones = [], [], [], [], [], []
total_reward = 0
done = False
# --- Collect a trajectory ---
while not done:
state_tensor = torch.FloatTensor(state).unsqueeze(0)
mean, std, value = model(state_tensor)
dist = Normal(mean, std)
action = dist.sample()
log_prob = dist.log_prob(action).sum(dim=-1)
action_clamped = torch.clamp(action, -1.0, 1.0)
next_state, reward, terminated, truncated, _ = env.step(action_clamped.numpy()[0])
done = terminated or truncated
states.append(state)
actions.append(action)
log_probs_old.append(log_prob.item())
rewards.append(reward)
values.append(value.item())
dones.append(done)
total_reward += reward
state = next_state
episodes_rewards.append(total_reward)
# --- Compute advantages using GAE ---
advantages = []
gae = 0
for i in reversed(range(len(rewards))):
if i == len(rewards) - 1:
next_value = 0
else:
next_value = values[i + 1]
delta = rewards[i] + GAMMA * next_value * (1 - dones[i]) - values[i]
gae = delta + GAMMA * LAMBDA * (1 - dones[i]) * gae
advantages.append(gae)
advantages.reverse()
advantages = torch.FloatTensor(advantages)
returns = advantages + torch.FloatTensor(values)
# --- PPO Update with clipping ---
states_tensor = torch.FloatTensor(np.array(states))
actions_tensor = torch.cat(actions)
log_probs_old_tensor = torch.FloatTensor(log_probs_old)
for _ in range(UPDATE_EPOCHS):
# Recompute current policy's log probs and values
mean, std, current_values = model(states_tensor)
dist = Normal(mean, std)
log_probs_new = dist.log_prob(actions_tensor).sum(dim=-1)
entropy = dist.entropy().mean()
# The ratio r(θ) = π_new / π_old
ratios = torch.exp(log_probs_new - log_probs_old_tensor)
# PPO-Clip objective
surr1 = ratios * advantages
surr2 = torch.clamp(ratios, 1 - CLIP_EPSILON, 1 + CLIP_EPSILON) * advantages
actor_loss = -torch.min(surr1, surr2).mean()
# Critic loss
critic_loss = nn.MSELoss()(current_values.squeeze(), returns)
# Total loss (minus entropy bonus for exploration)
total_loss = actor_loss + 0.5 * critic_loss - 0.01 * entropy
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
# --- Track how often clipping is triggered ---
with torch.no_grad():
clipped_fraction = ((ratios < 1 - CLIP_EPSILON) | (ratios > 1 + CLIP_EPSILON)).float().mean().item()
if episode % 50 == 0:
avg_reward = np.mean(episodes_rewards[-50:])
print(f"Episode {episode:3d} | Avg reward: {avg_reward:.1f} | Clipped fraction: {clipped_fraction:.2%}")
env.close()
print(f"\nFinal average reward: {np.mean(episodes_rewards[-50:]):.1f}")
print(f"\nWhat the clipping fraction tells us:")
print(f" When {clipped_fraction:.0%} of updates are clipped, PPO is actively preventing")
print(f" the policy from changing too much. If this number is very high (>30%),")
print(f" the agent might be seeing noisy data. If it's very low (<5%), the clipping")
print(f" isn't doing much—the policy is already stable.")
Watch the clipped fraction. In early training, when the agent is flailing and the data is noisy, you’ll see a higher fraction of clipped updates—PPO is actively preventing the policy from overreacting to random lucky kicks. As training stabilizes, the clipped fraction drops because the policy is already making sensible updates. That’s PPO’s genius: it automatically applies the brakes when the data is noisy and gets out of the way when the policy is learning smoothly. No conjugate gradient, no hard constraints—just a simple clip that says “don’t change too much, too fast.”
The Reference Card: Which Algorithm for Which Problem
We’ve walked through four algorithms, each solving a specific problem the previous one couldn’t. Now let’s put it all together in a single, scannable reference. This is the section to bookmark.
import pandas as pd
def build_reference_table():
"""Generate the algorithm reference card as a formatted DataFrame."""
data = {
"Algorithm": ["Q-Learning", "DQN", "A2C/A3C", "PPO"],
"Action Space": [
"Discrete only",
"Discrete only",
"Both (discrete & continuous)",
"Both (discrete & continuous)",
],
"State Space": [
"Small & discrete",
"Large & continuous (pixels, sensors)",
"Large & continuous",
"Large & continuous",
],
"Sample Efficiency": [
"Low (needs many visits to every state)",
"Medium (replay buffer reuses data)",
"Medium (on-policy, discards old data)",
"Medium-High (on-policy, but stable updates help)",
],
"Implementation Complexity": [
"Very low (~50 lines)",
"Medium (replay buffer + target network)",
"Medium (two networks, parallel envs for A3C)",
"Medium (clipping is simple, full impl ~150 lines)",
],
"Best For": [
"Gridworlds, small control problems, teaching RL",
"Atari games, discrete-action problems with high-dim state",
"Continuous control, CPU-only training, actor-critic baseline",
"Continuous control, robotics sim, the default choice",
],
}
return pd.DataFrame(data)
reference_card = build_reference_table()
print(reference_card.to_string(index=False))
# --- Decision function you can adapt for your own projects ---
def recommend_algorithm(action_space, state_space_size, sample_efficiency_priority=False, complexity_tolerance="medium"):
"""
Encode the decision logic from the article into a reusable function.
Returns a string with the recommended algorithm and justification.
"""
if action_space == "discrete":
if state_space_size == "small":
return "Q-Learning: Small discrete problem. Start with a Q-table."
else:
return "DQN: Large discrete problem. Use a neural network with replay buffer and target network."
elif action_space == "continuous":
if complexity_tolerance == "low":
return "PPO: The stable, well-tested default for continuous control. Clipping prevents destructive updates."
elif sample_efficiency_priority:
return "SAC (not covered here): Better sample efficiency than PPO, but more complex. Consider if data is expensive."
else:
return "A2C: Simpler than PPO, good baseline. Use A3C if you need parallel CPU training."
else:
return "Hybrid action space: Consider hierarchical RL or separate policies for discrete and continuous sub-actions."
# Example usage
print("\n--- Quick recommendations ---")
print(f"Discrete, small state: {recommend_algorithm('discrete', 'small')}")
print(f"Discrete, large state: {recommend_algorithm('discrete', 'large')}")
print(f"Continuous, low complexity tolerance: {recommend_algorithm('continuous', 'large', complexity_tolerance='low')}")
This table is your starting point, not the final word. There are algorithms we haven’t covered—SAC, TD3, model-based methods, offline RL—that solve specific problems better than any algorithm on this card. But for the majority of problems you’ll encounter, the decision logic above will get you to a working prototype without wasting weeks on the wrong approach.
What We Didn’t Cover (And Where to Go Next)
Honesty about scope builds trust. This article is a reference card, not an encyclopedia. Here are the major algorithm families that didn’t fit, with one sentence on when you’d need them.
Soft Actor-Critic (SAC): When you need better sample efficiency than PPO for continuous control, and you’re willing to implement entropy regularization—SAC actively encourages exploration by rewarding the policy for being uncertain.
TD3 (Twin Delayed DDPG): When DQN’s overestimation bias is killing you on continuous-action tasks, but you don’t want a full stochastic policy like PPO. TD3 uses two Q-networks and delayed policy updates to combat overestimation.
Model-Based RL: When you can learn a world model—a simulator of the environment—and plan through it. This is an entirely different paradigm: much more sample-efficient, much more complex to implement. Think AlphaZero learning a model of chess.
Offline RL: When you have a fixed dataset and can’t interact with the environment at all. All the algorithms above assume online interaction. Offline RL is a different beast, requiring techniques to handle distribution shift.
If you want deep dives on any of these, the rest of the “Reinforcement Learning From Zero” series has you covered. But for now, you have a decision-making framework that’ll serve you in 90% of situations. Let’s make sure it sticks.
Check Your Understanding
Remember: Name the two tricks that make DQN stable.
Understand: In your own words, why can’t you use Q-learning for a self-driving car’s steering angle?
Apply: You’re building an RL agent to play a simple 5×5 grid game. Which algorithm should you start with, and why?
Analyze: A colleague used PPO for an Atari game and got worse results than DQN. Give two possible reasons why.
Evaluate: Compare A3C and A2C. Under what circumstances would you choose A3C over A2C, despite A3C’s added complexity?
Create: Design a hybrid approach: you have a robot with a discrete gripper (open/close) and a continuous arm (joint angles). How would you combine algorithms from this reference card?
Apply What You Learned
Take an RL problem you’ve encountered—or pick one from OpenAI Gym. Write down answers to the three questions from Section 2: What’s your action space? Do you have a simulator? How much complexity can you tolerate? Then use the reference card to pick an algorithm. Implement a minimal version (even just 50 lines) and run it for 10 minutes.
Deliverable: A short note—even just a comment in your code—saying: “I picked [algorithm] because [action space] and [state space]. It [did/didn’t] learn. I think [reason].”
Self-check rubric:
- Did you correctly identify your action space as discrete or continuous?
- Did you check whether your state space is small enough for a table?
- Did you notice if your algorithm assumes online interaction but you only had a dataset?
Here’s a starter template to get you going:
# --- RL Algorithm Selection Starter Template ---
# Fill in the blanks based on YOUR problem, then implement the recommended algorithm.
import gymnasium as gym
def recommend_algorithm(action_space, state_space_size, complexity_tolerance="medium"):
"""Copy the decision function from the Reference Card section above."""
if action_space == "discrete":
if state_space_size == "small":
return "Q-Learning"
else:
return "DQN"
elif action_space == "continuous":
if complexity_tolerance == "low":
return "PPO"
else:
return "A2C"
return "Unknown — check your action space classification."
# --- Inspect YOUR environment ---
# Uncomment and replace with your chosen environment:
# env = gym.make("YourEnvironment-v0")
# print(f"Action space: {env.action_space}")
# print(f"Observation space: {env.observation_space}")
# env.close()
# --- Classify your problem ---
# action_type = "discrete" if isinstance(env.action_space, gym.spaces.Discrete) else "continuous"
# state_size = "small" if ... else "large" # Your judgment call
# print(f"My action space is {action_type}, my state space is {state_size}")
# print(f"Recommended algorithm: {recommend_algorithm(action_type, state_size)}")
# --- Now implement the recommended algorithm and run it for 10 minutes ---
# (Use the code from the relevant section above as a starting point.)
Related articles
- Python Engineering Under review
Gpu Reference For Data Scientists When You Actuall
Before we talk about which GPU, we need to be honest about whether your workflow actually benefits from one. Most data scientists don’t need a GPU for their daily work.
- Python Engineering Under review
Python Desktop Gui Frameworks Compared Tkinter Vs
Before we write a single line of code, we need a mental model for comparing these tools. Think of it like choosing a vehicle.
- Python Engineering Under review
Andrew Ng S Machine Learning Courses Which One Sho
Before we talk about what exists today, we need to talk about what doesn't. Because half the confusion around 'Andrew Ng's ML course' comes from a ghost.
- Python Engineering Under review
Pip Vs Conda Vs Poetry A Package Management Refere
Let’s give that sinking feeling a name. You have a project, `data-dashboard`, that relies on `pandas==1.5.3`. It works perfectly. Months later, you start a new project, `ml-experiment`, which needs `scikit-learn==1.3.0`.
Looking for something else?
Search every article by title, summary or topic.