Equations · Watkins, “Learning from Delayed Rewards” (PhD thesis, 1989); Watkins and Dayan, “Q-learning” (1992)

The Q-learning update rule, explained

Q-learning learns the value of each action in each state from experience, one transition at a time. It nudges the current estimate toward the reward received plus the best value available from the next state. Deep Q-networks (DQN) use the same target with a neural network in place of the table.

Q(st,at)←Q(st,at)+α[rt+1+γmax⁡aQ(st+1,a)−Q(st,at)]Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha\left[r_{t+1} + \gamma \max_{a} Q(s_{t+1}, a) - Q(s_t, a_t)\right]

Open in the decoder →

Term by term

  1. Q(st,at)Q(s_t, a_t)

    The current estimate of the action value: the expected return from taking action ata_t in state sts_t and acting well afterwards. Not the query matrix of attention.

  2. ←\leftarrow

    Assignment: overwrite the stored value. This is an update rule, not an equation.

  3. α\alpha

    The learning rate, between 0 and 1: how far to move toward the target.

  4. rt+1+γmax⁡aQ(st+1,a)r_{t+1} + \gamma \max_{a} Q(s_{t+1}, a)

    The TD target: the reward received plus the discounted value of the best action in the next state. The max is what makes Q-learning learn the optimal policy's values whatever policy collected the data (off-policy).

  5. […−Q(st,at)][\ldots - Q(s_t, a_t)]

    The TD error, often written δt\delta_t: target minus current estimate. Zero when the estimate already agrees with the target.

A small worked example

Q(s,a)=2Q(s, a) = 2, reward r=1r = 1, the best action in the next state has Q=4Q = 4, γ=0.9\gamma = 0.9, α=0.5\alpha = 0.5. Target: 1+0.9×4=4.61 + 0.9 \times 4 = 4.6. TD error: 2.62.6. New value: 2+0.5×2.6=3.32 + 0.5 \times 2.6 = 3.3. At the end of an episode the target is just rr.

In code

import numpy as np

def q_update(Q, s, a, r, s2, done, alpha=0.1, gamma=0.99):
    # Q: (num_states, num_actions) table
    target = r if done else r + gamma * Q[s2].max()
    Q[s, a] += alpha * (target - Q[s, a])

Every symbol in it

Qπ(s,a)=Eπ[Gt∣st=s,at=a]Q^\pi(s, a) = \mathbb{E}_\pi\left[G_t \mid s_t = s, a_t = a\right]Action-value function Qst,at,rt,st+1s_t, a_t, r_t, s_{t+1}State s and action axi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)θ←θ−η∇θL\theta \leftarrow \theta - \eta \nabla_\theta \mathcal{L}Assignment arrowα\alphaAlphart=R(st,at)r_t = R(s_t, a_t)Reward rγ\gammaGammamax⁡(0,x)\max(0, x)Max and minδ\deltaDelta (lowercase)

Other equations