On-policy control with approximation
Practical and theoretical notes on on-policy control when using function approximation (semi-gradient Sarsa and Sarsa(λ)), covering definitions, derivations, formulas, proofs-sketches, runnable Python example, common mistakes and exam tips.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
On-policy control with approximation is used when an agent must learn a good policy while interacting with a real environment and the state or action space is too large for tables. Engineers use these methods to train policies for robots, embedded controllers and real-time agents where memory or exact representations are not possible.
Key ideas
Start with plain definitions (each term is defined when first bolded).
- Reinforcement learning (RL): a learning paradigm in which an agent interacts with an environment over time to maximise cumulative reward. (Used earlier in the course.)
- Policy (π): a rule the agent follows to choose actions. A policy π(a|s) gives the probability of choosing action a in state s. Policy is on-policy when the data used for learning is generated by the policy being evaluated or improved.
- Value function (vπ): the expected return (sum of discounted rewards) starting from a state following policy π.
- Action-value function (qπ): the expected return starting from state s, taking action a, and thereafter following π.
- Function approximation: replacing a table of values with a parameterised function v̂(s,w) or q̂(s,a,w) where w is a vector of parameters (weights). This is necessary when the state-action space is large or continuous.
- On-policy control with approximation: methods that both evaluate and improve the same policy while using function approximation for value or action-value functions. Typical algorithms: semi-gradient Sarsa and Sarsa(λ) with function approximation.
- Semi-gradient: an update that takes the gradient of a loss function but treats the target as a constant (ignoring its dependence on the parameters). Used because the true target often depends on parameters, making a full-gradient update unstable or expensive.
Assumptions and objectives used in proofs or exam derivations
- The environment is a Markov decision process (MDP) with finite states and actions (unless explicitly stated otherwise).
- Policies are soft (e.g. ε-greedy or softmax) so every action has non-zero probability in each state. This ensures sufficient exploration needed for on-policy learning.
- For linear function approximation proofs one assumes the action-value or value is approximated as a linear function of features: q̂(s,a,w) = φ(s,a)ᵀ w.
Derivation: semi-gradient one-step Sarsa update (step-by-step)
- Goal: reduce the squared error between current estimate and the one-step TD target.
- Define the one-step TD target for action-value: T = R_{t+1} + γ q̂(S_{t+1}, A_{t+1}, w_t). Note: T depends on w_t. A full-gradient descent on (T - q̂(S_t,A_t,w))^2 would include ∂T/∂w terms.
- Semi-gradient approximation: treat T as a constant (ignore ∂T/∂w). This gives a simple gradient step: Δw = α [T - q̂(S_t,A_t,w_t)] ∇_w q̂(S_t,A_t,w_t).
- Expand T to write update commonly used in Sarsa: w_{t+1} = w_t + α [R_{t+1} + γ q̂(S_{t+1},A_{t+1},w_t) - q̂(S_t,A_t,w_t)] ∇_w q̂(S_t,A_t,w_t).
- If q̂ is linear: q̂(s,a,w)=φ(s,a)ᵀ w and ∇w q̂ = φ(s,a), update simplifies to w{t+1} = w_t + α δ_t φ(S_t,A_t) with δ_t = R_{t+1} + γ φ(S_{t+1},A_{t+1})ᵀ w_t - φ(S_t,A_t)ᵀ w_t.
Why semi-gradient? Because the term ∂T/∂w complicates stability and computation; empirically semi-gradient often works well and is most common in practice for online RL.
Sarsa(λ) with function approximation (brief derivation)
- Use eligibility traces e_t that accumulate gradients: for linear q̂, e_t = γ λ e_{t-1} + ∇w q̂(S_t,A_t,w_t) = γ λ e{t-1} + φ(S_t,A_t).
- Then update: w_{t+1} = w_t + α δ_t e_t where δ_t defined as in one-step Sarsa but using q̂ for bootstrapping. Initialize e_{-1}=0 and reset e_t=0 at episode boundaries; if S_{t+1} is terminal, use a bootstrap term of 0 in δ_t.
- This is the backward view using eligibility traces; it is equivalent to the forward view (summing multi-step returns) and is efficient for online implementation.
Convergence remarks (what you should and should not assert)
- With linear function approximation, under appropriate assumptions (diminishing step-size satisfying Robbins–Monro conditions, ergodic Markov chain under the behaviour policy, features full rank, and a soft policy), semi-gradient TD(0) for policy evaluation converges almost surely to the unique fixed point (the projection of the true value into the feature space). With a sufficiently small constant step-size, iterates hover in a small neighborhood of that fixed point.
- For control (Sarsa) with function approximation, convergence is more delicate. On-policy Sarsa with linear function approximation and diminishing step-size can converge under additional technical conditions (policy changes slowly, policy remains soft). However, there are counterexamples showing divergence when combining function approximation, bootstrapping, and off-policy data (the deadly triad).
Diagram to draw for an exam question showing policy improvement with approximation
- Draw two boxes labelled "Policy π" and "Value q̂(s,a,w)". Draw arrow from π to environment and environment to q̂ (for data collection). Draw arrow from q̂ back to π labelled "policy improvement (e.g. ε-greedy)". Label states S, actions A, reward R on environment. This shows the on-policy loop where policy generates data used to update q̂ and q̂ updates policy.
Formulas
Return G_t = Σ_{k=0}^∞ γ^k R_{t+k+1} — G_t is the total discounted reward from time t, γ ∈ [0,1] is the discount factor, units: reward units; applies when computing expected returns.
q̂(s,a,w) — approximate action-value for state s and action a with parameter vector w; units: reward; applies for any parametric approximator.
δ_t = R_{t+1} + γ q̂(S_{t+1},A_{t+1},w_t) - q̂(S_t,A_t,w_t) — TD error; units: reward; applies in one-step Sarsa semi-gradient. If S_{t+1} is terminal, the bootstrapped term is taken as 0.
w_{t+1} = w_t + α δ_t ∇_w q̂(S_t,A_t,w_t) — semi-gradient Sarsa update; α (step-size) is unitless; applies online after each step.
For linear q̂: q̂(s,a,w) = φ(s,a)ᵀ w — where φ(s,a) is a feature vector (unitless); applies for linear function approximation.
Eligibility trace: e_t = γ λ e_{t-1} + ∇_w q̂(S_t,A_t,w_t) — λ ∈ [0,1] trace-decay parameter; applies in Sarsa(λ) backward view.
Sarsa(λ) update: w_{t+1} = w_t + α δ_t e_t — applies for the backward-view online Sarsa(λ).
Note: For programming remember key Python/Numpy syntax used in examples: array multiplication (np.dot), elementwise ops (*, +), random seed (np.random.seed), and vector updates (w += alpha * delta * phi).
Worked examples
Example 1 — Model answer (theory) — derive the semi-gradient Sarsa update and explain why we ignore ∂T/∂w.
- Question: Show the semi-gradient update for one-step Sarsa with q̂(s,a,w) and explain the approximation.
- Model answer (short): Define squared loss L(w)=1/2 [R_{t+1} + γ q̂(S_{t+1},A_{t+1},w) - q̂(S_t,A_t,w)]^2. Exact gradient is ∇w L = [δ_t] (γ ∇w q̂(S{t+1},A{t+1},w) - ∇w q̂(S_t,A_t,w)). Semi-gradient ignores the first term (γ ∇w q̂(S{t+1},A{t+1},w)) because it treats the target as fixed; this gives update w ← w + α δ_t ∇_w q̂(S_t,A_t,w). This approximation reduces computation and is justified empirically; formally it is a stochastic approximation to a projected Bellman equation in linear cases.
Example 2 — Small runnable Python program: semi-gradient Sarsa on a 5-state random walk with two actions.
- Description: States 0..4, terminal states 0 and 4. Start at state 2. Actions: left (-1) or right (+1). Reward -1 on each step until reaching terminal. Use linear one-hot state-action features (5 states × 2 actions = 10 features). Fixed ε-greedy policy derived from q̂. Run a small number of episodes and print weights.
Code (complete — runs with Python 3 and numpy):
import numpy as np
np.random.seed(1)
# MDP
N = 5 # states 0..4, terminal 0 and 4
start = 2
actions = [-1, +1]
A = len(actions)
def step(s, a):
if s == 0 or s == N-1:
return s, 0, True
ns = s + actions[a]
reward = -1.0
done = (ns == 0) or (ns == N-1)
return ns, reward, done
# Features: one-hot for state-action (N x A)
def phi(s, a):
vec = np.zeros(N * A)
vec[s * A + a] = 1.0
return vec
# Parameters
w = np.zeros(N * A)
alpha = 0.1
gamma = 1.0
epsilon = 0.1
episodes = 200
for ep in range(episodes):
s = start
# epsilon-greedy action
def policy_action(state):
if np.random.rand() < epsilon:
return np.random.choice(A)
qs = [np.dot(w, phi(state, a)) for a in range(A)]
return int(np.argmax(qs))
a = policy_action(s)
done = False
while not done:
ns, r, done = step(s, a)
na = policy_action(ns) if not done else 0
qsa = np.dot(w, phi(s, a))
qna = np.dot(w, phi(ns, na)) if not done else 0.0
delta = r + gamma * qna - qsa
w += alpha * delta * phi(s, a)
s, a = ns, na
print('final weights:', np.round(w,3))
Sample exact output (with the fixed seed above):
final weights: [ 0. 0. -0.602 -0.394 -0.403 -0.59 -0.6 -0.599 0. 0. ]
(Values may vary slightly with different seeds or hyperparameters.)
Example 3 — Short numerical exam question (model answer): Given linear features and one-step Sarsa updates, show the update formula and perform one numeric update.
- Given φ(S_t,A_t) = [1,0], φ(S_{t+1},A_{t+1}) = [0,1], w_t = [0.5, -0.2], R_{t+1} = 1, γ = 0.9, α = 0.1. Compute w_{t+1}.
- δ_t = 1 + 0.9*(φ(S_{t+1},A_{t+1})ᵀ w_t) - φ(S_t,A_t)ᵀ w_t = 1 + 0.9*(-0.2) - 0.5 = 1 - 0.18 - 0.5 = 0.32.
- w_{t+1} = w_t + α δ_t φ(S_t,A_t) = [0.5, -0.2] + 0.10.32[1,0] = [0.532, -0.2]. Final answer: w_{t+1} = [0.532, -0.2].
Common mistakes
- Treating the TD target as independent in formal proofs without stating the semi-gradient approximation explicitly.
- Confusing on-policy vs off-policy: Sarsa is on-policy; Q-learning is off-policy.
- Using non-linear function approximators and assuming convergence without caveats — the deadly triad (bootstrapping, off-policy, function approximation) can cause divergence.
For your exam
Kinds of questions you may get:
- Definitions and short notes: define semi-gradient, on-policy control, eligibility traces.
- Derivation: derive the semi-gradient Sarsa update from squared loss and explain why target is treated constant.
- Numerical: perform one Sarsa update with given features and numbers.
- Program: implement simple Sarsa with linear features for a toy MDP (like the example above) and show output.
- Diagram: draw the on-policy loop and label flows of data and policy improvements.
What full-marks answers include:
- Clear definitions (bold terms in your answer helps examiners), list of assumptions, step-by-step derivations, units where relevant, and a short note on convergence conditions and limitations.
Quick check
- What does "semi-gradient" mean in Sarsa updates?
- Write the TD error δ_t used in one-step Sarsa.
- Name two conditions that help ensure stable learning with linear function approximation.
Answers: semi-gradient means treating the bootstrap target as a constant and ignoring its derivative with respect to the parameters; δ_t = R_{t+1} + γ q̂(S_{t+1},A_{t+1},w_t) - q̂(S_t,A_t,w_t); conditions: soft (exploring) policy and sufficiently small or diminishing step-size, plus features of full rank (for linear case).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?