Part 4: Deep learning Lesson 14 of 15 in this part
Reinforcement learning: policy methods
What you will learn. Explain how a policy gradient nudges action probabilities towards rewarding actions, why subtracting a baseline gives a clearer signal, and how PPO's clipping keeps each update small.
Before this lesson: Reinforcement learning: value methods. Already know these? Carry on.
In plain words
Value methods learn how good things are and then pick the best action. Policy methods skip that step: they learn the policy itself, the rule that gives the probability of each action in each state, and improve it directly. The basic method is the policy gradient (REINFORCE): after trying actions, make the actions that led to high rewards more probable, and the others less probable. The raw reward signal is noisy, so we subtract a baseline, usually the average reward. What remains is the advantage: how much better than usual this action turned out. Actor-critic methods learn two things at once: the policy (the actor) and a value estimate (the critic) that supplies the baseline. PPO (proximal policy optimisation) keeps training stable by limiting how far the policy may change in one update. Policy methods suit continuous actions, such as how hard to push a pedal.
Value-based
- Learn how good each action is
- Pick the best, so actions are discrete
Policy-based
- Learn the action probabilities directly
- Works for continuous actions too
Many modern systems use both together in an actor-critic design.
- InputRun the policy and collect an episodeActions taken and rewards received
- ProcessCompute each step's advantageReturn minus a baseline
- ModelRaise the probability of high-advantage actionsA small step along the gradient
Repeat with the improved policy
Actions that did better than usual become more likely.
- RiskRaw returns are all positiveEvery action looks good
- ProcessSubtract the average returnNow good actions are positive and poor ones negative
- OutputThe signal is clearerLess noise, faster learning
A baseline does not change the direction of learning, only how noisy it is.
Inside the allowed range
- Ratio near one, normal update
Outside the allowed range
- The gain from moving further is cut off
- The policy stays close to the old one
The clip stops one lucky batch from pushing the policy far in a single step.
Real-world example
A team trains a simulated robot arm to reach a target. The arm's actions are continuous torques, so a table of action values is impossible. They use an actor-critic method with PPO. The actor outputs the average torque and its spread. The critic predicts the expected reward, which gives the baseline. In early runs the arm sometimes collapsed because one update changed the policy too much. Switching on PPO's clipping fixed it. A designer also checked the reward by watching videos of the arm, because the agent had found a way to score by touching the target with a flailing motion.
How it works
- Policy. A function from a state to action probabilities. For two actions, a softmax over two preference numbers.
- Gradient. Raise the preference of an action in proportion to its probability times how much better its reward was than average.
- Baseline and advantage. Replace the raw return by return minus a baseline. The value estimate from a critic is the usual baseline. Generalised advantage estimation blends several steps for a good trade between noise and bias.
- Trust. PPO multiplies the advantage by the ratio of the new to the old probability of the action, and clips that ratio to a narrow band, such as 0.8 to 1.2.
- Other families. TRPO limits the change by a distance constraint. DDPG, TD3 and SAC learn continuous control with an off-policy critic. AlphaZero combines a policy, a value and tree search. Offline RL learns from a fixed log without trying anything new, which is safer but harder. Reward shaping adds hints to the reward to speed up learning, and must be designed carefully so that it does not change what the best behaviour is.
Python example
Python: example run The example programme behind this lesson's quoted output ran on 2026-11-19 (Python 3.12.10). 1 code block in the lesson passed a syntax check, 1 also ran on their own.
Three small calculations with the standard library: exact policy-gradient steps on a two-action choice, the returns and advantages of a five-step episode, and the PPO objective for four ratios.
"""Policy methods in three small calculations: the policy gradient on a two-action choice, advantages with a baseline,
and the PPO clipped objective.
Run: python rl_policy.py
"""
import math
# 1. Policy gradient (REINFORCE) on a two-action choice with exact expected gradients
# Action 1 pays 1, action 0 pays 0. The policy is a softmax over two preferences.
theta = [0.0, 0.0]
def probs(th):
e = [math.exp(v) for v in th]; s = sum(e)
return [v / s for v in e]
print("step probability of the better action")
for step in range(0, 31):
p = probs(theta)
if step in (0, 5, 10, 20, 30):
print("%4d %.3f" % (step, p[1]))
# expected gradient of E[reward] with respect to preference i: p_i * (reward_i - expected reward)
expected = p[1] * 1.0
for i, rew in ((0, 0.0), (1, 1.0)):
theta[i] += 0.5 * p[i] * (rew - expected)
# 2. Advantage: how much better than usual was this step? Discounted returns minus a baseline.
rewards = [0.0, 0.0, 1.0, 0.0, 2.0]
gamma = 0.9
returns, g = [], 0.0
for r in reversed(rewards):
g = r + gamma * g
returns.append(g)
returns.reverse()
baseline = sum(returns) / len(returns)
print("returns: ", " ".join("%.3f" % v for v in returns))
print("advantages:", " ".join("%.3f" % (v - baseline) for v in returns), " (baseline %.3f)" % baseline)
# 3. PPO clipped objective for one step: ratio = new probability / old probability
def ppo(ratio, advantage, eps=0.2):
return min(ratio * advantage, max(min(ratio, 1 + eps), 1 - eps) * advantage)
for ratio, adv in ((1.1, 2.0), (1.5, 2.0), (0.7, -2.0), (1.1, -2.0)):
print("ratio %.1f advantage %+.1f objective %+.2f" % (ratio, adv, ppo(ratio, adv)))step probability of the better action
0 0.500
5 0.760
10 0.871
20 0.939
30 0.961
returns: 2.122 2.358 2.620 1.800 2.000
advantages: -0.058 0.178 0.440 -0.380 -0.180 (baseline 2.180)
ratio 1.1 advantage +2.0 objective +2.20
ratio 1.5 advantage +2.0 objective +2.40
ratio 0.7 advantage -2.0 objective -1.60
ratio 1.1 advantage -2.0 objective -2.20The probability of the better action climbs from 0.500 to 0.961 in 30 steps, quickly at first and then more slowly as the policy becomes confident. The returns are 2.122, 2.358, 2.620, 1.800 and 2.000, with a baseline of 2.180, giving advantages from -0.380 to +0.440. The PPO objective equals the plain product when the ratio is inside the band (2.20 and -2.20) and is cut when it is outside (2.40 instead of 3, and -1.60 instead of -1.40).
.NET (C#) example
C#: compiled and run The C# sample compiled on 2026-11-19 with .NET SDK 10.0.400 (no extra packages). It also ran to the end without error.
The same three calculations from scratch in C#, with no packages, printing the same output. Training a neural policy is done in Python; a trained policy is run from .NET through ONNX Runtime. The Unity ML-Agents toolkit also lets a C# game environment train with Python algorithms.
// Policy gradient, advantages and the PPO clipped objective, from scratch. Same output as rl_policy.py. No packages.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
// 1. Policy gradient (REINFORCE) on a two-action choice with exact expected gradients
double[] theta = { 0.0, 0.0 };
double[] Probs(double[] th) { var e = th.Select(Math.Exp).ToArray(); double s = e.Sum(); return e.Select(v => v / s).ToArray(); }
Console.WriteLine("step probability of the better action");
for (int step = 0; step <= 30; step++)
{
var p = Probs(theta);
if (step is 0 or 5 or 10 or 20 or 30) Console.WriteLine($"{step,4} {p[1]:F3}");
double expected = p[1] * 1.0;
// expected gradient of E[reward] with respect to preference i: p_i * (reward_i - expected reward)
theta[0] += 0.5 * p[0] * (0.0 - expected);
theta[1] += 0.5 * p[1] * (1.0 - expected);
}
// 2. Advantage: how much better than usual was this step? Discounted returns minus a baseline.
double[] rewards = { 0.0, 0.0, 1.0, 0.0, 2.0 };
double gamma = 0.9, g = 0.0;
var rets = new double[rewards.Length];
for (int i = rewards.Length - 1; i >= 0; i--) { g = rewards[i] + gamma * g; rets[i] = g; }
double baseline = rets.Average();
Console.WriteLine("returns: " + string.Join(" ", rets.Select(v => v.ToString("F3"))));
Console.WriteLine("advantages: " + string.Join(" ", rets.Select(v => (v - baseline).ToString("F3"))) + $" (baseline {baseline:F3})");
// 3. PPO clipped objective for one step: ratio = new probability / old probability
double Ppo(double ratio, double adv, double eps = 0.2) => Math.Min(ratio * adv, Math.Max(Math.Min(ratio, 1 + eps), 1 - eps) * adv);
foreach (var (ratio, adv) in new[] { (1.1, 2.0), (1.5, 2.0), (0.7, -2.0), (1.1, -2.0) })
Console.WriteLine($"ratio {ratio:F1} advantage {adv:+0.0;-0.0} objective {Ppo(ratio, adv):+0.00;-0.00}");Maths behind it
- Probabilities from a softmax over preferences (probability)
- Discounted returns and averages (arithmetic)
- Ratio of new to old probability (algebra)
- Taking the smaller of two values to limit a change (arithmetic)
Common mistakes
- Using raw returns without a baseline and getting very noisy learning.
- A learning rate or a PPO band so wide that the policy collapses after one lucky batch.
- Judging an agent from one episode. Average over many.
- A reward that can be gamed, so the agent scores without doing the task.
- Training only in simulation and trusting the result on a real machine without tests.
Quick check
What does a policy-gradient method learn directly?
Show answer
The policy: the probability of each action in each state, improved by making rewarding actions more likely.
Why subtract a baseline?
Show answer
Raw returns can all be positive, so every action would be pushed up. The baseline leaves only the above-average actions pushed up and the others pushed down, which gives a cleaner, less noisy signal.
What is an advantage?
Show answer
How much better an action turned out than was usual from that state, often the return minus a value estimate.
What does PPO's clip prevent?
Show answer
A single update pushing the new policy far from the old one. It cuts off the extra reward for moving the probability ratio outside a narrow band.
Completion
Evidence of completion. One policy-gradient step worked by hand with the new probability, a table of advantages for a short trajectory, and a PPO objective for one ratio with and without clipping.
Saved in this browser only. Reading and exercise are ticked separately because they are different achievements. A tick records your own work; it is not a test result. See all progress.