AI & ML Quick Path Progress

Part 4: Deep learning Lesson 13 of 15 in this part

Reinforcement learning: value methods

What you will learn. Estimate how good each state is from experience with Monte Carlo and temporal-difference learning, learn the value of each action with Q-learning and SARSA, and explain how a deep Q-network replaces the table with a neural network.

  • Advanced
  • Study time about 75 min
  • Maths Some algebra
  • Python: example run
  • C#: compiled and run

Before this lesson: Reinforcement learning. Already know these? Carry on.

In plain words

A reinforcement-learning agent acts, gets rewards and wants the largest total over time. A value says how much total reward to expect from here on. If the agent knows the value of every state, or of every action in every state, it can simply choose well. Monte Carlo learning plays a whole episode, then looks back and averages the rewards that followed each state. Temporal-difference (TD) learning updates after every step: it nudges its estimate towards the reward just received plus its current estimate of the next state. That lets it learn before an episode ends. Q-learning and SARSA apply the same idea to the value of each action, called Q. They differ in one thing: Q-learning looks at the best action in the next state, SARSA looks at the action the agent actually takes. When the problem has too many states for a table, a deep Q-network (DQN) uses a neural network to estimate Q.

Diagram Monte Carlo and temporal-difference learning

Monte Carlo

  • Waits until the episode ends
  • Uses the real total reward that followed

Temporal difference

  • Updates after every step
  • Uses reward plus its estimate of the next state

Both estimate value from experience. They differ in when they learn.

Diagram One Q-learning step
  1. InputLook at the state and pick an actionMostly the best, sometimes a random one
  2. ProcessAct and see the reward and the next stateWhat the world does
  3. ModelCompare what happened with what was expectedThe TD error
  4. OutputNudge the action value towards the estimateSmall step, set by a learning rate

Repeat for every step of every episode

The table of action values slowly fills in with what the agent learns.

Diagram Q-learning and SARSA

Q-learning

  • Looks at the best action in the next state
  • Learns the value of playing well

SARSA

  • Looks at the action it really takes next
  • Learns the value of its own exploring

Same update rule. A different choice of what comes next.

Diagram From a table to a network
  1. RiskToo many states to store in a tableImages, positions, sensor readings
  2. ModelUse a network that maps a state to action valuesThe deep Q-network
  3. ProcessTrain with replayed steps and a slow copyReplay buffer and target network

A network can estimate Q for states it has never visited, but training can become unstable.

Real-world example

A warehouse robot has to learn the quickest way along a corridor to a charging dock. Its state is its position and its actions are left and right. It gets no reward until it reaches the dock. At first it wanders, but after enough trips the values of the states near the dock rise, then the values further away, as the reward passes back one step at a time. The engineers run Q-learning in a simulator first, because a wrong move costs time and the robot needs thousands of trips. They watch for the case where the learned route differs from the safe route they wanted.

How it works

  1. Discounting. A reward later is worth a little less than a reward now. Multiply by a discount, such as 0.9, for each step of delay.
  2. Monte Carlo. After an episode, the value of a state is the discounted rewards that followed it. Average over many episodes.
  3. TD. After each step, the new estimate of a state's value is the old estimate plus a small step towards (reward + discount × next state's value). The gap is the TD error.
  4. Q-learning and SARSA. The same update, applied to action values. Q-learning uses the best next action, SARSA uses the next action taken.
  5. Exploration. With a small chance the agent tries a random action, so it can find better routes.

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.

A five-state corridor with the reward on reaching the last state. First the policy "always right" is evaluated two ways, with exact returns and with TD updates. Then Q-learning and SARSA each learn for 200 episodes, with a small random generator so the numbers repeat.

Python — rl_value.py
"""Value methods on a five-state corridor: Monte Carlo and temporal-difference estimates, then Q-learning and SARSA.

States 0 to 4, the agent starts at 0 and the only reward (+1) comes on reaching state 4. Discount 0.9.
Exploration uses a small repeatable random generator, so the numbers repeat and match the C# version.
Run:  python rl_value.py
"""
gamma = 0.9

# 1. Evaluate the policy "always move right" from the same five episodes by two methods
#    Every episode is the same walk, 0 -> 1 -> 2 -> 3 -> 4, so returns are exact.
G = [gamma ** (3 - s) for s in range(4)]                     # return from state s: reward 1 after (4 - s) steps
print("Monte Carlo return from states 0, 1, 2, 3:", " ".join("%.3f" % g for g in G))
V = [0.0] * 5
for episode in range(30):                                    # TD(0): V(s) += alpha * (r + gamma V(s') - V(s))
    for s in range(4):
        r = 1.0 if s == 3 else 0.0
        V[s] += 0.5 * (r + gamma * V[s + 1] - V[s])
print("TD(0) estimates after 30 episodes:       ", " ".join("%.3f" % v for v in V[:4]))

# 2. Q-learning and SARSA with epsilon-greedy exploration (actions: 0 = left, 1 = right)
class Lcg:
    def __init__(self, seed): self.x = seed
    def next(self):
        self.x = (1103515245 * self.x + 12345) % (2 ** 31)
        return self.x / 2 ** 31

def run(on_policy):
    rng, Q = Lcg(7), [[0.0, 0.0] for _ in range(5)]
    def act(s):
        if rng.next() < 0.3:
            return 0 if rng.next() < 0.5 else 1
        return 1 if Q[s][1] >= Q[s][0] else 0
    for episode in range(200):
        s, a = 0, act(0)
        for step in range(30):
            s2 = max(0, s - 1) if a == 0 else min(4, s + 1)
            r = 1.0 if s2 == 4 else 0.0
            a2 = act(s2)
            nxt = 0.0 if s2 == 4 else (Q[s2][a2] if on_policy else max(Q[s2]))
            Q[s][a] += 0.2 * (r + gamma * nxt - Q[s][a])
            if s2 == 4: break
            s, a = s2, a2
    return Q
for name, flag in (("Q-learning", False), ("SARSA", True)):
    Q = run(flag)
    print("%-10s value of 'right' in states 0 to 3: %s   best action in each: %s" % (name, " ".join("%.3f" % Q[s][1] for s in range(4)), "".join("R" if Q[s][1] >= Q[s][0] else "L" for s in range(4))))
Output — Output of rl_value.py (executed)
Monte Carlo return from states 0, 1, 2, 3: 0.729 0.810 0.900 1.000
TD(0) estimates after 30 episodes:        0.729 0.810 0.900 1.000
Q-learning value of 'right' in states 0 to 3: 0.729 0.810 0.900 1.000   best action in each: RRRR
SARSA      value of 'right' in states 0 to 3: 0.639 0.782 0.889 1.000   best action in each: RRRR

Monte Carlo and TD agree: 0.729, 0.810, 0.900 and 1.000 for states 0 to 3. Q-learning finds the same values for the action "right", and the best action everywhere is right. SARSA finds lower values (0.639 for state 0 against 0.729) because it includes its own random moves, though it also learns to go right everywhere.

More ideas, named. The deadly triad is the combination of function approximation (a network), bootstrapping (TD) and off-policy learning, which can make training diverge. Double DQN fixes the habit of Q-learning to over-estimate values. Prioritised replay replays the surprising steps more often. Rainbow combines several of these upgrades. Eligibility traces, or TD(lambda), spread each TD error back over recent states so the reward travels faster. A deep Q-network was not run here because PyTorch was not installed.

.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 corridor in C#, from scratch, with no packages, printing the same output. For deep reinforcement learning you would train in Python (for example with Stable-Baselines3) and run the trained network from .NET through ONNX Runtime.

C# — Program.cs
// Value methods on a five-state corridor, from scratch. Same output as rl_value.py. No packages.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
double gamma = 0.9;

// 1. Evaluate the policy "always move right": exact returns, then TD(0) from the same walk
var returns = Enumerable.Range(0, 4).Select(s => Math.Pow(gamma, 3 - s)).ToArray();
Console.WriteLine("Monte Carlo return from states 0, 1, 2, 3: " + string.Join(" ", returns.Select(g => g.ToString("F3"))));
var V = new double[5];
for (int episode = 0; episode < 30; episode++)
    for (int s = 0; s < 4; s++)
    {
        double r = s == 3 ? 1.0 : 0.0;
        V[s] += 0.5 * (r + gamma * V[s + 1] - V[s]);              // TD(0): V(s) += alpha * (r + gamma V(s') - V(s))
    }
Console.WriteLine("TD(0) estimates after 30 episodes:        " + string.Join(" ", V.Take(4).Select(v => v.ToString("F3"))));

// 2. Q-learning and SARSA with epsilon-greedy exploration (actions: 0 = left, 1 = right)
double[][] Run(bool onPolicy)
{
    long state = 7;
    double Next() { state = (1103515245L * state + 12345) % (1L << 31); return state / (double)(1L << 31); }
    var Q = Enumerable.Range(0, 5).Select(_ => new double[2]).ToArray();
    int Act(int s)
    {
        if (Next() < 0.3) return Next() < 0.5 ? 0 : 1;
        return Q[s][1] >= Q[s][0] ? 1 : 0;
    }
    for (int episode = 0; episode < 200; episode++)
    {
        int s = 0, a = Act(0);
        for (int step = 0; step < 30; step++)
        {
            int s2 = a == 0 ? Math.Max(0, s - 1) : Math.Min(4, s + 1);
            double r = s2 == 4 ? 1.0 : 0.0;
            int a2 = Act(s2);
            double nxt = s2 == 4 ? 0.0 : (onPolicy ? Q[s2][a2] : Math.Max(Q[s2][0], Q[s2][1]));
            Q[s][a] += 0.2 * (r + gamma * nxt - Q[s][a]);
            if (s2 == 4) break;
            s = s2; a = a2;
        }
    }
    return Q;
}
foreach (var (name, flag) in new[] { ("Q-learning", false), ("SARSA", true) })
{
    var Q = Run(flag);
    string values = string.Join(" ", Enumerable.Range(0, 4).Select(s => Q[s][1].ToString("F3")));
    string best = string.Concat(Enumerable.Range(0, 4).Select(s => Q[s][1] >= Q[s][0] ? "R" : "L"));
    Console.WriteLine($"{name,-10} value of 'right' in states 0 to 3: {values}   best action in each: {best}");
}

Maths behind it

  • Discounted sums: geometric series (algebra)
  • Moving an estimate towards a target by a small step (arithmetic)
  • Averages of sampled returns (statistics)
  • Maximum over actions (arithmetic)

Common mistakes

  • A learning rate too high, so the estimates jump on noise, or too low, so learning is slow.
  • Never exploring, so the agent never finds a better route.
  • Comparing Q-learning and SARSA values as if they measured the same thing.
  • Training a network on consecutive steps without a replay buffer, which makes the data too similar.
  • Designing a reward that the agent can satisfy without doing what you meant.

Quick check

  1. What is the main difference between Monte Carlo and TD learning?

    Show answer

    Monte Carlo waits for the end of the episode and uses the real total reward. TD updates after each step, using the reward plus its own estimate of the next state.

  2. What is a TD error?

    Show answer

    The gap between what happened (reward plus the discounted value of the next state) and what was expected (the current value).

  3. Why are SARSA's values lower than Q-learning's in the example?

    Show answer

    SARSA's update includes the agent's own random exploratory moves, which are sometimes poor. Q-learning always assumes the best next action.

  4. What problem does a replay buffer solve in a DQN?

    Show answer

    Consecutive steps are very similar, which destabilises training. Sampling past steps at random breaks that similarity.

Completion

Evidence of completion. A table of state values on a small corridor from two methods that agree, and a comparison of the Q-learning and SARSA values after the same number of episodes, with a sentence saying why they differ.

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.

This lesson prepares you for: Reinforcement learning: policy methods.