Skip to content

Policy Gradients

Learning policies directly — REINFORCE, the policy gradient theorem, and variance reduction


One-Sentence Summary

Policy gradients optimize a parameterized policy directly by estimating gradients of expected return through sampled trajectories, avoiding the need for explicit value function maximization.


Why Direct Policy Optimization?

Limitations of Value-Based Methods

Value-based methods (Q-learning, DQN) learn an action-value function Q(s,a) and derive a policy implicitly:

π(s)=argmaxaQ(s,a)

This approach has fundamental limitations:

IssueDescription
Discrete actions onlyArgmax requires enumeration over all actions
Deterministic policiesCannot represent stochastic behavior
High-dimensional actionsIntractable for continuous control
Indirect optimizationOptimizing Q does not directly optimize policy performance

Advantages of Policy Gradients

Policy gradient methods parameterize the policy directly as πθ(a|s) and optimize parameters θ to maximize expected return:

  • Continuous actions: Natural representation via Gaussian policies
  • Stochastic policies: Enable exploration and handle partial observability
  • Direct optimization: Gradient ascent on the true objective
  • Smoother optimization: Small θ changes yield small policy changes

Policy Evolution Animation

The animation shows how a policy evolves during training, with action probabilities shifting toward the optimal action as the agent learns.


Policy Parameterization

The Policy Network

A parameterized policy πθ(a|s) maps states to action distributions:

Discrete Actions: Softmax Policy

For discrete action spaces, output logits and apply softmax:

πθ(a|s)=exp(fθ(s,a))aexp(fθ(s,a))

where fθ(s,a) is the network output (logit) for action a.

Continuous Actions: Gaussian Policy

For continuous actions, output mean and variance of a Gaussian:

πθ(a|s)=N(μθ(s),σθ(s)2)

The network outputs μθ(s) (mean) and optionally logσθ(s) (log standard deviation).

Log probability for gradients:

logπθ(a|s)=(aμθ(s))22σθ(s)2logσθ(s)12log(2π)

The Policy Gradient Theorem

Objective Function

We want to maximize expected cumulative reward (return):

J(θ)=Eτπθ[t=0Tγtrt]=Eτπθ[R(τ)]

where τ=(s0,a0,r0,s1,a1,r1,) is a trajectory.

The Gradient

The key insight: we can compute the gradient of J(θ) even though the expectation is over trajectories that depend on θ:

θJ(θ)=Eτπθ[R(τ)t=0Tθlogπθ(at|st)]

Derivation Intuition

The derivation uses the log-derivative trick:

θπθ(a|s)=πθ(a|s)θlogπθ(a|s)

Starting from the objective:

J(θ)=τP(τ|θ)R(τ)

Taking the gradient:

θJ(θ)=τθP(τ|θ)R(τ)

Applying the log-derivative trick:

=τP(τ|θ)θlogP(τ|θ)R(τ)

Since P(τ|θ)=p(s0)tπθ(at|st)p(st+1|st,at), only the policy terms depend on θ:

θlogP(τ|θ)=t=0Tθlogπθ(at|st)

This yields the policy gradient theorem:

θJ(θ)=Eτπθ[R(τ)t=0Tθlogπθ(at|st)]

Key insight: The gradient is an expectation, so we can estimate it by sampling trajectories.

Gradient Direction in Parameter Space

Policy gradient ascent in parameter space: arrows show gradient directions pointing toward regions of higher expected return.


REINFORCE Algorithm

Algorithm Overview

REINFORCE (Williams, 1992) is the simplest policy gradient algorithm:

Algorithm: REINFORCE
─────────────────────────────────────
1. Initialize policy parameters θ
2. For each episode:
   a. Generate trajectory τ = (s₀, a₀, r₀, ..., s_T)
   b. Compute return R(τ) = Σᵢ γⁱrᵢ
   c. For each timestep t:
      - Compute gradient: ĝ = R(τ) ∇_θ log π_θ(aₜ|sₜ)
      - Update: θ ← θ + α ĝ

Monte Carlo Estimation

The gradient estimate uses complete episodes (Monte Carlo):

g^=1Nn=1NR(τn)t=0Tθlogπθ(atn|stn)

Properties:

  • Unbiased: E[g^]=θJ(θ)
  • High variance: Single trajectory estimates are noisy
  • On-policy: Requires fresh samples after each update

Causality Improvement

Actions at time t cannot affect rewards at earlier times. We can use reward-to-go:

θJ(θ)=E[t=0Tθlogπθ(at|st)t=tTγttrt]

This uses Gt=t=tTγttrt instead of R(τ), reducing variance.

REINFORCE Update Animation

REINFORCE in action: the policy updates based on episode returns, gradually concentrating probability on better actions.


The Variance Problem

Why High Variance?

Policy gradient estimates suffer from high variance because:

  1. Stochastic actions: Randomness in action sampling
  2. Stochastic transitions: Environment dynamics
  3. Rare events: Important but infrequent rewards

Consequence: Gradient estimates swing wildly between updates, causing unstable learning.

Policy Gradient Variance Comparison

Baseline Subtraction

We can subtract any function b(s) that does not depend on actions:

θJ(θ)=E[t=0Tθlogπθ(at|st)(Gtb(st))]

Why this works: The subtracted term has zero expectation:

Eaπθ[θlogπθ(a|s)b(s)]=b(s)aθπθ(a|s)=b(s)θaπθ(a|s)=1=0

Common Baselines

BaselineFormulaVariance Reduction
Constantb=R¯ (average return)Moderate
State-dependentb(s)=V(s) (value function)High
Moving averageb=EMA(R)Moderate

Optimal baseline: The value function Vπ(s) is provably the variance-minimizing baseline.


The Advantage Function

Definition

The advantage function measures how much better an action is compared to the average:

Aπ(s,a)=Qπ(s,a)Vπ(s)

where:

  • Qπ(s,a) = expected return starting from (s,a) following π
  • Vπ(s) = expected return starting from s following π

Advantage Actor-Critic Gradient

Using advantage as the weighting term:

θJ(θ)=E[t=0Tθlogπθ(at|st)Aπ(st,at)]

Intuition:

  • A>0: Action better than average — increase probability
  • A<0: Action worse than average — decrease probability
  • A=0: Action is average — no change

Advantage Estimation

Since we do not know the true advantage, we estimate it:

TD(0) Advantage Estimate:

A^t=rt+γV(st+1)V(st)

Generalized Advantage Estimation (GAE):

A^tGAE(γ,λ)=l=0(γλ)lδt+l

where δt=rt+γV(st+1)V(st) is the TD error.

GAE interpolates between high-bias/low-variance (λ=0) and low-bias/high-variance (λ=1).


Policy Gradients for Continuous Actions

Gaussian Policy Implementation

For continuous control, we typically use a diagonal Gaussian:

πθ(a|s)=N(μθ(s),diag(σθ2))

The network outputs:

  • Mean: μθ(s) — deterministic component
  • Log std: logσ — learned or fixed

Score Function for Gaussian

The gradient of log probability:

θlogπθ(a|s)=θμθ(s)aμθ(s)σ2+θlogσθ(s)((aμθ(s))2σ21)

Interpretation:

  • If a>μ: Increase μ to make a more likely
  • Magnitude scales inversely with σ2 (more certain = larger gradients)

Exploration-Exploitation

ApproachMethodTrade-off
Entropy bonusAdd H[πθ(·|s)] to objectiveEncourages exploration
Fixed varianceσ is a hyperparameterSimpler but less adaptive
Learned varianceNetwork outputs logσAdapts exploration over time

Visual Summary


Interview Questions

Q1: "Why do we need the log-derivative trick in policy gradients?"

Answer:

The log-derivative trick converts a gradient of a probability distribution into an expectation we can sample from.

The problem: We want θEaπθ[R], but the expectation itself depends on θ:

θaπθ(a)R(a)

The solution: Using θπ=πθlogπ:

=aπθ(a)θlogπθ(a)R(a)=Eaπθ[R(a)θlogπθ(a)]

Now we can estimate this gradient by sampling actions from our policy. Without this trick, we would need to compute gradients through the sampling process itself, which is not differentiable.


Q2: "What is the advantage function and why does it reduce variance?"

Answer:

The advantage function Aπ(s,a)=Qπ(s,a)Vπ(s) measures how much better action a is compared to the average action under policy π in state s.

Variance reduction mechanism:

  1. Centering: By subtracting V(s), we center the reward signal around zero. Good actions get positive weights, bad actions get negative weights.

  2. Credit assignment: Instead of weighting by absolute return (which includes rewards unrelated to the current action), we weight by relative performance.

  3. Reduced scale: Returns can be very large or vary wildly across episodes. Advantage values are typically smaller and more consistent.

Example: If baseline return is 100 and we get 102, raw weighting uses 102 while advantage uses +2. The smaller magnitude means less variance in gradient estimates.


Q3: "Compare REINFORCE to Actor-Critic. When would you use each?"

Answer:

AspectREINFORCEActor-Critic
Value functionNoneLearned critic V(s)
BiasUnbiasedBiased (critic error)
VarianceHigh (Monte Carlo)Lower (TD estimates)
Sample efficiencyLowHigher
ComplexitySimpleTwo networks to train

Use REINFORCE when:

  • Episodes are short (low variance naturally)
  • Simplicity is prioritized
  • Debugging/understanding the algorithm

Use Actor-Critic when:

  • Episodes are long (need variance reduction)
  • Sample efficiency matters
  • Continuous control tasks
  • Building toward PPO/A3C

Key insight: Actor-Critic trades unbiasedness for variance reduction. The bias introduced by an imperfect critic is usually preferable to the high variance of REINFORCE in practice.


Quick Reference Card

POLICY GRADIENT CORE
─────────────────────────────────────────────────────────────
Objective:     J(θ) = E_τ[R(τ)]
Gradient:      ∇J = E[R(τ) Σ_t ∇log π_θ(aₜ|sₜ)]
Log-trick:     ∇π = π ∇log π

REINFORCE
─────────────────────────────────────────────────────────────
Update:        θ ← θ + α R(τ) ∇log π_θ(a|s)
Reward-to-go:  Use Gₜ = Σ_{t'≥t} γ^(t'-t) r_{t'}
Properties:    Unbiased, high variance, on-policy

VARIANCE REDUCTION
─────────────────────────────────────────────────────────────
Baseline:      Subtract b(s) — zero expected gradient
Best baseline: V^π(s) — value function
Advantage:     A(s,a) = Q(s,a) - V(s)

CONTINUOUS ACTIONS
─────────────────────────────────────────────────────────────
Gaussian:      π(a|s) = N(μ_θ(s), σ²)
Log-prob:      -½[(a-μ)²/σ²] - log σ - ½log(2π)
Exploration:   Entropy bonus, learned σ

ALGORITHMS HIERARCHY
─────────────────────────────────────────────────────────────
REINFORCE → Actor-Critic → A2C/A3C → PPO/TRPO
(simple)     (baseline)     (parallel)  (constrained)

Key Takeaways

  1. Policy gradients optimize policies directly by computing gradients of expected return through sampled trajectories, enabling continuous actions and stochastic policies.

  2. The policy gradient theorem provides an unbiased gradient estimate using the log-derivative trick: weight each action's score function by its return.

  3. Variance is the central challenge — REINFORCE estimates are unbiased but noisy. Baselines and advantage functions dramatically reduce variance without introducing bias.

  4. The advantage function measures relative action quality, providing both variance reduction and intuitive credit assignment.

  5. Actor-Critic methods trade a small amount of bias (from critic errors) for significant variance reduction, forming the foundation for modern algorithms like PPO and A3C.