Q-Learning

Learning the best action in every situation, purely by trial and error.

🟡 intermediate4 min readrl
Q-learning teaches an agent which action is best in each situation, purely by trial and error, without needing a model of how the world works. It keeps a score for every situation and action, estimating the total future reward of taking that action there. After each move it nudges that score toward the reward it just got plus the best score available from where it landed. It learns the best behaviour even while still exploring with random moves, which is why it is called off-policy.

Q-Learning Mechanics

Q-Learning maintains a table (or function approximator) Q(s,a)Q(s, a) storing expected cumulative return for taking action aa in state ss.

                        Q-LEARNING ITERATION LOOP
  1. Observe State s
  2. Select Action a using ε-Greedy (Exploration vs Exploitation)
  3. Execute Action a ──► Observe Reward r and Next State s'
  4. Compute TD Target:   Target = r + γ max_{a'} Q(s', a')
  5. Compute TD Error:    δ = Target - Q(s, a)
  6. Update Q Table:      Q(s, a) ← Q(s, a) + α · δ

The Single-Step Update Formula

Q(s,a)←Q(s,a)+α(r+γmax⁡a′Q(s′,a′)⏟TD Target−Q(s,a))⏞TD Error δtQ(s, a) \leftarrow Q(s, a) + \alpha \overbrace{\Big( \underbrace{r + \gamma \max_{a'} Q(s', a')}_{\text{TD Target}} - Q(s, a) \Big)}^{\text{TD Error } \delta_t}

Exploration vs Exploitation (ϵ\epsilon-Greedy Policy)

To avoid getting trapped in local sub-optimal actions, actions are selected via ϵ\epsilon-greedy:

at={Random Action a∈Awith probability ϵ(Exploration)arg⁡max⁡aQ(st,a)with probability 1−ϵ(Exploitation)a_t = \begin{cases} \text{Random Action } a \in A & \text{with probability } \epsilon \quad \text{(Exploration)} \\ \arg\max_a Q(s_t, a) & \text{with probability } 1 - \epsilon \quad \text{(Exploitation)} \end{cases}

Typically, decay ϵ→0.01\epsilon \to 0.01 over training iterations.

Convergence Proof

Watkins & Dayan (1992) proved that Tabular Q-Learning converges to optimal action-values Q∗(s,a)Q^*(s, a) with probability 1 if:

  1. All state-action pairs (s,a)(s, a) are visited infinitely often.
  2. Learning rate satisfies Robbins-Monro conditions: ∑αt=∞\sum \alpha_t = \infty and ∑αt2<∞\sum \alpha_t^2 < \infty.

Say this out loud

"Q-Learning is a model-free, off-policy TD control algorithm. It updates action values using Q(s,a) ← Q(s,a) + α [r + γ max_{a'} Q(s',a') - Q(s,a)]. It is off-policy because it uses a greedy max target max_{a'} Q(s',a') to evaluate optimal behavior while executing an ε-greedy behavior policy for exploration."

Follow-ups to expect

Check yourself

Question 1 of 3

What is the single-step Q-Learning update rule for updating Q(s, a) given sample experience (s, a, r, s')?

More in Reinforcement Learning

See all →
Value-Based vs Policy-Based Methods5 minMulti-Armed Bandits4 minProximal Policy Optimization5 min