Policy Gradients & Actor–Critic
Optimizing behavior directly.
Q-learning acts by maximizing a learned value table. Policy-gradient methods skip the max: they parameterize the policy itself and climb the gradient of expected return. That handles continuous actions and policies that must be random to be optimal, and with a learned critic it becomes actor–critic, the template behind A2C, PPO and SAC.
What you’ll learn
- Derive the policy-gradient theorem in its likelihood-ratio form and turn it into the REINFORCE algorithm.
- Prove that baselines leave the gradient unbiased, and derive the variance-minimizing constant baseline.
- Build a one-step actor–critic from the TD error, and explain generalized advantage estimation as a bias–variance dial.
- Explain when policy-based methods beat value-based ones, and what makes them fragile.
Why optimize the policy directly?
Value-based methods such as Q-learning learn and act greedily on it. Policy-gradient methods instead give the policy its own parameters and improve it by gradient ascent on the expected return,
For discrete actions the usual choice is a softmax over learned preferences, for continuous actions a Gaussian whose mean (and often spread) a network outputs:
Why bother? Three reasons. With many or continuous actions, is itself an optimization problem at every step, while sampling from is cheap. Some problems need stochastic policies to be optimal: in games such as rock–paper–scissors, and whenever the agent cannot tell states apart. And smooth parameterizations give better convergence guarantees with function approximation. The costs are high-variance gradient estimates, local optima, and data that must usually come from the current policy.
Here is a problem where randomness is essential (Sutton & Barto, Example 13.1). A corridor has three cells before the goal, and each step costs 1. In the first cell left bumps into the wall and right moves on. In the second cell the actions are switched: right moves back and left moves forward. In the third, right reaches the goal. The agent's observation is the same in every cell, so its policy is a single number: the probability of choosing right.
Which probability of choosing right, used in every cell, maximizes the expected return from the first cell?
Show the answer
0.59
Always going right is a trap: the switched cell sends you back. Always going left stalls at the first wall. The optimum mixes them, , with expected return ; the derivation follows.
Let be the values of the three cells (). Each step costs 1, and the goal is worth 0:
The first equation gives . Substitute it and the third equation into the second, and solve:
Maximize . The derivative of vanishes where :
A deterministic policy ( or ) never reaches the goal. An ε-greedy policy over action values with can only express or , worth about and . A parameterized stochastic policy can represent .
| Aspect | Value-based (Q-learning, DQN) | Policy-based (REINFORCE, actor–critic) |
|---|---|---|
| What is learned | action values; the policy is | the policy itself (often a critic too) |
| Action spaces | small and discrete | any, including continuous |
| Stochastic optimal policies | not representable by a greedy policy | natural |
| Data | off-policy, replay | usually on-policy (off-policy variants exist) |
| Typical weakness | instability with function approximation | high variance, sample hunger, local optima |
The policy-gradient theorem
The objective is an expectation over trajectories whose distribution depends on : with . How can you differentiate it without knowing the dynamics?
Use . The gradient of an expectation becomes an expectation of a gradient:
A trajectory's probability factorizes into start, policy and dynamics terms. Only the policy terms depend on , so the unknown dynamics drop out:
Causality. A reward earned before time cannot depend on , and given everything up to the score has mean zero: . Dropping those terms leaves the return from time on:
Since , grouping time steps by state, with discounted visit frequencies , gives the policy-gradient theorem (Sutton, McAllester, Singh & Mansour, 2000):
Two things are remarkable. The state distribution depends on , yet its derivative never appears. And the dynamics are only ever sampled, never modeled, so the estimate is model-free. The score has simple forms: for a tabular softmax, ; for a Gaussian with mean and fixed , . REINFORCE (Williams, 1992) samples whole episodes and follows the estimate:
input: policy π_θ, value estimate V_w, step sizes α_θ and α_w
repeat for each episode:
generate S_0, A_0, R_1, …, S_{T−1}, A_{T−1}, R_T by following π_θ
for t = 0, 1, …, T−1:
G ← R_{t+1} + γ·R_{t+2} + … + γ^{T−t−1}·R_T # return from step t
δ ← G − V_w(S_t) # advantage estimate
w ← w + α_w · δ · ∇V_w(S_t) # fit the baseline
θ ← θ + α_θ · γ^t · δ · ∇log π_θ(A_t | S_t) # policy stepREINFORCE with a learned baseline (next step). With it is plain REINFORCE. Implementations usually drop the factor , which biases the estimate; the Deep Layer lesson discusses what is then being optimized.
REINFORCE estimates from sampled episodes without knowing the transition probabilities . Why is that possible?
- Because it learns a model of from the episodes first
- Because contains only policy terms: the transition probabilities do not depend on
- Because it assumes deterministic transitions
- Because the critic replaces the dynamics
Show the answer
B. Because contains only policy terms: the transition probabilities do not depend on
The log of a trajectory's probability is a sum of start, policy and transition terms. Differentiating with respect to kills every term except . The dynamics still shape the gradient, through which states and returns are sampled, but they never need to be written down.
Baselines and variance
REINFORCE is unbiased but noisy: sums many random rewards, and with all-positive rewards every sampled action is pushed up, the better ones only a little more than the worse. The fix is to compare each return with a baseline and use instead.
A baseline that does not depend on the action leaves the expected gradient unchanged:
So for one component of the score, the estimate has a mean that does not depend on , and its variance depends on only through the second moment. Minimize that:
The variance-optimal constant baseline is an average of returns weighted by the squared score. In practice a learned state value is the standard choice: simple, often close to optimal, and it turns the return into an estimate of the advantage, how much better the action was than the policy's average:
A two-armed bandit pays exactly 10 on arm 1 and 11 on arm 2. A softmax policy with one parameter , the logit of arm 2, picks each arm with probability , so the score is for arm 2 and for arm 1. Without a baseline, single-sample gradient estimates are or (mean 0.25, standard deviation 5.25). What is their variance with the baseline ?
- About 27.6, unchanged: a baseline cannot change the variance
- 0.0625
- About 5.25
- 0
Show the answer
D. 0
Both samples become : . Every sample now points the right way with the right size. Here is exactly the optimal baseline, since for both arms makes . Without it, telling the sign of a 0.25 signal through noise of 5.25 takes about samples.
Actor–critic: a learned critic, bootstrapped
REINFORCE with a baseline still waits for the end of each episode to compute . An actor–critic bootstraps instead: it replaces the return by the one-step target and uses the TD error of a learned critic as its advantage estimate. If the critic were exact, the TD error would be an unbiased estimate of the advantage:
input: policy π_θ, critic V_w, step sizes α_θ and α_w
repeat for each episode:
S ← initial state; I ← 1
while S is not terminal:
A ~ π_θ(· | S); take A, observe R and S'
δ ← R + γ·V_w(S') − V_w(S) # V_w(terminal) = 0
w ← w + α_w · δ · ∇V_w(S) # critic: TD(0)
θ ← θ + α_θ · I · δ · ∇log π_θ(A | S) # actor: advantage-weighted score
I ← γ·I; S ← S'One-step actor–critic (Sutton & Barto, §13.5). The critic usually learns faster than the actor, so that the actor follows a critic that is nearly up to date; two-timescale analyses prove convergence for linear critics of a special, "compatible" form (Konda & Tsitsiklis, 2000).
Actor–critic is an instance of generalized policy iteration: the critic evaluates the current policy, the actor improves it, and neither waits for the other to finish. Policy iteration, from Decisions: Utility, MDPs & Bandits, is the extreme case: an exact evaluation, then a greedy switch in every state. The policy-gradient theorem says the actor's step moves probability toward actions with positive advantage, the same direction as the greedy switch, only a small way.
Think first Policy iteration switches every state to its greedy action at once. Why does an actor–critic take small gradient steps instead?
Its critic is an estimate learned from samples, so a greedy switch would act on the critic's errors at full strength, and the next data would come from that possibly bad policy. With function approximation, changing parameters to fix one state changes the policy in others, so greedy switches can oscillate. With continuous actions the argmax is itself an optimization problem. And small steps keep the policy stochastic, so it keeps exploring. The price is many more rounds; Trust Regions: TRPO & PPO asks how large a step is safe.
Generalized advantage estimation, and the modern family
Between the one-step TD error and the full return lie the -step advantages. Their TD errors telescope, which gives a simple way to mix them all, generalized advantage estimation (GAE; Schulman et al., 2016):
The -step advantage estimate uses real rewards, then the critic. Adding and subtracting for each intermediate step turns it into a sum of TD errors:
Average the -step estimates with geometric weights , as the -return does for values. Each appears in every estimate with , and those weights sum to :
gives the TD error: low variance, biased by the critic. gives : an unbiased gradient for any critic, and the noisiest. Values around 0.9–0.99 are typical, and GAE paired with PPO is a common default.
import numpy as np
def gae(rewards, values, dones, gamma=0.99, lam=0.95):
"""rewards[t], dones[t] for t < T; values[t] for t <= T (values[T] bootstraps)."""
T = len(rewards)
adv = np.zeros(T)
running = 0.0
for t in reversed(range(T)):
live = 1.0 - dones[t] # 0 if the episode ended after step t
delta = rewards[t] + gamma * values[t + 1] * live - values[t]
running = delta + gamma * lam * live * running
adv[t] = running
returns = adv + values[:T] # regression targets for the critic
return adv, returnsGAE in one backward pass, using the recursion and resetting at episode boundaries; values is a NumPy array of length .
| Method | Data | Actions | Key idea |
|---|---|---|---|
| A2C / A3C (Mnih et al., 2016) | on-policy | discrete or continuous | -step advantages, entropy bonus, parallel workers instead of replay |
| TRPO (2015), PPO (2017) | on-policy | discrete or continuous | limit how far each update moves the policy |
| DDPG (2016), TD3 (2018) | off-policy, replay | continuous | deterministic actor following the critic's action gradient |
| SAC (2018) | off-policy, replay | mainly continuous | maximum-entropy objective and soft Bellman backups |
Key takeaways
- Policy-based methods do gradient ascent on for a parameterized stochastic policy, which suits continuous actions and problems whose best policy is random, like the switched corridor with .
- Policy-gradient theorem: ; the dynamics drop out, and the state distribution is never differentiated.
- Baselines leave the gradient unbiased because the score has mean zero; the variance-optimal constant is , and a learned turns returns into advantages.
- Actor–critic uses the TD error as an advantage estimate, trading variance for bias; it is generalized policy iteration with gradient steps in place of greedy switches.
- GAE, , slides from the TD error () to the Monte Carlo advantage () and feeds A2C, PPO and their relatives.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which of these "baselines" would bias the policy-gradient estimate?
- A constant
- A learned state value
- The average return of the last 100 episodes
- A learned action value of the action actually taken
Show the answer
D. A learned action value of the action actually taken
A baseline may depend on anything except the action it multiplies, because then . Subtracting correlates the baseline with the action, and the expectation no longer vanishes. (Action-dependent control variates can be used, but only with a correction term that restores unbiasedness.)
A tabular softmax policy samples action in state , and the advantage estimate is positive. After one policy-gradient update, what happens to the probabilities of the other actions in ?
- They decrease
- They are unchanged, since only is updated
- They increase
- They change only if their own advantages were estimated
Show the answer
A. They decrease
The score's component for logit is : the sampled action's logit rises by and every other logit falls by . Probabilities sum to 1, so raising one lowers the rest.
Generalized advantage estimation with uses which advantage estimate?
- The Monte Carlo return minus the baseline,
- The average of all -step advantages with equal weights
- The one-step TD error
- The action value
Show the answer
C. The one-step TD error
keeps only when : lowest variance, biased by the critic's errors. gives , which yields an unbiased gradient for any but is the noisiest.
In the switched-action corridor, why can't an ε-greedy policy over learned action values reach the optimum ?
- Because Q-learning diverges in this problem
- Because ε-greedy can only choose right with probability or , never an intermediate value
- Because the rewards are negative
- Because the optimal policy is deterministic and ε-greedy keeps exploring
Show the answer
B. Because ε-greedy can only choose right with probability or , never an intermediate value
All cells look alike, so the greedy action is the same everywhere, and ε-greedy can express only or (for ), worth about and against at . A parameterized policy can learn any .
An actor–critic replaces the Monte Carlo return in the policy update with the TD target . What is the effect?
- No effect on bias or variance
- Higher variance, but no bias
- It makes the method off-policy
- Lower variance, at the price of bias whenever
Show the answer
D. Lower variance, at the price of bias whenever
The TD target depends on one reward and one transition instead of a whole future, so it varies much less. But it trusts : if the critic is wrong, the advantage estimate is wrong in expectation. GAE's chooses a point between the two extremes.
Go deeper
- The Policy Gradient Theorem · REINFORCE, baselines and variance.
- Trust Regions: TRPO & PPO · Stable policy updates with constraints.
- Actor–Critic & Soft Actor–Critic · Combining value estimates with policies.
Further reading
- R. J. Williams, "Simple statistical gradient-following algorithms for connectionist reinforcement learning," Machine Learning 8, 229–256 (1992).
- R. S. Sutton, D. McAllester, S. Singh & Y. Mansour, "Policy gradient methods for reinforcement learning with function approximation," NeurIPS 12 (2000).
- J. Schulman, P. Moritz, S. Levine, M. I. Jordan & P. Abbeel, "High-dimensional continuous control using generalized advantage estimation," ICLR (2016).
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 13 (MIT Press, 2nd ed., 2018).