Why learn the policy directly
A parameterized policy has several advantages over a policy derived from action values (Sutton & Barto, 2018):- It can become deterministic, or stay stochastic, as the task requires. An -greedy policy always takes random actions with probability . A softmax policy can move its probabilities as close to 0 or 1 as the return rewards. When the best policy is stochastic, for example when two states look the same to the agent but need different actions, a policy-gradient method can learn it, and an action-value method that acts greedily cannot.
- The policy can be simpler than the value function. In some tasks it is easier to describe what to do than how much each action is worth.
- The policy changes smoothly. A small change of changes the action probabilities a little. With action values, a small change of can switch the greedy action and change the behavior abruptly. This smoothness is behind the convergence guarantees of policy-gradient methods.
- Continuous actions are natural. The policy can output the parameters of a distribution over actions, such as the mean of a Gaussian, instead of maximizing over infinitely many actions.
The three components
The hard part is the gradient. The policy gradient theorem (Sutton & Barto, 2018) states that
where is the fraction of time the policy spends in state . The gradient needs no derivative of the state distribution , which depends on the unknown dynamics. The rest of this section derives the same result for whole trajectories, step by step.
Deriving the policy gradient
The log-derivative trick
Take a function and a parameterized distribution . The goal is the gradient of the expectation , in a form that can be estimated from samples.Step 1: Definition of expectation
Step 1: Definition of expectation
Explanation:
This uses the definition of an expectation under a density:
Step 2: Leibniz rule
Step 2: Leibniz rule
Explanation:
Under mild regularity conditions, differentiation and integration commute (Leibniz rule), allowing us to move inside the integral.
Step 3: Product rule
Step 3: Product rule
Explanation:
This applies the product rule to .
Step 4: Simplification
Step 4: Simplification
Explanation:
We assume does not depend on , so and the second term vanishes. This is the standard situation in policy-gradient and score-function estimators: in our setting, is the return of the whole trajectory , which depends on the sampled trajectory but not directly on the policy parameters . The -dependence is captured by the distribution itself.
Step 5: Multiply and divide
Step 5: Multiply and divide
Explanation:
Multiply and divide by ; this is valid whenever on the support of interest.
Step 6: Log-derivative identity
Step 6: Log-derivative identity
Explanation:
We use the log-derivative identity:
Step 7: Back to expectation form
Step 7: Back to expectation form
Explanation:
We rewrite the integral back into expectation form.
From trajectories to actions
In RL the random variable is a trajectory , and is its return , so that . The probability of a trajectory factorizes into the start distribution, the policy and the dynamics: Its logarithm is a sum, and only the policy terms depend on : The dynamics drop out. The gradient needs the log-probabilities of the actions that were taken, which the agent computes itself, and never the transition probabilities of the environment. That is why REINFORCE is model-free. With the log-derivative trick,Reward-to-go
This estimator weights every action by the return of the whole episode, including rewards that arrived before the action was taken. Those rewards cannot depend on the action, and their contribution is zero in expectation. For a reward with , condition on everything up to : is then fixed, and the expected score of is zero, because Dropping the earlier rewards leaves each action weighted by the rewards that follow it, : The expectation is unchanged. The variance is usually lower, because the dropped rewards add noise that the action did not cause, but this is not guaranteed: if an earlier reward happens to cancel part of the later return, dropping it can raise the variance. Because , this is the policy gradient theorem written for sampled trajectories. The Policy Gradient Minimal Examples measure both effects on a two-step task. The factor . The exact gradient of the discounted objective weights the update at time by , as Sutton and Barto’s REINFORCE does. Most implementations drop the factor and weight each action by alone, which gives every time step equal weight. This page and the algorithm below follow that common simplification. It is exact for , and for close to 1, such as 0.99, the two differ little over short episodes.The softmax policy
For discrete actions the policy network outputs one preference, or logit, per action, and the policy is their softmax: The score with respect to the preferences has a simple form: The update raises the preference of the action taken, in proportion to , and lowers the others in proportion to their probabilities. Backpropagation carries this through the network to . The scores are bounded, and an action that is already almost certain gets almost no further push. The Policy Gradient Minimal Examples work through the two-action case.The algorithm
The expectation over trajectories is estimated with sampled episodes, a Monte Carlo estimate. Each update samples a trajectory with the current policy, computes the return from every time step, and moves along the sum of the weighted scores, without any knowledge of the transition or reward functions.Algorithm: Monte Carlo Policy Gradient (REINFORCE)
images/reinforce-loop.mermaid.md
A trajectory is discarded after the update that uses it and is never reused. REINFORCE is an on-policy method, like Monte Carlo control. The update in line 10 uses the score of the current policy in line 8, and the returns in line 7 must come from trajectories generated by that same policy. Returns generated by another policy would adjust the action probabilities with outcomes that would not have produced.
Policy network
The policy network maps a state to one logit per action. Sampling an action and computing its log-probability takes four steps:Applying the REINFORCE algorithm
A runnable end-to-end implementation on theCartPole-v1 environment lives in its own section so you can train, inspect episode returns, and experiment with hyperparameters directly. It uses the same policy architecture described above and plots a learning curve.

REINFORCE on CartPole-v1
Runnable policy-gradient agent with a learning-curve plot, modernized for the current Gymnasium API.
Why the learning curve is not monotonic
Train the model above and the episode returns rise on average but oscillate sharply; bursts to the 500 ceiling are routinely followed by drops to 50 to 150. Monotonic improvement is not expected for vanilla REINFORCE. The reasons are structural:- Gradient variance: a single trajectory is used per update. One lucky or unlucky episode dominates the gradient at that step.
- Uncentered returns: without a baseline, every action inside a good episode gets reinforced, including suboptimal ones. The gradient carries “absolute goodness,” not “advantage.”
- Unbounded step size: the per-step loss scales with the return . A lucky 500-return episode produces a gradient step many times larger than a typical one, and a single oversized update can overshoot the current good region of parameter space; the very next episode’s policy is then markedly worse. Later methods (e.g. PPO) explicitly cap how much the policy is allowed to change per update.
- On-policy non-stationarity: the trajectory distribution itself changes with , so yesterday’s gradient is stale today.
- Stochastic policy at eval time: even a well-trained policy samples from , so episode returns inherently fluctuate.
Reducing variance with a baseline
The first and simplest fix targets reasons 1 and 2 above: subtract a state-dependent baseline from the return: A baseline that does not depend on the action leaves the gradient unbiased. The proof is the same zero-mean property of the score used for reward-to-go: It can, however, reduce the variance a lot. The most common choice is , an estimate of the state value learned by a separate network. This is REINFORCE with baseline. The difference estimates the advantage of the action taken. The method is still not actor-critic: the learned value is used only as a baseline and never to bootstrap the target (Sutton & Barto, 2018). Actor-Critic Methods replace with a bootstrapped target such as , and they lead to PPO and GRPO, which also limit the size of each policy update to address reason 3. The DDPG navigation section uses a deterministic actor with a learned critic on a TurtleBot3, and compares its gradient with the one above. Key references: (Sutton & Barto, 2018); Williams (1992), Simple statistical gradient-following algorithms for connectionist reinforcement learning.References
- Sutton, R., Barto, A. (2018). Reinforcement Learning: An Introduction. Link
Found an error on this page? Report an issue.
Footnotes
- We write the objective as , as Sutton and Barto do (Sutton & Barto, 2018). It depends on the policy only through its parameters . ↩

