Machine Learning · 18 of 20

Q-Learning tutorial

Learns the long-term value of actions by exploring rewards in an environment. Learn the concept, implement it from scratch, and apply it with Gymnasium and NumPy.

Category
Reinforcement learning
Core idea
Q(s,a) ← Q(s,a) + α[r + γ maxₐ′ Q(s′,a′) − Q(s,a)]
Typical use
Navigation, scheduling, games, and sequential decision-making.
Practical tool
Gymnasium and NumPy

What is Q-Learning?

Q-Learning is a reinforcement learning technique. Learns the long-term value of actions by exploring rewards in an environment. Its central idea is summarized by Q(s,a) ← Q(s,a) + α[r + γ maxₐ′ Q(s′,a′) − Q(s,a)].

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with Gymnasium and NumPy and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when Q-Learning is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with Gymnasium and NumPy and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python functions, NumPy arrays, and basic descriptive statistics.
  • A clear distinction between training data, validation data, and untouched test data.
  • Familiarity with features, targets, preprocessing, and task-appropriate evaluation metrics.
LanguagePython 3
Primary libraryGymnasium and NumPy
Learning modeFrom scratch + library

How Q-Learning works

  1. 1

    Input

    States, available actions, rewards, and observed next states.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Update action values from reward plus the best future value.

  4. 4

    Output

    A policy that chooses the highest-value action in each state.

  5. 5

    Validate

    Evaluate the greedy policy over many episodes without exploration and report mean return plus success rate.

Formula and intuition

Q(s,a) ← Q(s,a) + α[r + γ maxₐ′ Q(s′,a′) − Q(s,a)]

α is the learning rate, γ is the discount factor, r is the reward, and s′ is the next state.

The notation captures the main operation or complexity statement behind Q-Learning. Read it together with the symbol key above and the step-by-step process in this guide.

When to use Q-Learning

Navigation, scheduling, games, and sequential decision-making.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

Q-Learning from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
import numpy as np

size = 5
Q = np.zeros((size, size, 4))  # up, right, down, left
rng = np.random.default_rng(0)
alpha, gamma, epsilon = .2, .95, .2

for _ in range(1000):
    state = [0, 0]
    while state != [4, 4]:
        action = rng.integers(4) if rng.random() < epsilon else Q[state[0], state[1]].argmax()
        move = [(-1,0), (0,1), (1,0), (0,-1)][action]
        nxt = [np.clip(state[0]+move[0], 0, 4), np.clip(state[1]+move[1], 0, 4)]
        reward = 10 if nxt == [4, 4] else -1
        target = reward + gamma * Q[nxt[0], nxt[1]].max()
        Q[state[0], state[1], action] += alpha * (target - Q[state[0], state[1], action])
        state = nxt
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build Q-Learning with Gymnasium and NumPy

Gymnasium supplies a standard environment API while NumPy holds the tabular action-value function.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Install the required package python -m pip install numpy gymnasium
  1. Prepare the data.States, available actions, rewards, and observed next states. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Update action values from reward plus the best future value.
  4. Inspect the result.A policy that chooses the highest-value action in each state. Then apply the evaluation checks in the next section.
PythonGymnasium and NumPy workflow
import gymnasium as gym
import numpy as np

env = gym.make("FrozenLake-v1", is_slippery=False)
Q = np.zeros((env.observation_space.n, env.action_space.n))
rng = np.random.default_rng(7)
alpha, gamma = 0.2, 0.95

for episode in range(5000):
    state, _ = env.reset(seed=episode)
    terminated = truncated = False
    epsilon = max(0.02, 1 - episode / 3500)
    while not (terminated or truncated):
        action = rng.integers(4) if rng.random() < epsilon else Q[state].argmax()
        nxt, reward, terminated, truncated, _ = env.step(action)
        target = reward + gamma * Q[nxt].max() * (not terminated)
        Q[state, action] += alpha * (target - Q[state, action])
        state = nxt

print("greedy policy:", Q.argmax(axis=1).reshape(4, 4))
env.close()

API details and version-specific options: official Gymnasium and NumPy reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Evaluate the greedy policy over many episodes without exploration and report mean return plus success rate.
  • Plot episodic return and Q-value change to verify that learning has stabilized.
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • Do not bootstrap from terminal states.
  • Insufficient exploration can lock the agent into a poor policy.
  • A table becomes impractical when states or actions are continuous.

Before using Q-Learning in a project

  • Define the prediction or discovery objective before selecting the algorithm.
  • Split data before fitting preprocessing and tune only inside cross-validation.
  • Record data versions, random seeds, features, hyperparameters, and evaluation metrics.
  • Compare against a simple baseline and inspect errors by meaningful subgroups.
  • Monitor input drift and real-world performance after deployment.

Official documentation and next steps

Primary software reference Gymnasium and NumPy

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See Q-Learning in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →