In the previous lesson we set the goal: find a policy that maximizes expected discounted return. This lesson introduces the machinery for reaching that goal without ever writing the policy down directly. Instead we learn to answer the question "how good is it to be here?" and "how good is it to do this?", the state-value and action-value functions. From those answers, a good policy falls out almost for free, and one algorithm in particular, tabular Q-learning, lets an agent learn optimal action values from raw experience.
How good is a state? Value functions
A value function measures expected return, not immediate reward. Under a fixed policy π, the state-value function is the return you expect to collect if you start in state s and follow π forever after:
Ask the tutor
Ask about this lesson, or about anything in AI. Answers cite the lessons they draw on.
Finished this lesson?
Mark it complete to earn XP, keep your streak, and schedule a review.
Vπ(s)=Eπ[Gt∣st=s]=Eπ[∑k=0∞γkrt+k+1
The action-value function (the "Q function") is similar, but it commits to a specific first action a before letting π take over:
Qπ(s,a)=Eπ[Gt∣st=s,at=a].
Why prefer Q? Because it tells you directly what to do. If you know Qπ, you can improve the policy simply by picking the highest-valued action in each state, no model of the environment required. This is the whole reason action values dominate practical value-based RL.
V versus Q in one sentence
V(s) scores a situation; Q(s,a) scores a situation paired with a move. Their relationship is Vπ(s)=∑aπ(a∣s)Qπ(s,a), the state value is the policy-weighted average of the action values available there.
The Bellman equation: value is recursive
The key structural fact of RL is that value functions obey a self-consistency condition. The value of a state equals the immediate reward plus the discounted value of wherever you land next. Writing this out for action values under a policy gives the Bellman expectation equation:
Qπ(s,a)=E[rt+1+γQπ(st+1,at+1)∣st=s,at=a].
We do not usually want the value of some policy, though, we want the value of the best policy. That gives the Bellman optimality equation, where instead of averaging over the policy's next action we take the best one:
Q⋆(s,a)=E[rt+1+γmaxa′Q⋆(st+1,a′)∣st=s,at=a].
That max is the heart of the matter. It says: the best value of doing a now is the reward you get, plus the discounted value of acting optimally from the next state onward. Once you have Q⋆, the optimal policy is greedy with respect to it:
π⋆(s)=argmaxaQ⋆(s,a).
Intuition
For a curious beginner
Imagine planning a road trip where each city has a "goodness" score. A city's real goodness is not just the fun you have there, but that fun plus the goodness of the best city you can drive to next (slightly discounted because it is further off). Value flows backward from good destinations to the roads that reach them.
Engineering
How it is actually used
The Bellman equation turns a hard, infinite-horizon expectation into a one-step recursion you can bootstrap from. You estimate a value using your current estimate of the next value, then nudge the old estimate toward that target. This "learn a guess from a guess" trick is called temporal-difference (TD) learning and it is what makes learning from single transitions possible.
Mathematical
The underlying mechanism
Q⋆ is the unique fixed point of the Bellman optimality operator T, where (TQ)(s,a)=E[r+γmaxa′Q(s′,a. Because T is a γ-contraction in the sup norm, repeatedly applying it converges to Q⋆ from any starting point, this underwrites both value iteration and, stochastically, Q-learning.
For a curious beginner
Imagine planning a road trip where each city has a "goodness" score. A city's real goodness is not just the fun you have there, but that fun plus the goodness of the best city you can drive to next (slightly discounted because it is further off). Value flows backward from good destinations to the roads that reach them.
How it is actually used
The Bellman equation turns a hard, infinite-horizon expectation into a one-step recursion you can bootstrap from. You estimate a value using your current estimate of the next value, then nudge the old estimate toward that target. This "learn a guess from a guess" trick is called temporal-difference (TD) learning and it is what makes learning from single transitions possible.
The underlying mechanism
Q⋆ is the unique fixed point of the Bellman optimality operator T, where (TQ)(s,a)=E[r+γmaxa′Q(s′,a. Because T is a γ-contraction in the sup norm, repeatedly applying it converges to Q⋆ from any starting point, this underwrites both value iteration and, stochastically, Q-learning.
Q-learning: bootstrapping toward Q⋆
Q-learning learns Q⋆ from experience without knowing the environment's transition probabilities. It keeps a table of estimates Q(s,a) and, after each transition (s,a,r,s′), nudges the relevant entry toward the Bellman target:
The bracketed quantity is the TD error: how surprised we were, compared to what we predicted. The learning rate α∈(0,1] controls how much of that surprise we absorb into the estimate. The pieces:
r+γmaxa′Q(s′,a′) is the target, a better estimate that uses one step of real reward plus the discounted best future value.
Q(s,a) is our current estimate.
α scales the correction. Small α learns slowly but stably; large α learns fast but jitters.
# Tabular Q-learning, one episode
def q_learning_episode(env, Q, alpha=0.1, gamma=0.99, epsilon=0.1):
s = env.reset()
done = False
while not done:
# epsilon-greedy action selection (exploration covered next lesson)
if random.random() < epsilon:
a = env.sample_action()
else:
a = argmax(Q[s])
s_next, r, done = env.step(a)
best_next = 0.0 if done else max(Q[s_next]) # no bootstrap past terminal
td_target = r + gamma * best_next
Q[s][a] += alpha * (td_target - Q[s][a]) # the update rule
s = s_next
return Q
Note the detail that trips up beginners: at a terminal state there is no future, so the target is just r (bootstrap value zero). Getting this wrong quietly corrupts every value estimate that leads to the terminal state.
A worked Q-update with numbers
Let us do one update by hand. Suppose:
Current estimate Q(s,a)=2.0.
We take action a, receive reward r=1, and land in s′.
In s′ the best action value is maxa′Q(s′,a′)=5.0.
Learning rate α=0.1, discount γ=0.9.
First the TD target:
r+γmaxa′Q(s′,a′)=1+0.9×5.0=5.5.
Then the TD error: 5.5−2.0=3.5. Finally the update:
Q(s,a)←2.0+0.1×3.5=2.35.
The estimate moved 10% of the way from 2.0 toward the target 5.5. Repeat this across many transitions and, under mild conditions, the table converges to Q⋆.
On-policy vs off-policy
Q-learning has a subtle and powerful property: it learns about the greedy policy (via the max) while behaving according to a different, more exploratory policy. That makes it off-policy. Its close cousin SARSA uses the action actually taken next instead of the max, which makes it on-policy.
Off-policy (e.g. Q-learning)
Learns the value of the optimal/target policy while following a different behavior policy.
Target uses max over next actions, independent of what was actually done.
Can reuse old experience (replay buffers), data-efficient.
Behavior can be freely exploratory without biasing the learned target.
On-policy (e.g. SARSA)
Learns the value of the policy it is actually following, exploration and all.
Target uses the next action the policy actually takes.
Tends to be safer during learning (accounts for exploratory mistakes).
Cannot straightforwardly reuse data from an old policy.
The distinction becomes practically important later: replay buffers and most deep value-based methods rely on off-policy learning, while many policy-gradient methods (next lesson) are on-policy.
Where this leads: the exploration problem
The Q-learning loop above has a hidden dependency: it only converges if the agent keeps trying every state–action pair often enough. If it always acts greedily on its current estimates, it can lock onto a mediocre action and never discover a better one whose value it underestimated. Deciding when to trust current estimates versus gather more information is the exploration–exploitation tradeoff, the subject of a dedicated lesson later in this course. The epsilon in the code above is a first taste of the fix.
Common mistakes
Bootstrapping past a terminal state. At episode end the target is just r; adding γmaxa′Q(s′,a′) for a terminal s′ injects phantom value.
Confusing SARSA and Q-learning. Q-learning's target uses maxa′Q(s′,a′) (off-policy); SARSA uses for the action actually chosen (on-policy).
Learning rate too large. With α near 1 the estimate chases the latest noisy target and never settles. Decay α over time for tabular convergence.
Acting purely greedily during learning. Without exploration, unvisited state–action pairs keep stale estimates and the agent can converge to a suboptimal policy.
Forgetting Q estimates the return, not the reward. A high Q(s,a) can come from small rewards accumulated over many steps, not a big immediate payoff.
Further reading
Sutton & Barto, Reinforcement Learning: An Introduction (2nd ed.), Chapters 3–6 develop value functions, the Bellman equations, and TD/Q-learning rigorously: http://incompleteideas.net/book/the-book.html
Mnih et al., "Human-level control through deep reinforcement learning" (DQN, Nature 2015), scales Q-learning to pixels with function approximation: https://www.nature.com/articles/nature14236