Reinforcement Learning Basics

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

In supervised learning a model is shown the right answer for each input. In reinforcement learning (RL) there is no teacher: an agent acts in an environment, receives a numerical reward, and must discover, by trial and error, which behaviour earns the most reward over time. The two defining difficulties are that the reward may arrive long after the action that caused it (the credit assignment problem) and that the agent’s own actions determine what data it sees (so it must balance exploration and exploitation). This page covers the vocabulary, the central equations, the main algorithm families, and a hands-on path with Gymnasium and Stable-Baselines3.

The code targets Python 3.13 and PyTorch 2.15, with Gymnasium 1.4 and Stable-Baselines3 2.9, checked on 2026-10-30. Examples were run on Python 3.13 with Gymnasium 1.4.0, Stable-Baselines3 2.9.2 and PyTorch 2.15 (CPU) on 2026-11-01. The older package gym (OpenAI Gym) is no longer maintained and its successor is Gymnasium; the two APIs differ (see the pitfalls). For the broader place of RL among learning paradigms see Types of Learning; for optimisation background see Gradient Descent & Optimization.

The reinforcement learning problem

At each discrete time step \(t\), the agent observes a state \(s_t\), chooses an action \(a_t\), and the environment returns a reward \(r_{ t+1 }\) and a next state \(s_{ t+1 }\). The loop repeats until the episode ends (a task with a natural end such as a game) or forever (a continuing task such as controlling a data centre).

flowchart LR A["Agent (policy)"] -- "action a_t" --> E["Environment"] E -- "state s_t+1 and reward r_t+1" --> A

The standard mathematical model is the Markov decision process (MDP): a set of states, a set of actions, transition probabilities \(P(s' \mid s, a)\), a reward function, and a discount factor \(\gamma \in [0, 1)\). The Markov property says the next state depends only on the current state and action, not on the earlier history. When the agent sees only part of the true state (a partial observation, such as a single game frame without velocity), the problem is a POMDP, and the agent needs memory: stacked frames, a recurrent network or a transformer. This is a frequent source of silent failure.

Return, policy and value

  • The return is the discounted sum of future rewards: \(G_t = r_{ t+1 } + \gamma r_{ t+2 } + \gamma^2 r_{ t+3 } + \dots\). The discount \(\gamma\) makes the sum finite for continuing tasks and expresses a preference for sooner rewards; values around 0.99 are common.

  • A policy \(\pi(a \mid s)\) is the agent’s behaviour: a probability distribution over actions in each state (stochastic), or a deterministic mapping.

  • The state-value function \(V^\pi(s)\) is the expected return starting from \(s\) and following \(\pi\). The action-value function \(Q^\pi(s, a)\) is the expected return after taking action \(a\) in \(s\) and following \(\pi\) afterwards.

  • The advantage \(A^\pi(s, a) = Q^\pi(s, a) - V^\pi(s)\) says how much better an action is than the policy’s average in that state.

The goal is a policy that maximises the expected return from the start state.

The Bellman equations

Value functions satisfy a recursive relationship that is the foundation of most RL algorithms. The value of a state is the expected immediate reward plus the discounted value of the next state:

\[V^\pi(s) = \sum_a \pi(a \mid s) \sum_{ s' } P(s' \mid s, a) \left[ r(s, a, s') + \gamma V^\pi(s') \right]\]

For the best possible behaviour the Bellman optimality equation replaces the average over actions by a maximum:

\[Q^(s, a) = \sum_{ s' } P(s' \mid s, a) \left[ r(s, a, s') + \gamma \max_{ a' } Q^(s', a') \right]\]

If \(Q^\) is known, the optimal policy is simply to pick \(\arg\max_a Q^(s, a)\) in every state. Algorithms differ in how they approximate these quantities from experience when \(P\) is unknown.

Families of algorithms

Family Idea Examples

Dynamic programming

The model \(P\) is known; iterate the Bellman equations.

Policy iteration, value iteration

Value-based (model-free)

Learn \(Q(s, a)\) from experience; act greedily with some exploration.

Q-learning, SARSA, DQN and its variants

Policy-based

Parameterise the policy and ascend the gradient of the expected return.

REINFORCE, policy gradient with baselines

Actor-critic

A policy (actor) trained with the help of a learned value function (critic).

A2C, PPO, SAC, TD3, DDPG

Model-based

Learn a model of the environment and plan with it.

Dyna, MuZero-style systems, world models

Offline and imitation

Learn from a fixed dataset or from demonstrations, with no environment interaction.

Behaviour cloning, conservative Q-learning

On-policy methods (SARSA, A2C, PPO) learn about the policy that is generating the data, and must discard data after each update. Off-policy methods (Q-learning, DQN, SAC) can learn from data produced by an older or different policy, and so can reuse a replay buffer, which makes them more sample-efficient but harder to stabilise.

Exploration versus exploitation

If the agent always takes the action that looks best, it may never discover better ones; if it explores too much, it wastes reward. Common strategies are:

  • Epsilon-greedy: with probability \(\varepsilon\) take a random action, otherwise the greedy one; decay \(\varepsilon\) over time.

  • Softmax (Boltzmann) exploration: sample actions in proportion to their exponentiated values.

  • Entropy regularisation: add a bonus for keeping the policy stochastic (used by PPO and SAC).

  • Noise injected into continuous actions (Gaussian or Ornstein-Uhlenbeck noise in DDPG and TD3) or into the parameters.

  • Intrinsic motivation: a curiosity bonus for novel states, for hard problems with sparse rewards.

Tabular Q-learning

For small discrete problems the action-value function can be a table with one entry per state-action pair. Q-learning updates an entry after every step using the temporal-difference (TD) error, the difference between the current estimate and a bootstrapped target:

\[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]\]

The learning rate \(\alpha\) controls the step size. The update is off-policy because the target uses the greedy maximum regardless of which action was actually taken. SARSA uses the action actually taken next and is on-policy.

Gymnasium’s API, used in all RL code below, is: env.reset(seed=...) returns (observation, info); env.step(action) returns (observation, reward, terminated, truncated, info). Terminated means the episode ended in a terminal state of the MDP (the pole fell, the goal was reached); truncated means it was cut off by a time limit or other external condition. The distinction matters for the learning target: after termination the future value is 0, but after truncation it is not, so a bootstrapped target should still use the next state’s value.

pip install "gymnasium>=1.4" stable-baselines3
import gymnasium as gym
import numpy as np

env = gym.make("FrozenLake-v1", is_slippery=False)   # 4x4 grid, 16 states, 4 actions
n_states, n_actions = env.observation_space.n, env.action_space.n

rng = np.random.default_rng(0)
Q = np.zeros((n_states, n_actions))
alpha, gamma = 0.8, 0.95
episodes = 2000

for ep in range(episodes):
    eps = max(0.05, 1.0 - ep / (0.7 * episodes))      # decaying exploration
    state, _ = env.reset(seed=int(rng.integers(1_000_000)))
    done = False
    while not done:
        if rng.random() < eps:
            action = int(env.action_space.sample())
        else:
            # break ties randomly so an all-zero row does not always pick action 0
            best = np.flatnonzero(Q[state] == Q[state].max())
            action = int(rng.choice(best))
        next_state, reward, terminated, truncated, _ = env.step(action)
        # bootstrap unless the episode really ended (terminated), not merely truncated
        target = reward + gamma * Q[next_state].max() * (not terminated)
        Q[state, action] += alpha * (target - Q[state, action])
        state = next_state
        done = terminated or truncated

env.close()

# Evaluate the greedy policy
env = gym.make("FrozenLake-v1", is_slippery=False)
wins = 0
for _ in range(100):
    s, _ = env.reset()
    done = False
    while not done:
        s, r, terminated, truncated, _ = env.step(int(Q[s].argmax()))
        done = terminated or truncated
    wins += r
print("success rate:", wins / 100)

Output:

success rate: 1.0

With is_slippery=True the environment is stochastic and the same code needs many more episodes. Tabular methods do not scale to large or continuous state spaces; there the table is replaced by a function approximator.

Deep reinforcement learning

DQN

The Deep Q-Network replaces the table with a neural network \(Q_\theta(s, \cdot)\) that outputs one value per discrete action. Training a network on bootstrapped targets is unstable because the data is correlated and the target moves as the network changes. DQN adds two stabilisers:

  • A replay buffer stores past transitions and trains on random mini-batches, breaking temporal correlation and reusing data.

  • A target network, a slowly updated copy of the Q-network, computes the bootstrap target so that it does not change at every step.

Later refinements are Double DQN (reduces overestimation by separating action selection from evaluation), dueling networks, prioritised replay, distributional and noisy-network variants, combined in Rainbow. DQN handles discrete actions only.

Policy gradients

Policy-gradient methods optimise a parameterised policy \(\pi_\theta\) directly by gradient ascent on the expected return. The basic estimator (REINFORCE) is:

\[\nabla_\theta J(\theta) = \mathbb{E}\left[ \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) \, G_t \right]\]

Intuitively, make actions that were followed by high return more probable and those followed by low return less probable. The estimate is unbiased but noisy; subtracting a baseline (typically the learned value function) leaves the expectation unchanged and greatly reduces the variance. With a learned baseline the method becomes actor-critic, and \(G_t\) is replaced by an advantage estimate (generalised advantage estimation, GAE). Policy gradients work for continuous actions, for example by outputting the mean and standard deviation of a Gaussian.

PPO

Proximal Policy Optimization (PPO) is the default on-policy algorithm in practice. It collects a batch of experience with the current policy, then performs several epochs of mini-batch updates, using a clipped objective so that one update cannot move the policy too far from the one that produced the data. The clip range (clip_range, default 0.2 in Stable-Baselines3) limits the ratio of new to old action probabilities. PPO is relatively robust to hyperparameters and works with discrete and continuous actions, which is why it is also the algorithm behind most reinforcement learning from human feedback pipelines for language models (see below).

For continuous control with high sample efficiency, SAC and TD3 are common off-policy alternatives.

Stable-Baselines3

Stable-Baselines3 (SB3) is a set of reliable, well-documented PyTorch implementations of RL algorithms (A2C, DDPG, DQN, PPO, SAC, TD3, and others) with a uniform interface. Its companion package sb3-contrib adds further algorithms (for example recurrent PPO, TRPO, and masked PPO for invalid actions). Version 2.9 targets Gymnasium. The typical workflow is: create a vectorised environment, instantiate an algorithm with a policy name, call learn, evaluate and save.

import gymnasium as gym
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.monitor import Monitor

# four environment copies run in parallel to decorrelate and speed up data collection
vec_env = make_vec_env("CartPole-v1", n_envs=4, seed=0)

model = PPO("MlpPolicy", vec_env, verbose=1, seed=0)
model.learn(total_timesteps=50_000)

# evaluate on a separate environment (not the training one)
eval_env = Monitor(gym.make("CartPole-v1"))   # Monitor records the true episode rewards and lengths
mean_reward, std_reward = evaluate_policy(model, eval_env, n_eval_episodes=20)
print(f"mean reward {mean_reward:.1f} +/- {std_reward:.1f}")   # 500 is the maximum

model.save("ppo_cartpole")
loaded = PPO.load("ppo_cartpole", env=vec_env)

# Use the trained policy
obs, _ = eval_env.reset(seed=1)
done = False
while not done:
    action, _ = loaded.predict(obs, deterministic=True)
    obs, reward, terminated, truncated, _ = eval_env.step(action)
    done = terminated or truncated

After the training log (a table printed every rollout), the evaluation printed the following; the exact value varies between runs because the evaluation episodes start from unseeded states:

mean reward 496.4 +/- 12.6

For other algorithms swap the class (DQN("MlpPolicy", env) for discrete actions, SAC("MlpPolicy", env) for continuous ones). For image observations use "CnnPolicy" with a frame-stacking wrapper. Stable-Baselines3 saves a zip archive that includes serialised Python objects; treat a model file like code and load only files you trust. For a custom environment, subclass gymnasium.Env, define observation_space and action_space, implement reset and step, and check it with stable_baselines3.common.env_checker.check_env.

Monitoring matters: the logged mean episode reward and episode length (ep_rew_mean, ep_len_mean) are the first thing to look at, and TensorBoard logging is available through the tensorboard_log argument (install tensorboard separately). See Experiment Tracking & MLOps for tracking runs.

Reinforcement learning and language models

RL appears in the language-model pipeline as reinforcement learning from human feedback (RLHF): a reward model is trained on human preference comparisons, and the language model is then optimised with a policy-gradient method (PPO historically, simpler variants such as GRPO and direct preference optimisation more recently) to produce responses with a higher reward while staying close to a reference model. A related line uses verifiable rewards (does the code pass the tests, is the maths answer correct) to train reasoning models. The preference and fine-tuning tooling is described in Fine-Tuning with PEFT & TRL (TRL provides the trainers), the pipeline stages in Training Pipeline and the resulting models in Reasoning Models.

Practical pitfalls

  • Reward design. Agents optimise exactly what is rewarded, not what you meant ("reward hacking"). A reward that is easy to exploit, such as circling to collect points, produces surprising behaviour. Prefer simple, verifiable rewards and inspect behaviour, not only the reward curve.

  • Sparse rewards. If reward arrives only at the goal, random exploration may never reach it. Use reward shaping carefully (potential-based shaping preserves the optimal policy), curriculum learning, demonstrations, or intrinsic motivation.

  • Sample inefficiency. Model-free RL often needs millions of interactions. Use fast simulators and vectorised environments, and consider whether a simpler method (planning, supervised learning from logs, a bandit) would do.

  • Seeds and variance. Results vary substantially between seeds. Report the mean and spread over several seeds, and compare against a strong baseline, not a single lucky run.

  • Hyperparameter sensitivity. Learning rate, discount, batch size, network size and the number of environments change outcomes. Start from the library defaults or published zoo settings (RL Baselines3 Zoo) before tuning.

  • Observation and reward scaling. Normalise observations and rewards (SB3’s VecNormalize), and save the normalisation statistics together with the model.

  • Terminated versus truncated. Treating time-limit truncation as termination biases value estimates. Gymnasium separates them for this reason.

  • API drift from old tutorials. In OpenAI Gym before 0.26, reset() returned only the observation and step() returned four values (obs, reward, done, info). In Gymnasium, reset() returns (obs, info) and step() returns five values. Old code that unpacks four values fails with an error; replace import gym with import gymnasium as gym and split done into terminated and truncated.

  • Evaluation in the training environment. Evaluate with a separate environment, deterministic actions where appropriate, and enough episodes.

  • Safety and deployment. A policy trained in simulation may fail in the real world (the sim-to-real gap); in production, constrain actions and monitor for distribution shift. Many business problems called RL are better solved with contextual bandits or supervised learning on logged data.

Where to go next

Sutton and Barto’s textbook is the standard reference and is free online; the Hugging Face Deep RL course and the Gymnasium and Stable-Baselines3 documentation provide hands-on practice. For algorithms beyond SB3 (distributed training, offline RL, multi-agent environments), look at libraries such as CleanRL (single-file reference implementations), RLlib and TorchRL, and check their maintenance status before adopting them.