Reinforcement Learning Cheat Sheet — Q-Learning, DQN, PPO, Policy Gradients | Dataplexa
← Back to Cheat Sheets
Sheet icon

Reinforcement Learning Cheat Sheet

MDP · reward · policy · Q-learning · DQN · policy gradients · Actor-Critic · PPO

Sheet 4 of 4 Specialized ML Advanced Printable

Markov Decision Process (MDP)

RL Foundation

Every RL problem is formally defined as an MDP. An agent observes a state, takes an action, receives a reward, and transitions to the next state — repeatedly.

MDP Tuple
MDP = (S, A, P, R, γ)
S = state space · A = action space · P(s'|s,a) = transition probability · R(s,a) = reward function · γ ∈ [0,1) = discount factor
Return (Discounted Cumulative Reward)
Gt = Σk=0 γk Rt+k+1
γ close to 1 = far-sighted (values future rewards). γ close to 0 = short-sighted (greedy). Discount ensures convergence for infinite horizons.
ElementSymbolExample (Cart-Pole)
States ∈ SCart pos, velocity, angle, angular vel
Actiona ∈ APush left or push right
Rewardr = R(s,a)+1 for every step pole stays upright
TransitionP(s'|s,a)Physics simulation → next state
Policyπ(a|s)Prob of pushing left given current state
EpisodeτSequence until pole falls (terminal)
Markov property: The future depends only on the current state, not the full history: P(st+1|st, at) = P(st+1|s0:t, a0:t). This is the key assumption that makes RL tractable.
State-Value Function Vπ
Vπ(s) = 𝔼π[Gt | St=s]
Expected return starting from state s, following policy π. Answers: "how good is it to be in state s?"
Action-Value Function Qπ
Qπ(s,a) = 𝔼π[Gt | St=s, At=a]
Expected return taking action a in state s, then following policy π. The basis of Q-learning and DQN.

Bellman Equations

Dynamic Programming
Bellman Expectation — Vπ
Vπ(s) = Σa π(a|s) [R(s,a) + γ Σs' P(s'|s,a) Vπ(s')]
Recursive relationship: value of s = immediate reward + discounted value of next states, averaged over policy and transitions.
Bellman Optimality — Q*
Q*(s,a) = R(s,a) + γ Σs' P(s'|s,a) maxa' Q*(s',a')
Optimal Q-value: take action a, then act optimally thereafter. The optimal policy is π*(s) = argmaxa Q*(s,a).
Advantage Function
Aπ(s,a) = Qπ(s,a) − Vπ(s)
How much better action a is compared to the average action in state s. A > 0 means action is better than baseline. Used in A2C, PPO.
Curse of dimensionality: Tabular methods store V or Q for every (s,a) pair. With large or continuous spaces this is infeasible — we need function approximation (neural networks).

Q-Learning & SARSA

Tabular Methods
Q-Learning Update (Off-Policy)
Q(s,a) ← Q(s,a) + α[r + γ maxa'Q(s',a') − Q(s,a)]
α = learning rate. Learns optimal Q* regardless of the behaviour policy. The bracketed term is the TD error δ.
SARSA Update (On-Policy)
Q(s,a) ← Q(s,a) + α[r + γ Q(s',a') − Q(s,a)]
Uses actual next action a' (from the current policy), not the greedy max. Safer in stochastic environments. Converges to Qπ, not Q*.
Q-Learning — Tabular Python
import numpy as np

Q = np.zeros((n_states, n_actions))
alpha, gamma, eps = 0.1, 0.99, 0.1

for episode in range(1000):
  s = env.reset()
  while True:
    # ε-greedy action selection
    if np.random.rand() < eps:
      a = env.action_space.sample()
    else:
      a = np.argmax(Q[s])
    s2, r, done, _ = env.step(a)
    td = r + gamma*np.max(Q[s2])-Q[s,a]
    Q[s,a] += alpha * td
    s = s2
    if done: break

Deep Q-Network (DQN)

Value-Based Deep RL

DQN replaces the Q-table with a neural network Q(s,a;θ) that generalises across large state spaces (e.g. raw pixels).

DQN Loss (MSE of TD Error)
L(θ) = 𝔼[(r + γ maxa' Q(s',a';θ⁻) − Q(s,a;θ))²]
θ = online network weights. θ⁻ = frozen target network weights. Target network updated every C steps to stabilise training.
Double DQN — Reduces Overestimation
y = r + γ Q(s', argmaxa' Q(s',a';θ); θ⁻)
Action selection with online network θ, value estimation with target θ⁻. Decouples selection from evaluation — reduces upward bias.
DQN InnovationProblem It Solves
Experience ReplayBreaks correlation between consecutive samples; reuses data
Target NetworkStabilises training by fixing Q-target for C steps
Double DQNReduces Q-value overestimation bias
Dueling DQNSeparates V(s) and A(s,a) streams for better generalisation
Prioritised ReplaySamples high TD-error transitions more frequently
Noisy NetsLearnable noise for exploration instead of ε-greedy
DQN with Stable-Baselines3
from stable_baselines3 import DQN
import gymnasium as gym

env = gym.make("CartPole-v1")

model = DQN(
  "MlpPolicy", env,
  learning_rate=1e-4,
  buffer_size=10_000,
  learning_starts=1000,
  batch_size=32,
  tau=1.0,
  gamma=0.99,
  train_freq=4,
  target_update_interval=1000,
  exploration_fraction=0.1,
  exploration_final_eps=0.05,
  verbose=1
)
model.learn(total_timesteps=50_000)
model.save("dqn_cartpole")
When to use DQN: Discrete action spaces only. For continuous actions (robotics, locomotion), use policy gradient methods (PPO, SAC, TD3) instead.

Policy Gradient Methods

REINFORCE · Actor-Critic

Instead of learning Q-values, policy gradient methods directly optimise the policy πθ(a|s) by gradient ascent on expected return.

Policy Gradient Theorem
θJ(θ) = 𝔼π[∇θ log πθ(a|s) · Qπ(s,a)]
Log-derivative trick: ∇ log π · Q. Update θ to increase probability of high-return actions. Foundation of REINFORCE and all Actor-Critic methods.
REINFORCE with Baseline
θJ ≈ Σtθ log πθ(at|st) (Gt − b(st))
b(s) = baseline (usually V(s)) reduces variance without adding bias. Gt − b(st) = advantage estimate.
MethodTypeKey Property
REINFORCEMonte Carlo PGSimple, high variance
A2CAdvantage ACSynchronous, stable
A3CAsync ACParallel workers, faster
PPOClipped PGBest default, robust
TRPOTrust regionTheoretically safe updates

PPO — Proximal Policy Optimisation

Default Choice
PPO Clipped Objective
LCLIP(θ) = 𝔼t[min(rt(θ)Ât, clip(rt(θ), 1−ε, 1+ε)Ât)]
rt(θ) = πθ(a|s) / πθold(a|s) = probability ratio. ε = 0.2 typical. Clip prevents large policy updates that destabilise training.
PPO Full Loss
L = LCLIP − c1LVF + c2S[πθ]
LVF = value function MSE loss. S = entropy bonus for exploration. c1=0.5, c2=0.01 typical. Single network for actor + critic.
PPO with Stable-Baselines3
from stable_baselines3 import PPO

model = PPO(
  "MlpPolicy", env,
  learning_rate=3e-4,
  n_steps=2048,      # rollout buffer
  batch_size=64,
  n_epochs=10,       # update epochs
  gamma=0.99,
  gae_lambda=0.95,   # GAE smoothing
  clip_range=0.2,    # ε clipping
  ent_coef=0.0,      # entropy coeff
  vf_coef=0.5,       # value loss coeff
  verbose=1
)
model.learn(total_timesteps=1_000_000)
GAE (Generalised Advantage Estimation): λ=0 → TD(0) advantage (low var, high bias). λ=1 → Monte Carlo (high var, low bias). λ=0.95 balances both.

Actor-Critic, SAC & TD3

Continuous Action RL

Actor-Critic methods maintain two networks: the actor πθ(a|s) selects actions; the critic Vφ(s) or Qφ(s,a) estimates value and provides a baseline.

Actor Update (Policy Gradient)
θJ = 𝔼[∇θ log πθ(a|s) · A(s,a)]
Advantage A(s,a) from critic reduces variance. Actor improves policy. Critic improves value estimates. Both updated simultaneously.
SAC Entropy-Augmented Objective
J(π) = Σt 𝔼[r(st,at) + α H(π(·|st))]
α = temperature. H = entropy. Maximising entropy encourages exploration and prevents premature convergence. α auto-tuned in SAC.
AlgorithmAction SpaceKey FeatureBest For
A2CBothSynchronous, simpleDiscrete + continuous
PPOBothClipped ratio, robustMost tasks — default
SACContinuousEntropy maximisationRobotics, locomotion
TD3ContinuousTwin critics + delayed actorRobotics, high precision
DDPGContinuousDeterministic policyPredecessor to TD3/SAC
SAC — Stable-Baselines3
from stable_baselines3 import SAC
import gymnasium as gym

env = gym.make("Pendulum-v1")
model = SAC(
  "MlpPolicy", env,
  learning_rate=3e-4,
  buffer_size=1_000_000,
  batch_size=256,
  gamma=0.99,
  tau=0.005,
  ent_coef='auto',  # auto-tune α
  verbose=1
)
model.learn(100_000)
TD3 TrickWhy It Helps
Twin CriticsTake min of 2 Q-estimates → reduces overestimation
Delayed ActorUpdate policy every 2 critic steps → more stable
Target NoiseAdd noise to target actions → smooths Q-landscape
HyperparameterTypical ValueEffect
gamma0.99Discount — horizon length
tau0.005Soft target update rate
buffer_size1MReplay memory capacity
batch_size256SGD mini-batch
learning_rate3e-4Adam lr for all networks

Exploration Strategies

Exploration vs Exploitation

The agent must balance exploring new actions to discover better rewards vs exploiting known good actions.

ε-Greedy
a = argmax Q(s,a) with prob 1−ε, else random
ε decays from 1.0 → 0.05 over training. Simple but effective for discrete actions.
Upper Confidence Bound (UCB)
a* = argmaxa [Q(a) + c √(ln t / N(a))]
N(a) = times action a was taken. Explores actions with high uncertainty (low N). Optimistic in the face of uncertainty.
StrategyHowBest For
ε-greedyRandom action with prob εDQN, tabular
BoltzmannSample ∝ exp(Q/T)Soft preference
UCBOptimistic upper boundBandits, planning
Entropy bonusAdd H(π) to rewardSAC, PPO
Noisy NetsLearnable weight noiseRainbow DQN
Intrinsic rewardBonus for novel statesSparse reward envs
Sparse rewards: When rewards are rare (e.g. reaching a goal in a maze), pure ε-greedy fails. Use Hindsight Experience Replay (HER), curiosity-driven exploration, or reward shaping.

Reward Shaping & Design

Reward Engineering
Reward TypeExampleRisk
Sparse+1 on goal, 0 otherwiseHard to learn from
DenseDistance to goal each stepMay exploit reward
ShapedExtra bonus for sub-goalsReward hacking
Potential-basedφ(s') − φ(s) shapingSafe — preserves optima
IntrinsicSurprise / novelty bonusAgent ignores task
  1. Define the goal clearly — what does success look like? Avoid proxy rewards that can be gamed
  2. Start sparse — if the agent can learn, sparse is cleanest and most reliable
  3. Add shaping carefully — only add dense components if sparse fails; use potential-based shaping to preserve optimal policy
  4. Check for reward hacking — agent will maximise reward, not your intent; watch for unexpected behaviours
Goodhart's Law in RL: "When a measure becomes a target, it ceases to be a good measure." Agents exploit any gap between your reward function and your true objective.

Algorithm Selection & RL Libraries

Practical Guide
SituationRecommended Algorithm
Discrete actions, small state spaceQ-Learning / tabular
Discrete actions, pixel/large stateDQN / Rainbow
Continuous actions, any taskPPO (start here)
Continuous actions, sample efficiency criticalSAC or TD3
Multi-agent environmentsMAPPO, QMIX
Sparse rewards, goal-conditionedHER + SAC/TD3
Sim-to-real roboticsPPO + domain randomisation
LLM alignment / fine-tuningPPO + RLHF (TRL library)
LibraryBest For
stable-baselines3Production RL, all major algos
gymnasiumStandard envs (CartPole, Atari, MuJoCo)
ray[rllib]Distributed, large-scale RL
cleanrlSingle-file implementations, research
tianshouModular, PyTorch-native
trlRLHF for LLMs (PPO, DPO)
Full Training Loop with Callbacks
from stable_baselines3 import PPO
from stable_baselines3.common.callbacks import (
  EvalCallback, StopTrainingOnRewardThreshold)
from stable_baselines3.common.monitor import Monitor
import gymnasium as gym

env      = Monitor(gym.make("LunarLander-v2"))
eval_env = Monitor(gym.make("LunarLander-v2"))

# Stop when mean reward >= 200
stop_cb = StopTrainingOnRewardThreshold(
  reward_threshold=200, verbose=1)

eval_cb = EvalCallback(
  eval_env,
  callback_on_new_best=stop_cb,
  eval_freq=5000,
  best_model_save_path="./logs/",
  verbose=1)

model = PPO("MlpPolicy", env,
  learning_rate=3e-4, verbose=1)
model.learn(
  total_timesteps=500_000,
  callback=eval_cb)

# Load and evaluate best model
best = PPO.load("./logs/best_model")
obs, _ = eval_env.reset()
while True:
  action, _ = best.predict(obs)
  obs, r, done, _, _ = eval_env.step(action)
  if done: break

Reinforcement Learning Mastery Checklist

Self-Assessment

Foundations & Value Methods

  • Define an MDP with S, A, P, R, γ for a real problem
  • Explain the Markov property and why it matters
  • Derive the Bellman optimality equation for Q*
  • Implement tabular Q-learning with ε-greedy exploration
  • Distinguish on-policy (SARSA) from off-policy (Q-learning)
  • Explain experience replay and target networks in DQN

Policy Gradient & Actor-Critic

  • State the policy gradient theorem and its intuition
  • Explain how a baseline reduces variance in REINFORCE
  • Describe the PPO clipped objective and why clipping helps
  • Distinguish GAE λ=0 vs λ=1 and choose an intermediate value
  • Explain SAC's entropy maximisation and auto-tuned temperature
  • Name the 3 TD3 tricks and the problem each solves

Exploration, Reward & Practice

  • Choose the right exploration strategy for discrete vs continuous actions
  • Design a reward function and check it for Goodhart's Law violations
  • Apply potential-based reward shaping without changing the optimal policy
  • Train a PPO agent on LunarLander with EvalCallback
  • Select the right algorithm given action space and sample budget
  • Use stable-baselines3 to train, save, and evaluate any RL model

Specialized ML series complete! Explore more series on Dataplexa — Deep Learning (CNN, RNN, Transformers), Statistics & Math, and Language series (Python, JavaScript, Rust).

← Browse All Cheat Sheets
← Back