Lesson 10 of 12 · Deep RL
Policy Gradients
Learn policy gradient methods: softmax policies, the REINFORCE algorithm, baselines that cut variance, and NumPy examples on a bandit and a corridor.
- 18 min read
- Advanced
- Reviewed
- Explain how a policy gradient method learns the policy directly, instead of deriving it from action values
- Turn learned preferences into action probabilities with a softmax policy
- Write the REINFORCE update and train it in NumPy
- Explain why a baseline makes REINFORCE less noisy without changing its average direction
- Weigh policy gradients against value-based methods such as Q-learning and DQN
The idea in plain words
Q-Learning and Deep Q-Networks learn how good every action is, and the policy comes second: take the action with the largest Q-value, plus some ε-greedy exploration. Policy gradient methods turn this around. The policy itself is a function with adjustable parameters θ that gives a probability for every action, and learning changes θ directly. After each episode, actions that were followed by high returns become more likely, and actions followed by low returns become less likely.
Think of learning to throw darts. You don't keep a table of scores for every possible throwing motion. You throw, see where the dart lands, and shift your next throw a little towards what worked. That shift is the policy gradient: "gradient" because it follows the direction in which the expected return rises fastest. It's gradient descent run uphill, called gradient ascent.
Why do this when Q-learning works? Three reasons:
- Continuous actions. A robot's joint torque or a car's steering angle can take any value in a range. Q-learning would need the largest Q-value out of infinitely many actions at every step. A policy can simply output the mean and spread of a normal distribution and draw the action from it.
- Stochastic policies. Sometimes the best policy is random, as in rock-paper-scissors from Markov Decision Processes. ε-greedy is random in one fixed, crude way; a policy gradient method learns exactly how random to be.
- Smooth learning. A small change to θ changes the probabilities a little. In Q-learning, a small change to one Q-value can flip the argmax and change what the agent does in that state completely.
A softmax policy
For a handful of discrete actions, the usual choice is a softmax policy. It keeps one preference h(s, a) for each action, a number that can be positive or negative, and turns the preferences into probabilities:
π(a | s) = e^h(s, a) ÷ Σ e^h(s, b) the sum runs over every action bIt's the formula of softmax selection in Exploration vs Exploitation, with one big difference. There, the numbers inside were value estimates divided by a temperature. Here they're preferences, learned directly, that don't estimate any return. In a small problem, θ is a table of preferences with one row per state; in deep RL, a neural network computes them from the state.
import numpy as np
def softmax(h):
e = np.exp(h - h.max()) # subtract the largest preference to avoid overflow
return e / e.sum()
def show(label, h):
print(f"{label:<29}", " ".join(f"{p:.3f}" for p in softmax(h)))
h = np.array([1.0, 2.0, 0.5]) # one learned preference per action
show("preferences 1.0, 2.0, 0.5:", h)
show("add 10 to every preference:", h + 10) # only the differences matter
show("raise action 0 by 1:", h + np.array([1.0, 0.0, 0.0]))
rng = np.random.RandomState(0)
counts = np.bincount(rng.choice(3, size=1000, p=softmax(h)), minlength=3)
print("1,000 actions drawn:", counts)preferences 1.0, 2.0, 0.5: 0.231 0.629 0.140 add 10 to every preference: 0.231 0.629 0.140 raise action 0 by 1: 0.450 0.450 0.100 1,000 actions drawn: [229 614 157]
- Larger preferences mean larger probabilities, and every action keeps some chance of being picked.
- Adding 10 to every preference changes nothing: only the differences between preferences matter.
- Raising one preference by 1 multiplies its e^h by e ≈ 2.72, so action 0 rises from 0.231 to 0.450, and the others shrink to make room.
- Drawing 1,000 actions gives counts close to the probabilities: 229, 614 and 157.
REINFORCE
The goal is to make J(θ), the expected return, as large as possible. The policy gradient theorem (Sutton and others, 2000) gives its gradient in a form that can be estimated from episodes alone, without a model of the environment:
J(θ) the expected return when actions are drawn from π_θ
G_t the return from step t onwards: r_(t+1) + γ × r_(t+2) + γ² × r_(t+3) + …
∇J(θ) = the average over episodes of Σ over the steps t of G_t × ∇ log π_θ(a_t | s_t)
REINFORCE: play an episode with π_θ, then for every step t
θ ← θ + α × G_t × ∇ log π_θ(a_t | s_t)Read the update from right to left. ∇ log π(a_t | s_t) is the direction in which to move θ to make the action that was actually taken more likely. G_t says how far to move: a large return pushes that action up a lot, and a negative return pushes it down. Why the log? Because ∇ log π = ∇π ÷ π, and dividing by π stops actions that are picked often from winning just because they collect more updates.
This is REINFORCE, published by Ronald Williams in 1992. It's a Monte Carlo method: like the simulations in Markov Decision Processes, it needs the whole episode before it can compute G_t. And it's on-policy: the episodes must come from the current policy, so each one is used for one update and then thrown away. (With γ below 1, the textbook version also multiplies step t's update by γ^t; most code leaves that factor out.)
For a softmax policy with one preference per action, the gradient is short:
∇ log π(a) = (1 for action a, 0 for the others) − π with respect to the preferences
an example: π = (0.2, 0.5, 0.3), action 0 was followed by G = 2, α = 0.1
∇ log π(0) = (1, 0, 0) − (0.2, 0.5, 0.3) = (0.8, −0.5, −0.3)
h ← h + 0.1 × 2 × (0.8, −0.5, −0.3) = h + (0.16, −0.10, −0.06)
π becomes (0.24, 0.47, 0.29): action 0 is now more likelyA baseline: same direction, less noise
The gradient that REINFORCE follows is right on average, but every single estimate of it is noisy. Here's a three-armed bandit, like those in Multi-Armed Bandits, whose arms pay 9, 10 and 11 on average, plus noise with a standard deviation of 1. Every reward is around 10, so every update pushes up whichever arm was just pulled, even the worst one. The best arm only wins because its pushes are slightly bigger, and that small difference is buried in the noise.
A baseline fixes this. Subtract a number b from the return, and only better-than-expected results push an action up:
θ ← θ + α × (G_t − b(s_t)) × ∇ log π_θ(a_t | s_t) b can depend on the state, never on the action
why the average update doesn't change: averaged over the actions the policy picks,
Σ over a of π(a) × ∇ log π(a) = Σ over a of ∇π(a) = ∇(Σ over a of π(a)) = ∇1 = 0The probabilities always add up to 1, so their gradients add up to 0, and subtracting b changes the average update by b × 0 = 0. It does change every single update, and that's the point. Here the baseline is the average of all the rewards so far, and each setting runs 50 times with different seeds:
import numpy as np
def softmax(h):
e = np.exp(h - h.max())
return e / e.sum()
means = np.array([9.0, 10.0, 11.0]) # average reward of arms 0, 1, 2: arm 2 is the best
def reinforce(use_baseline, pulls=500, alpha=0.1, seed=0):
rng = np.random.RandomState(seed)
h, baseline, best_pulls = np.zeros(3), 0.0, 0
for t in range(1, pulls + 1):
pi = softmax(h)
a = rng.choice(3, p=pi) # sample an action from the policy
r = rng.normal(means[a], 1.0) # its reward: the arm's mean plus noise
grad_log = -pi # the gradient of log pi(a): one-hot(a) - pi
grad_log[a] += 1
b = baseline if use_baseline else 0.0
h += alpha * (r - b) * grad_log # the REINFORCE update
baseline += (r - baseline) / t # the average of all rewards so far
best_pulls += a == 2
return softmax(h), best_pulls / pulls
print("50 runs, 500 pulls each favourite arm at the end average P(arm 2) pulls of arm 2")
print(" arm 0 arm 1 arm 2")
for use_baseline in [False, True]:
runs = [reinforce(use_baseline, seed=seed) for seed in range(50)]
final = np.array([pi for pi, _ in runs])
favourite = np.bincount(final.argmax(axis=1), minlength=3)
print(f"{'with a baseline' if use_baseline else 'no baseline':<26}" + "".join(f"{n:>5} " for n in favourite)
+ f"{final[:, 2].mean():>12.2f} {np.mean([share for _, share in runs]):>16.0%}")50 runs, 500 pulls each favourite arm at the end average P(arm 2) pulls of arm 2
arm 0 arm 1 arm 2
no baseline 5 19 26 0.52 45%
with a baseline 0 0 50 0.99 91%Without a baseline, only 26 of the 50 runs end up favouring arm 2, the best one; 19 settle on arm 1 and 5 on arm 0, the worst. The first few pulls decide: whichever arm gets lucky early is pushed up, gets pulled more often, gets pushed up more, and soon nothing else is tried. With the average reward as a baseline, a reward of 9 counts as bad news, and all 50 runs favour arm 2, ending with an average probability of 0.99 for it. A smaller α would also tame the noise, but it learns more slowly: try α = 0.01. A natural baseline for problems with many states is V(s), the expected return from the state, which the agent can learn as it goes. That's the idea behind Actor-Critic Methods, the next lesson.
Learning a stochastic policy: the short corridor
This classic example from Sutton and Barto's textbook shows something value-based methods can't do. A corridor has four cells. The agent starts in cell 0 and must reach cell 3, and every step costs 1. In cell 1 the controls are reversed: "right" moves left and "left" moves right. And all the cells look the same to the agent, so it has to use the same probabilities everywhere.
cell: 0 1 2 3
[ S ] [ ⇄ ] [ ] [ G ]
start reversed goalEvery fixed choice fails. Always pressing right goes from cell 0 to cell 1, where the reversed controls send the agent back to cell 0, forever; always pressing left never leaves cell 0. An ε-greedy agent built on Q-values, with ε = 0.1, picks a random action 10% of the time and its greedy action otherwise, so its P(right) is either 0.05 or 0.95. A policy gradient method can learn any probability in between. Here the policy has one parameter θ, with P(right) = 1 ÷ (1 + e^−θ), a softmax over two actions. REINFORCE starts at P(right) = 0.05, as bad as the worse ε-greedy policy, and learns for 1,000 episodes, with the average of all the returns so far as its baseline. As in the bandit, the baseline matters: every return here is negative, so without one, every update would push down whichever action was just taken. To score each policy exactly, the program solves the Bellman equations of the three cells with np.linalg.solve, as in the exercise in Value Functions:
import numpy as np
# The short corridor: cells 0 to 3, start in cell 0, goal in cell 3, and every step costs 1.
# In cell 1 the controls are reversed. All cells look the same to the agent, so its whole
# policy is one number: the probability of pressing "right".
def play(p_right, rng):
cell, actions = 0, []
while cell != 3 and len(actions) < 1000:
right = rng.rand() < p_right
move = 1 if right else -1
cell = max(cell + (-move if cell == 1 else move), 0)
actions.append(right)
return actions # the return is minus the number of steps
def reinforce(episodes=1000, alpha=0.001, seed=0):
rng, theta = np.random.RandomState(seed), np.log(1 / 19) # start at P(right) = 0.05
total, count = 0.0, 0 # for the baseline: the average of all returns so far
for _ in range(episodes):
p = 1 / (1 + np.exp(-theta)) # a softmax over two actions is the sigmoid
actions = play(p, rng)
baseline = total / count if count else 0.0
for t, right in enumerate(actions):
G = -(len(actions) - t) # the return from step t: minus the steps still to go
theta += alpha * (G - baseline) * ((1 - p) if right else -p) # × the gradient of log pi
total, count = total + G, count + 1
return 1 / (1 + np.exp(-theta))
def expected_return(p): # exact: solve the Bellman equations of cells 0-2
P = np.array([[1 - p, p, 0], # cell 0: right -> 1, left -> stays in 0
[p, 0, 1 - p], # cell 1, reversed: right -> 0, left -> 2
[0, 1 - p, 0]]) # cell 2: right -> goal, left -> 1
return np.linalg.solve(np.eye(3) - P, -np.ones(3))[0]
learned = [reinforce(seed=seed) for seed in range(5)]
print("P(right) after 1,000 episodes, 5 runs:", " ".join(f"{p:.2f}" for p in learned))
print("\nexpected return from the start:")
for name, p in [("ε-greedy, greedy = left", 0.05), ("ε-greedy, greedy = right", 0.95),
("REINFORCE, run 1", learned[0]), ("REINFORCE, run 2", learned[1]),
("the best possible", 2 - np.sqrt(2))]:
print(f" {name:<26} P(right) = {p:.2f} {expected_return(p):6.1f}")P(right) after 1,000 episodes, 5 runs: 0.66 0.59 0.58 0.61 0.58 expected return from the start: ε-greedy, greedy = left P(right) = 0.05 -82.1 ε-greedy, greedy = right P(right) = 0.95 -44.2 REINFORCE, run 1 P(right) = 0.66 -12.0 REINFORCE, run 2 P(right) = 0.59 -11.7 the best possible P(right) = 0.59 -11.7
The two ε-greedy policies expect −82.1 and −44.2, because they spend most of their time bouncing back and forth. All five REINFORCE runs climb from 0.05 to between 0.58 and 0.66, and the first two expect −12.0 and −11.7, next to the best possible −11.7 at P(right) = 2 − √2 ≈ 0.59. No ε-greedy agent can find that policy, because the best behaviour here is to be random in a particular way. The spread between the five runs is a reminder that REINFORCE's estimates are noisy: different seeds land in different places.
Policy gradients or value-based methods?
| Value-based: Q-Learning, Deep Q-Networks | Policy gradients: REINFORCE | |
|---|---|---|
| What is learned | Q-values; the policy takes the largest | The policy itself: a probability for every action |
| Continuous actions | Hard: needs the largest Q-value over infinitely many actions | Natural: output the mean and spread of a distribution |
| Stochastic policies | Only the fixed randomness of ε-greedy | Learns how random to be |
| When it learns | After every step, by bootstrapping | After every episode, from whole returns |
| Old experience | Reusable: off-policy, with a replay memory | Used once: on-policy |
| Noise and data needed | Less noise, fewer episodes | Noisy updates, often many episodes |
| Stability | Can diverge with a neural network | Changes smoothly, towards a local optimum |
Value-based methods squeeze more out of every step, which matters when experience is expensive. Policy gradients optimise the policy you actually care about, extend naturally to continuous and huge action spaces, and change behaviour gradually, at the price of noise and data. Most modern deep RL algorithms combine the two: an actor-critic method learns a policy, like REINFORCE, together with a value function, like Q-learning, to cut the noise.
Common mistakes
Practice
An agent has played one three-step episode with a softmax policy. Fill in the return from each step, working backwards from the end. Then apply the REINFORCE update with a baseline of 2.0 for every step, using pi, the probabilities that played the episode, and print the returns and the new probabilities.
import numpy as np
def softmax(h):
e = np.exp(h - h.max())
return e / e.sum()
h = np.zeros(3) # preferences for actions 0, 1 and 2
alpha, gamma, baseline = 0.1, 0.9, 2.0
actions = [0, 2, 2] # one episode: the action taken at each step
rewards = [0.0, 0.0, 4.0] # and the reward that followed it
pi = softmax(h) # the policy that played the episode
returns = np.zeros(3)
# 1. Fill in returns[t], the return from step t onwards. Work backwards: G = reward + gamma * G
# 2. Then, for every step t: h += alpha * (returns[t] - baseline) * (one-hot of the action - pi)
print("returns: ", " ".join(f"{g:.2f}" for g in returns))
print("probabilities:", " ".join(f"{p:.3f}" for p in softmax(h)))
Why does REINFORCE often subtract a baseline from the return?
Summary
- A policy gradient method learns the policy itself, by gradient ascent on the expected return. A softmax policy turns learned preferences into action probabilities.
- REINFORCE plays an episode, then updates θ ← θ + α × G_t × ∇ log π(a_t | s_t) for every step, so actions followed by high returns become more likely.
- Subtracting a baseline leaves the average gradient unchanged but cuts its noise: on a bandit with rewards near 10, the best arm won 50 runs out of 50 instead of 26.
- Policy gradients handle continuous actions and learn stochastic policies, such as P(right) ≈ 0.59 in the short corridor. But they're noisy and on-policy, so they need more episodes than Q-Learning and Deep Q-Networks.
Next: Actor-Critic Methods.
Finished reading? Tick it off to track your progress.