Reinforcement Learning: Core Concepts
1. Key Components: Agent, Environment, and Rewards
Key Components: Agent, Environment, and Rewards
The Reinforcement Learning Framework
Reinforcement learning (RL) formalizes the interaction between an agent and an environment through a sequence of states, actions, and rewards. The agent operates in discrete time steps t, where at each step, it observes the current state st from the environment, selects an action at based on its policy, and receives a scalar reward rt+1. The environment transitions to a new state st+1 according to its dynamics, and the process repeats.
The Agent
The agent is an autonomous decision-maker that implements a policy π, which maps states to actions. Policies can be deterministic (a = π(s)) or stochastic (a ∼ π(·|s)). Advanced agents often employ value functions or Q-functions to estimate expected future rewards:
where γ ∈ [0, 1] is a discount factor. Model-based agents additionally learn the environment's transition dynamics P(s'|s, a) and reward function R(s, a).
The Environment
The environment defines the problem's dynamics through a Markov Decision Process (MDP), characterized by:
- A state space S (discrete or continuous)
- An action space A
- A transition function P(s'|s, a)
- A reward function R(s, a, s')
Environments can be fully observable (the agent sees the true state) or partially observable (modeled as a POMDP). In continuous control tasks like robotic manipulation, the state and action spaces are often high-dimensional and continuous.
Reward Design
The reward signal is a critical component that shapes the agent's behavior. A well-designed reward function should:
- Align with the desired objective (e.g., +1 for reaching a goal, -0.01 per time step to encourage speed)
- Avoid sparse rewards that make learning difficult
- Prevent reward hacking (where the agent exploits unintended loopholes)
In inverse reinforcement learning, the reward function is inferred from expert demonstrations. The choice of discount factor γ trades off immediate versus long-term rewards:
Practical Considerations
In real-world applications like autonomous driving or game AI, agents must handle:
- Delayed rewards: Actions may affect rewards many steps later (e.g., a chess move)
- Partial observability: The true state may not be fully visible (e.g., poker)
- Continuous action spaces: Require policy gradient methods rather than Q-learning
Recent advances like hierarchical RL decompose complex tasks into subtasks with their own reward functions, while multi-agent RL introduces additional complexity through interacting agents.

Markov Decision Processes (MDPs)
A Markov Decision Process (MDP) is a mathematical framework for modeling sequential decision-making problems where outcomes are partly random and partly under the control of a decision-maker. Formally, an MDP is defined by the tuple (S, A, P, R, γ), where:
- S is a finite set of states,
- A is a finite set of actions,
- P(s'|s, a) is the transition probability function, representing the probability of transitioning to state s' from state s when taking action a,
- R(s, a, s') is the reward function, specifying the immediate reward received after transitioning from s to s' via action a,
- γ ∈ [0, 1] is the discount factor, which determines the present value of future rewards.
Markov Property
The defining characteristic of an MDP is the Markov property, which states that the future state and reward depend only on the current state and action, not on the history of previous states and actions. Mathematically, this is expressed as:
This property simplifies the modeling of sequential decisions by eliminating the need to track the entire history of interactions.
Policy and Value Functions
A policy π(a|s) defines the probability of taking action a in state s. The goal in an MDP is to find an optimal policy π* that maximizes the expected cumulative reward. Two key value functions are used to evaluate policies:
- State-value function Vπ(s): The expected return when starting in state s and following policy π thereafter.
- Action-value function Qπ(s, a): The expected return when taking action a in state s and thereafter following policy π.
These functions satisfy the Bellman equations:
Optimality and Dynamic Programming
An optimal policy π* satisfies Vπ*(s) ≥ Vπ(s) for all states s and policies π. The corresponding optimal value functions V* and Q* obey the Bellman optimality equations:
Dynamic programming methods, such as value iteration and policy iteration, leverage these equations to compute optimal policies for known MDPs.
Applications of MDPs
MDPs are widely used in robotics, finance, operations research, and game theory. For instance, in autonomous navigation, an MDP can model the robot's state (position, velocity), actions (move forward, turn), and rewards (reaching a goal, avoiding obstacles). Similarly, in algorithmic trading, states represent market conditions, actions are buy/sell decisions, and rewards correspond to profit maximization.

Policy, Value Functions, and Q-Learning
Policies in Reinforcement Learning
A policy π defines the agent's behavior by mapping states to actions. Formally, it is a probability distribution over actions given a state:
Deterministic policies select a single action per state (π(s) = a), while stochastic policies assign probabilities to multiple actions. Optimal policies maximize expected cumulative reward, often denoted as π*.
Value Functions
Value functions estimate long-term returns from states or state-action pairs. The state-value function Vπ(s) gives the expected return when starting in state s and following policy π:
The action-value function Qπ(s, a) extends this to include the initial action:
Here, γ ∈ [0, 1] is the discount factor balancing immediate and future rewards.
Bellman Equations
Value functions satisfy recursive Bellman equations. For Vπ(s):
For Qπ(s, a), the Bellman equation becomes:
These equations enable dynamic programming solutions like value iteration and policy iteration.
Q-Learning
Q-Learning is a model-free algorithm that directly approximates the optimal action-value function Q* using temporal difference (TD) updates. The update rule is:
Key properties:
- Off-policy: Learns Q* independent of the behavior policy.
- Greedy in the limit: With appropriate learning rates, converges to Q*.
- Tabular or function approximation: Scales via deep Q-networks (DQN) in large state spaces.
Algorithm: Q-Learning
def q_learning(env, episodes, alpha, gamma, epsilon):
Q = defaultdict(float)
for _ in range(episodes):
state = env.reset()
while not done:
action = epsilon_greedy(Q, state, epsilon)
next_state, reward, done, _ = env.step(action)
td_target = reward + gamma * max(Q[next_state].values())
Q[state][action] += alpha * (td_target - Q[state][action])
state = next_state
return Q
Practical Considerations
Q-Learning faces challenges in continuous spaces, requiring function approximation. Deep Q-Networks (DQN) address this with experience replay and target networks to stabilize training. Convergence guarantees hold only for tabular cases; neural approximators may diverge without careful tuning.

2. Epsilon-Greedy Strategy
Epsilon-Greedy Strategy
The epsilon-greedy strategy is a fundamental exploration-exploitation trade-off mechanism in reinforcement learning. It balances between selecting the action with the highest estimated value (exploitation) and exploring other actions to improve value estimates (exploration). The parameter ε (epsilon) controls the probability of exploration.
Mathematical Formulation
At each time step t, the agent selects an action a from the action space A according to the following policy:
where Q(s, a) represents the estimated value of taking action a in state s, and |A| is the cardinality of the action space.
Convergence Properties
For stationary environments, the epsilon-greedy strategy guarantees that all state-action pairs will be visited infinitely often as t → ∞, provided that ε > 0. This ensures asymptotic convergence to the optimal policy under standard stochastic approximation conditions.
However, the constant exploration probability means the agent will always perform suboptimal actions with probability at least ε/|A|, preventing it from becoming purely greedy even after convergence.
Practical Implementation
In practice, epsilon is typically initialized to 1 (pure exploration) and decayed over time according to a schedule. Common decay schemes include:
- Linear decay: εt = max(εmin, ε0 - βt)
- Exponential decay: εt = ε0γt
- Inverse time decay: εt = ε0/(1 + κt)
where β, γ, and κ are decay parameters, and εmin ensures a minimum exploration rate.
Variations and Improvements
Several modifications to the basic epsilon-greedy strategy have been proposed to address its limitations:
- Adaptive epsilon-greedy: Adjusts ε based on the uncertainty in value estimates
- Optimistic initialization: Encourages exploration through high initial Q-values
- Boltzmann exploration: Uses a softmax distribution over actions instead of uniform exploration
Performance Considerations
The choice of epsilon schedule significantly impacts learning performance. Too rapid decay may lead to premature convergence to suboptimal policies, while too slow decay results in excessive exploration. The optimal schedule depends on problem characteristics such as:
- The size of the state-action space
- The noise level in reward signals
- The degree of non-stationarity in the environment
Empirical studies suggest that exponential decay with γ ∈ [0.99, 0.999] often works well in practice for many benchmark problems.
Upper Confidence Bound (UCB)
The Upper Confidence Bound (UCB) algorithm addresses the exploration-exploitation trade-off in reinforcement learning by quantifying uncertainty in action-value estimates. Unlike ε-greedy methods, which explore randomly, UCB systematically favors actions with high potential reward based on confidence intervals derived from statistical bounds.
Mathematical Formulation
UCB selects actions by maximizing an upper confidence bound on the estimated action-value function. The UCB1 algorithm, a foundational variant, defines the bound as:
where:
- Qt(a) is the empirical mean reward of action a at time t,
- Nt(a) is the number of times action a has been selected,
- c is a hyperparameter controlling exploration,
- t is the total number of steps taken.
Derivation of the Confidence Bound
The term c√(ln t / Nt(a)) originates from Hoeffding's inequality, which bounds the deviation of empirical means from their true expectations. For a reward distribution with support in [0, 1], the probability that the true action-value q(a) exceeds the empirical mean by more than u is bounded by:
Setting the right-hand side equal to t−4 (to ensure convergence) and solving for u yields the UCB1 exploration term.
Regret Analysis
UCB1 achieves logarithmic regret, defined as the difference between the cumulative reward of the optimal action and the algorithm's performance. For K actions, the regret RT after T steps is bounded by:
where Δa is the suboptimality gap of action a. This bound highlights UCB1's efficiency in balancing exploration and exploitation.
Practical Considerations
In practice, UCB variants adapt to non-stationary environments by incorporating discount factors or sliding windows. For example, the UCB-Tuned algorithm refines the exploration term by estimating reward variances:
where Vt(a) is an empirical variance estimate. This adjustment improves performance in scenarios with heterogeneous reward distributions.
Applications
UCB is widely used in:
- Online advertising: Optimizing ad placement by modeling click-through rates as bandit problems,
- Clinical trials: Adaptive treatment allocation to maximize patient outcomes,
- Recommendation systems: Dynamically selecting content based on user feedback.
Thompson Sampling
Thompson Sampling is a Bayesian approach to the multi-armed bandit problem, balancing exploration and exploitation by sampling from posterior distributions over action rewards. Unlike deterministic methods such as UCB, it leverages probability matching to select actions, making it particularly effective in stochastic environments.
Bayesian Framework
At its core, Thompson Sampling operates within a Bayesian framework, where prior beliefs about the reward distribution of each arm are updated as observations are made. For Bernoulli bandits, a Beta distribution is commonly used as the conjugate prior due to its mathematical convenience. The posterior distribution after observing n successes and m failures for an arm is given by:
Here, θ represents the probability of success for the arm, while α and β are the parameters of the prior Beta distribution. Sampling from this posterior allows the algorithm to naturally incorporate uncertainty into its decision-making process.
Algorithmic Steps
The Thompson Sampling algorithm proceeds iteratively as follows:
- For each arm, sample a value from its current posterior distribution.
- Select the arm with the highest sampled value.
- Observe the reward and update the posterior distribution of the chosen arm.
This process ensures that arms with higher uncertainty are explored more frequently, while arms with high estimated rewards are exploited when confidence in their superiority is high.
Regret Analysis
The regret of Thompson Sampling is sublinear, meaning it converges to the optimal strategy over time. For a K-armed bandit with Bernoulli rewards, the expected cumulative regret after T rounds is bounded by:
This bound is asymptotically optimal, matching the lower bounds derived for the multi-armed bandit problem. The logarithmic dependence on T highlights the efficiency of Thompson Sampling in minimizing regret.
Practical Applications
Thompson Sampling has been successfully applied in clinical trials, online advertising, and recommendation systems. Its ability to handle delayed feedback and non-stationary environments makes it a robust choice for real-world scenarios where exploration is costly but necessary.
Extensions and Variants
Several extensions of Thompson Sampling exist, including:
- Non-conjugate priors: Gaussian Thompson Sampling for continuous rewards.
- Contextual bandits: Linear models or neural networks to incorporate contextual information.
- Hierarchical models: Sharing information across arms in structured environments.
These variants extend the applicability of Thompson Sampling to more complex decision-making problems while retaining its core Bayesian principles.

3. TD(0) and TD(λ)
TD(0) and TD(λ)
Temporal Difference (TD) learning bridges the gap between Monte Carlo methods and dynamic programming by combining bootstrapping and sampling. Two fundamental algorithms in this family are TD(0) and TD(λ), where λ is a trace-decay parameter controlling the trade-off between bias and variance.
TD(0): One-Step Temporal Difference Learning
TD(0) updates the value function based on the immediate reward and the estimated value of the next state, following the Bellman equation. The update rule for the state-value function V(s) is:
Here, α is the learning rate, γ is the discount factor, and rt+1 is the reward received after transitioning from state st to st+1. The term in brackets is the TD error, representing the difference between the current estimate and the TD target.
Eligibility Traces and TD(λ)
TD(λ) generalizes TD(0) by introducing eligibility traces, which allow credit assignment over multiple time steps. The trace et(s) for a state s at time t is updated as:
The value function update then incorporates the trace:
where δt is the TD error at time t. When λ=0, this reduces to TD(0); when λ=1, it becomes equivalent to Monte Carlo learning.
Forward and Backward Views
TD(λ) can be understood from two perspectives:
- Forward view: Updates are based on future rewards, weighted by (γλ)k for k-step returns.
- Backward view: Updates use eligibility traces to distribute credit backward along visited states.
The equivalence between these views is established by the TD(λ) theorem, proving that both yield identical updates under appropriate conditions.
Practical Considerations
In practice, λ controls the bias-variance trade-off:
- Lower λ values (closer to 0) provide faster, more biased learning.
- Higher λ values (closer to 1) reduce bias but increase variance and slow convergence.
Applications of TD(λ) include game playing (e.g., backgammon with TD-Gammon), robotics, and financial prediction, where multi-step returns improve learning efficiency.

3.2 SARSA: On-Policy TD Control
SARSA (State-Action-Reward-State-Action) is an on-policy temporal difference (TD) control algorithm that learns the action-value function Q(s, a) by bootstrapping from the current estimate of the value function. Unlike off-policy methods like Q-learning, SARSA updates its policy based on the actions selected by the current policy, making it inherently on-policy. The name derives from the sequence of elements used in the update rule: (St, At, Rt+1, St+1, At+1).
SARSA Update Rule
The core of SARSA is its TD update rule for the action-value function:
Here, α is the learning rate, γ is the discount factor, Rt+1 is the immediate reward, and Q(St+1, At+1) is the estimated value of the next state-action pair under the current policy. The term in brackets is the TD error, representing the difference between the current estimate and the new target value.
On-Policy Nature of SARSA
SARSA is on-policy because it evaluates and improves the same policy that is used to select actions. The next action At+1 is chosen according to the current policy (e.g., ε-greedy), and this same action is used in the TD update. This contrasts with Q-learning, which uses the maximum Q-value of the next state, irrespective of the current policy.
For an ε-greedy policy, SARSA's update can be written as:
Convergence Properties
Under standard stochastic approximation conditions (e.g., Robbins-Monro conditions for the learning rate), SARSA converges to the optimal action-value function Q* if the policy is greedy in the limit (GLIE). However, if the policy remains exploratory (e.g., fixed ε > 0), SARSA converges to a near-optimal policy that accounts for exploration penalties.
Algorithm Pseudocode
Initialize Q(s, a) arbitrarily
Repeat for each episode:
Initialize S
Choose A from S using policy derived from Q (e.g., ε-greedy)
Repeat for each step of episode:
Take action A, observe R, S'
Choose A' from S' using policy derived from Q
Q(S, A) ← Q(S, A) + α [R + γ Q(S', A') - Q(S, A)]
S ← S', A ← A'
until S is terminal
Practical Considerations
SARSA tends to be more conservative than Q-learning in stochastic environments because it accounts for the exploration inherent in the policy. This makes it suitable for applications where safety is critical, such as robotics or autonomous driving, where overly optimistic actions could lead to catastrophic outcomes.
One limitation is that SARSA can be slower to converge in deterministic environments compared to Q-learning, as it must account for the exploration noise in its updates. However, in highly stochastic environments, SARSA often outperforms Q-learning by learning more robust policies.
Extensions and Variants
Several variants of SARSA exist to improve its performance:
- Expected SARSA: Uses the expected value of the next state-action pair instead of sampling, reducing variance.
- SARSA(λ): Incorporates eligibility traces to speed up learning by propagating TD errors backward through visited states.
- Double SARSA: Uses two Q-functions to mitigate the overestimation bias common in TD methods.
Q-Learning: Off-Policy TD Control
Q-Learning represents a foundational algorithm in reinforcement learning that enables an agent to learn optimal policies without requiring a model of the environment. As an off-policy temporal difference (TD) control method, it learns the action-value function Q(s,a) directly, independent of the policy being followed.
Mathematical Formulation
The Q-Learning update rule combines aspects of value iteration and TD learning. The algorithm maintains estimates of state-action values Q(s,a) and updates them using the following rule:
Where:
- α represents the learning rate (0 < α ≤ 1)
- γ is the discount factor (0 ≤ γ ≤ 1)
- The term Rt+1 + γ maxa Q(St+1, a) constitutes the TD target
- The difference between the target and current estimate forms the TD error
Off-Policy Nature
Q-Learning's off-policy characteristic stems from its update rule, which evaluates the greedy policy while following an exploratory behavior policy. This separation allows for:
- Flexibility in exploration strategies (ε-greedy, Boltzmann, etc.)
- Convergence to optimal policy while maintaining exploration
- Efficient reuse of experience collected under different policies
Convergence Properties
Under standard stochastic approximation conditions, Q-Learning converges to the optimal action-value function Q* with probability 1, provided:
- All state-action pairs are visited infinitely often
- The learning rate α satisfies the Robbins-Monro conditions:
$$ \sum_{t=1}^\infty \alpha_t = \infty \quad \text{and} \quad \sum_{t=1}^\infty \alpha_t^2 < \infty $$
- The environment is finite Markov Decision Process (MDP)
Practical Implementation Considerations
Effective implementation requires addressing several practical challenges:
Exploration-Exploitation Tradeoff
The ε-greedy policy commonly serves as the behavior policy, selecting random actions with probability ε and greedy actions otherwise. Annealing ε from 1 to near 0 often yields better empirical results.
Learning Rate Scheduling
Common approaches include:
- Linear decay: αt = α0(1 - t/T)
- Inverse time: αt = α0/(1 + βt)
- Sample-average: αt = 1/n(s,a)
Function Approximation
For large state spaces, Q-values are typically approximated using:
- Linear function approximation: Q(s,a) ≈ θTφ(s,a)
- Neural networks (Deep Q-Networks)
- Tile coding or radial basis functions
Algorithm Pseudocode
Initialize Q(s,a) arbitrarily
Repeat (for each episode):
Initialize S
Repeat (for each step of episode):
Choose A from S using policy derived from Q (e.g., ε-greedy)
Take action A, observe R, S'
Q(S,A) ← Q(S,A) + α[R + γ max_a Q(S',a) - Q(S,A)]
S ← S'
until S is terminal
Applications and Variants
Q-Learning has powered numerous real-world applications and inspired several important variants:
- Deep Q-Networks (DQN): Combines Q-Learning with deep neural networks for high-dimensional state spaces
- Double Q-Learning: Addresses maximization bias by maintaining two separate estimators
- Expected SARSA: Uses the expected value of the next state-action pair rather than the maximum

4. Deep Q-Networks (DQN)
Deep Q-Networks (DQN)
Deep Q-Networks (DQN) combine Q-learning with deep neural networks to approximate the Q-value function in high-dimensional state spaces. Traditional Q-learning relies on tabular methods, which become infeasible when the state space grows exponentially. DQN addresses this by using a neural network to estimate Q-values, enabling generalization across similar states.
Q-Learning Recap
In Q-learning, the agent learns an action-value function Q(s, a), representing the expected cumulative reward of taking action a in state s. The Bellman equation describes the optimal Q-value:
where r is the immediate reward, γ is the discount factor, and s' is the next state. Tabular Q-learning updates Q-values iteratively, but this approach fails in large or continuous state spaces.
Neural Network Approximation
DQN replaces the Q-table with a neural network Q(s, a; θ), where θ represents the network parameters. The network minimizes the mean squared error (MSE) between predicted Q-values and target Q-values derived from the Bellman equation:
Here, θ⁻ denotes the parameters of a target network, which stabilizes training by providing consistent targets. The expectation is taken over transitions (s, a, r, s') sampled from a replay buffer 𝒟.
Key Innovations in DQN
DQN introduced two critical techniques to stabilize training:
- Experience Replay: Transitions are stored in a buffer and sampled randomly during training, breaking temporal correlations and improving data efficiency.
- Target Network: A separate network with frozen parameters provides Q-value targets, reducing harmful feedback loops caused by rapidly changing Q-estimates.
Algorithmic Steps
The DQN algorithm proceeds as follows:
- Initialize Q-network Q(s, a; θ) and target network Q(s, a; θ⁻) with the same weights.
- Store transitions (s, a, r, s') in replay buffer 𝒟.
- Sample a mini-batch of transitions from 𝒟.
- Compute target Q-values using the target network: y = r + γ maxₐ' Q(s', a'; θ⁻).
- Update Q-network by minimizing MSE loss between Q(s, a; θ) and y.
- Periodically update the target network: θ⁻ ← θ.
Practical Considerations
DQN performance depends on hyperparameters such as:
- Replay Buffer Size: Larger buffers improve stability but increase memory usage.
- Target Update Frequency: Infrequent updates prevent divergence but may slow learning.
- Exploration Strategy: ε-greedy policies balance exploration and exploitation, with ε typically annealed over time.
Variants like Double DQN and Dueling DQN further improve performance by addressing overestimation bias and decoupling value and advantage estimation, respectively.
Implementation Example
Below is a PyTorch implementation of a DQN agent:
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from collections import deque
import random
class DQN(nn.Module):
def __init__(self, state_dim, action_dim):
super(DQN, self).__init__()
self.fc1 = nn.Linear(state_dim, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, action_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
return self.fc3(x)
class ReplayBuffer:
def __init__(self, capacity):
self.buffer = deque(maxlen=capacity)
def push(self, state, action, reward, next_state, done):
self.buffer.append((state, action, reward, next_state, done))
def sample(self, batch_size):
return random.sample(self.buffer, batch_size)
def __len__(self):
return len(self.buffer)
class DQNAgent:
def __init__(self, state_dim, action_dim, lr=1e-3, gamma=0.99, buffer_size=10000):
self.q_net = DQN(state_dim, action_dim)
self.target_net = DQN(state_dim, action_dim)
self.target_net.load_state_dict(self.q_net.state_dict())
self.optimizer = optim.Adam(self.q_net.parameters(), lr=lr)
self.buffer = ReplayBuffer(buffer_size)
self.gamma = gamma
self.action_dim = action_dim
def update(self, batch_size):
if len(self.buffer) < batch_size:
return
batch = self.buffer.sample(batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.FloatTensor(np.array(states))
actions = torch.LongTensor(np.array(actions))
rewards = torch.FloatTensor(np.array(rewards))
next_states = torch.FloatTensor(np.array(next_states))
dones = torch.FloatTensor(np.array(dones))
current_q = self.q_net(states).gather(1, actions.unsqueeze(1))
next_q = self.target_net(next_states).max(1)[0].detach()
target_q = rewards + (1 - dones) * self.gamma * next_q
loss = nn.MSELoss()(current_q.squeeze(), target_q)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def update_target(self):
self.target_net.load_state_dict(self.q_net.state_dict())

4.2 Policy Gradient Methods
Policy gradient methods directly optimize the policy πθ(a|s) by adjusting its parameters θ to maximize expected return. Unlike value-based methods, which learn a value function and derive a policy indirectly, policy gradients operate in the policy space, making them particularly effective for high-dimensional or continuous action spaces. The core idea is to compute the gradient of the expected reward with respect to the policy parameters and perform gradient ascent.
Derivation of the Policy Gradient Theorem
The Policy Gradient Theorem provides the foundation for these methods by expressing the gradient of the objective function J(θ)—the expected return under policy πθ—as an expectation over trajectories. The theorem states:
Here, τ denotes a trajectory (s0, a0, r0, ..., sT), and Qπθ(st, at) is the state-action value function. The log-derivative trick is applied to rewrite the gradient in terms of the policy's likelihood ratios.
Variance Reduction Techniques
While the policy gradient estimator is unbiased, it often suffers from high variance. Two common techniques to mitigate this are:
- Baseline Subtraction: Replace Qπθ(st, at) with the advantage function Aπθ(st, at) = Qπθ(st, at) - Vπθ(st), where Vπθ(st) is the state-value function. This reduces variance without introducing bias.
- Actor-Critic Methods: Combine policy gradients with a learned value function (critic) to approximate Qπθ or Aπθ, improving sample efficiency.
Practical Algorithms
Several algorithms build on the policy gradient framework:
- REINFORCE: A Monte Carlo method that estimates the gradient using full episode returns.
- Proximal Policy Optimization (PPO): Constrains policy updates to prevent large deviations, enhancing stability.
- Trust Region Policy Optimization (TRPO): Uses a trust-region constraint to ensure monotonic policy improvement.
Example: REINFORCE Algorithm
The REINFORCE algorithm updates the policy parameters using:
where Gt is the return from time step t.
Applications and Limitations
Policy gradient methods excel in robotics, game playing, and other domains requiring continuous control. However, they face challenges such as sample inefficiency, local optima, and sensitivity to hyperparameters. Recent advances like distributed training and meta-learning aim to address these issues.
4.3 Actor-Critic Architectures
Actor-Critic methods combine the strengths of policy-based and value-based reinforcement learning, addressing the high variance of pure policy gradients while maintaining the flexibility of direct policy optimization. The architecture consists of two components: the actor, which updates the policy π(a|s; θ), and the critic, which estimates the value function V(s; w) or Q(s, a; w).
Mathematical Foundation
The actor’s policy gradient is adjusted using the critic’s value estimate as a baseline, reducing variance without introducing bias. The gradient of the expected return J(θ) is:
where A(s, a; w) is the advantage function, computed as Q(s, a; w) − V(s; w) or approximated via temporal difference (TD) error:
The critic minimizes the mean squared error (MSE) between its value estimate and the target (e.g., TD target or Monte Carlo return). For V(s; w), the loss is:
Architectural Variants
Synchronous vs. Asynchronous Updates: In synchronous Actor-Critic (e.g., A2C), the actor and critic share gradients after each episode. Asynchronous methods (e.g., A3C) parallelize agents with separate environments, updating a global model asynchronously.
Deterministic Policy Gradients (DPG): For continuous action spaces, the actor outputs deterministic actions μ(s; θ), and the critic estimates Q(s, a; w). The gradient becomes:
Proximal Policy Optimization (PPO): A popular variant that clips policy updates to avoid large deviations, optimizing:
Practical Implementation
Modern implementations often use deep neural networks for both actor and critic, sharing lower-layer features to improve sample efficiency. Key design choices include:
- Shared vs. Separate Networks: Shared feature extractors reduce computational overhead but may require careful tuning to balance actor-critic updates.
- Advantage Estimation: Generalized Advantage Estimation (GAE) combines multi-step TD errors with an exponential weighting factor λ:
Case Study: In robotics, Actor-Critic methods enable precise control policies by leveraging the critic’s low-variance gradient estimates. For example, DDPG (Deep Deterministic Policy Gradient) has been used to train robotic arms with continuous joint control.

5. Multi-Agent Reinforcement Learning
Multi-Agent Reinforcement Learning
Multi-Agent Reinforcement Learning (MARL) extends traditional single-agent RL to environments where multiple agents interact, learn, and adapt simultaneously. Unlike single-agent settings, MARL introduces complexities such as non-stationarity, partial observability, and emergent coordination dynamics. The joint action space grows exponentially with the number of agents, making centralized training often infeasible.
Mathematical Formulation
In MARL, the environment is modeled as a stochastic game (also called a Markov game), defined by the tuple (N, S, {Ai}, P, {Ri}, γ), where:
- N: Finite set of agents
- S: State space
- {Ai}: Action space for agent i
- P: Transition function P(s' | s, a1, ..., aN)
- {Ri}: Reward function for agent i, Ri(s, a1, ..., aN, s')
- γ: Discount factor
The Q-function for agent i in a Markov game extends the Bellman equation:
where a-i denotes the joint actions of all agents except i.
Key Challenges
Non-Stationarity: From the perspective of any single agent, the environment appears non-stationary because other agents are simultaneously learning and adapting their policies. This violates the Markov assumption crucial for convergence guarantees in single-agent RL.
Credit Assignment: In cooperative settings, determining each agent's contribution to the team's success becomes non-trivial. Global rewards provide sparse feedback, requiring specialized methods like difference rewards or counterfactual baselines.
Scalability: The joint action space dimensionality grows as O(|A|N), making exhaustive exploration impractical. Recent approaches use factorized value functions or attention mechanisms to mitigate this curse of dimensionality.
Algorithmic Approaches
Independent Q-Learning (IQL)
The simplest MARL approach treats other agents as part of the environment. Each agent independently learns its Q-function:
While computationally efficient, IQL often fails to converge due to the non-stationarity problem. Empirical results show it can work in practice with careful reward shaping and low learning rates.
Centralized Training with Decentralized Execution (CTDE)
Modern MARL algorithms like MADDPG and QMIX adopt the CTDE paradigm. During training, agents have access to global information (e.g., other agents' observations or actions), but policies execute locally during deployment. The centralized critic for agent i in MADDPG is:
where ϕ represents the centralized critic's parameters. Policy gradients are computed as:
QMIX extends this by enforcing monotonicity between centralized and decentralized value functions through a mixing network that satisfies:
Equilibrium Concepts
MARL solutions often converge to Nash equilibria rather than optimal policies. In a Nash equilibrium, no agent can improve its expected return by unilaterally changing its policy:
Recent work explores correlated equilibria and learning in Stackelberg games for hierarchical multi-agent systems. Evolutionary game theory provides tools to analyze population dynamics in large-scale MARL.
Applications
MARL has demonstrated success in autonomous driving coordination, where agents must negotiate merging lanes while avoiding collisions. In robotics swarms, MARL enables emergent flocking behaviors without explicit communication protocols. The StarCraft Multi-Agent Challenge (SMAC) benchmark has become a standard testbed for cooperative MARL algorithms, requiring precise unit micromanagement and tactical coordination.
Emerging applications include:
- Financial market simulation with adaptive traders
- Smart grid energy distribution
- Multi-robot warehouse optimization
- Adversarial network security

Hierarchical Reinforcement Learning
Hierarchical Reinforcement Learning (HRL) decomposes complex tasks into manageable subtasks, enabling more efficient exploration and credit assignment in long-horizon problems. By introducing temporal abstraction, HRL frameworks allow agents to operate at multiple levels of granularity, reducing the curse of dimensionality inherent in flat RL approaches.
Options Framework
The options framework formalizes temporally extended actions as options, defined by a tuple (I, π, β), where:
- I is the initiation set of states where the option can be invoked,
- π is the intra-option policy mapping states to lower-level actions,
- β is the termination condition specifying the probability of the option ending in a given state.
Here, QΩ(s, ω) represents the value of executing option ω in state s, with γ as the discount factor. The option-value function generalizes the standard action-value function to temporal abstractions.
MAXQ Value Function Decomposition
The MAXQ method decomposes the value function hierarchically, expressing the value of a parent task as the sum of its child task values. For a task M with subtasks m1, ..., mn, the projected value function is:
where Vπi(s) is the value of subtask mi and Cπ(s, a) is the completion function representing the expected return after completing action a in state s.
Feudal Reinforcement Learning
Inspired by hierarchical governance, feudal RL employs a manager-worker architecture. The manager operates at a higher temporal resolution, setting subgoals for the worker, which executes primitive actions. The manager's policy is trained to maximize the intrinsic reward:
where 𝒢 is the set of subgoal states, d(·,·) is a distance metric, and c scales the penalty for deviating from the current subgoal gt.
Recent Advances: HRL with Neural Networks
Modern HRL combines hierarchical decomposition with deep learning. For instance, the HIRO algorithm trains a higher-level policy that operates on a slower timescale, with its actions serving as goals for the lower-level policy. The lower-level policy is rewarded for achieving these goals:
where k is the temporal abstraction interval. This approach has demonstrated success in complex environments like Ant Maze and Montezuma's Revenge.

5.3 Reward Shaping and Sparse Rewards
Reward shaping is a critical technique in reinforcement learning (RL) designed to address the challenge of sparse rewards, where the agent receives feedback only upon achieving rare milestones. In sparse reward environments, the lack of frequent feedback makes learning inefficient, as the agent struggles to associate actions with long-term outcomes. Reward shaping introduces intermediate rewards to guide the agent toward optimal behavior without altering the underlying goal.
Formalizing Reward Shaping
The modified reward function R' combines the original sparse reward R with a shaping term F:
where F(s, s') is a potential-based shaping function ensuring policy invariance. Ng et al. (1999) proved that if F derives from a potential function Φ such that:
then the optimal policy remains unchanged. Here, γ is the discount factor. This formulation prevents the agent from exploiting shaping rewards for unintended behaviors.
Sparse Reward Challenges
In environments like robotic manipulation or Montezuma’s Revenge, sparse rewards lead to:
- High exploration variance: Random exploration rarely stumbles upon meaningful states.
- Credit assignment difficulty: The agent cannot discern which actions contributed to delayed rewards.
- Training instability: Rare positive rewards cause aggressive policy updates that degrade performance.
Practical Applications of Reward Shaping
In AlphaGo, shaping rewards guided the agent toward capturing stones, while the ultimate reward remained winning the game. Similarly, in autonomous driving, intermediate rewards for lane-keeping and collision avoidance accelerate learning before the sparse "successful trip" reward is achieved.
Advanced Techniques
Recent methods combine reward shaping with intrinsic motivation:
- Curiosity-driven exploration: Adds bonuses for visiting novel states (Pathak et al., 2017).
- Hindsight Experience Replay (HER): Relabels failed trajectories with artificial goals (Andrychowicz et al., 2017).
- Density-based rewards: Uses state visitation statistics to shape exploration (Bellemare et al., 2016).
These approaches mitigate sparse rewards without manual engineering of shaping functions. For example, HER reformulates the reward function during training as:
where g' is a substitute goal sampled from the episode, and f(s) maps states to achieved goals.
6. Foundational Papers and Books
6.1 Foundational Papers and Books
- PDF Reinforcement Learning - Lecture Notes - Sayantan Auddy — 1.5 Elements of Reinforcement Learning Before diving into the formal description of the reinforcement learning setup, let us un-derstand the meaning of some commonly used terms, as listed in Table 1. Table 1: Informal description of common RL terms. Term Description Agent The arti cial entity that is being trained to perform a task by learning from
- Book: Foundations of Deep Reinforcement Learning | SLM Lab — A summary of the book is provided below: The Contemporary Introduction to Deep Reinforcement Learning that Combines Theory and Practice Deep reinforcement learning (deep RL) combines deep learning and reinforcement learning, in which artificial agents learn to solve sequential decision-making problems. In the past decade deep RL has achieved remarkable results on a range of problems, from ...
- An Introduction to Reinforcement Learning: Fundamental Concepts and ... — An overview of RL is provided in this paper, which discusses its core concepts, methodologies, recent trends, and resources for learning. We provide a detailed explanation of key components of RL such as states, actions, policies, and reward signals so that the reader can build a foundational understanding.
- PDF Fundamentals of Reinforcement Learning - Springer — system that involves Reinforcement Learning. Concepts such as agent, environ-ment, actions, rewards, policies, and value function are discussed. Examples and analogies are presented to help illustrate each of these concepts, from structuring problems starting from the Markov Chain through Watkins and Dayan's proposal
- (PDF) A Technical Introduction to Reinforcement Learning - ResearchGate — This white paper provides a technical introduction to Reinforcement Learning, explaining its core concepts and mathematical foundations as well as basic Reinforcement Learning algorithms.
- PDF Foundations of Deep Reinforcement Learning: Theory and Practice in Python — "This book provides an accessible introduction to deep reinforcement learning covering the mathematical concepts behind popular algorithms as well as their practical implementation. I think the book will be a valuable resource for anyone looking to apply deep reinforcement learning in practice." —VolodymyrMnih,leaddeveloperofDQN
- PDF Reinforcement Learning: An Introduction - Stanford University — a learning system that wants something, that adapts its behavior in order to maximize a special signal from its environment. This was the idea of a \he-donistic" learning system, or, as we would say now, the idea of reinforcement learning. Like others, we had a sense that reinforcement learning had been thor-
- An Introduction to Reinforcement Learning: Fundamental Concepts and ... — Reinforcement Learning (RL) is a branch of Artificial Intelligence (AI) which focuses on training agents to make decisions by interacting with their environment to maximize cumulative rewards.
- Fundamentals of Reinforcement Learning - amazon.com — 1.0 out of 5 stars Extremely poor book on reinforcement learning Reviewed in the United States on September 8, 2024 You cannot give RL fundamentals in 103 pages!
- Introduction to Reinforcement Learning | SpringerLink — Now, let us take a closer look at the relationship between the agent and the environment as depicted in Fig. 2.1.At an arbitrary time step, t, the agent first observes the current state of the environment, S t, and the corresponding reward value, R t.The agent then decides what to do next based on the state and reward information.
6.2 Online Courses and Tutorials
- Reinforcement Learning Tutorial: Semi-gradient n-step Sarsa and Sarsa ... — Reinforcement Learning Tutorial: Semi-gradient n-step Sarsa and Sarsa($$\lambda$$) Theory and Implementation. Reinforcement Learning (RL) is an exciting area of A.I that offers something entirely different to supervised or unsupervised techniques. ... Of course we also haven't covered Deep Learning RL methods (such as Deep Q-Learning). However ...
- An Introduction to Reinforcement Learning: Fundamental Concepts and ... — Reinforcement Learning (RL) is a branch of Artificial Intelligence (AI) which focuses on training agents to make decisions by interacting with their environment to maximize cumulative rewards. An overview of RL is provided in this paper, which discusses its core concepts, methodologies, recent trends, and resources for learning.
- PDF The Path Forward: A Primer for Reinforcement Learning - Stanford University — 1 Wisdom from Richard Sutton 6 2 Introduction to Reinforcement Learning 7 ... Also important was the use of learning by self play to learn a value function (as it was in many other games and even in chess, although learning ... together with learning on huge training sets,
- Introduction to reinforcement learning and control theory - DTU — This page contains material and information related to the spring 2025, version of the course Introduction to reinforcement learning and control, offered at DTU.. If you are thinking about taking the course you can read more about the course here or look at the Pre-requisites.If you are enrolled and just starting out, you should begin with the Installation.
- Decision Making and Reinforcement Learning | Coursera — This course is an introduction to sequential decision making and reinforcement learning. We start with a discussion of utility theory to learn how preferences can be represented and modeled for decision making. We first model simple decision problems as multi-armed bandit problems in and discuss several approaches to evaluate feedback.
- PDF Reinforcement Learning - Lecture Notes - Sayantan Auddy — Reinforcement Learning (RL) is an area of machine learning in which the objective is ... While the agent aims to learn how to map observations (states) to actions, there is no teacher which provides the correct actions during training. Instead, a scalar ... Several of the concepts in reinforcement learning have parallels in neuroscience, for ...
- Reinforcement Learning, Part 1: Introduction and Main Concepts — Introduction. Reinforcement learning is a special domain in machine learning that differs a lot from the classic methods used in supervised or unsupervised learning.. The ultimate objective consists of developing a so-called agent that will perform optimal actions in environments. From the start, the agent usually performs very poorly but as time goes on, it adapts its strategy from the trial ...
- CS/Stat 184 (0): Introduction to Reinforcement Learning — Reinforcement Learning (RL) is a general framework that can capture the interactive learning setting and has been used to design intelligent agents that achieve high-level performance in challenging applications such as Go, computer games, robotic manipulation, health care, and education. ... will have a programming component to give students ...
- Reinforcement Learning and Decision Making tutorials explained at an ... — If you'd like to access a bash session of a running container do: docker ps # will show you currently running containers -- note the id of the container you are trying to access docker exec --user root -it c3fbc82f1b49 /bin/bash # in this case c3fbc82f1b49 is the id If you'd like to start a new container instance straight into bash (without running Jupyter or TensorBoard)
- (PDF) A Technical Introduction to Reinforcement Learning - ResearchGate — Reinforcement Learning has emerged as an important area within machine learning, driven by its potential to solve complex, sequential decision-making problems . This white paper provides a
6.3 Open-Source Libraries and Tools
- Machine Learning and Deep Learning frameworks and libraries for large ... — While the number of Machine Learning algorithms is extensive and growing, their implementations through frameworks and libraries is also extensive and growing too. The software development in this field is fast paced with a large number of open-source software coming from the academy, industry, start-ups or wider open-source communities.
- Applied Deep Learning Book (Tools, Techniques & Implementation) — 253 Fig. 11.1 High-level reinforcement learning concept ... • Pandas - is a Python library that provides tools for data manipulation and analysis. • NumPy - is a Python library for multi-dimensional arrays and matrices. ... "From Server Room to Living Room: How open source and TiVo became a perfect match," Queue, vol. 1 ...
- D2L - Dive into Deep Learning — Dive into Deep Learning 1.0.3 ... — Follow D2L's open-source project for the latest updates. [Dec 2022] JAX implementation is available! New topics of reinforcement learning, Gaussian processes, and ... , code, text, and discussions, where concepts and techniques are illustrated and implemented with experiments on real data sets. Active community support.
- Ray is an AI compute engine. Ray consists of a core ... - GitHub — Ray consists of a core distributed runtime and a set of AI libraries for simplifying ML compute: Learn more about Ray AI Libraries: Data: Scalable Datasets for ML; Train: Distributed Training; Tune: Scalable Hyperparameter Tuning; RLlib: Scalable Reinforcement Learning; Serve: Scalable and Programmable Serving; Or more about Ray Core and its ...
- RLlib: Industry-Grade, Scalable Reinforcement Learning — Ray 2.46.0 — RLlib is an open source library for reinforcement learning (RL), offering support for production-level, highly scalable, and fault-tolerant RL workloads, while maintaining simple and unified APIs for a large variety of industry applications.. Whether training policies in a multi-agent setup, from historic offline data, or using externally connected simulators, RLlib offers simple solutions for ...
- PDF Scalable Reinforcement Learning Systems and their Applications — open source library for scalable reinforcement learning. We investigate the applications of RL and ML for improving systems, speci cally the examples of improving the speed of network packet classi ers and database cardinality estimators.
- 15 Open Source Library Software and Applications - INFLIBNET Centre — 4.1.1 Koha - Koha is a full featured open source library management system and it was initially developed by Harowhenua Library Trust, New Zealand in 2000. Now the project has grown as one of the popular Open Source Library management system by large group of volunteers from various parts of the world.
- Cognitive Computing: Concepts, Architectures, Systems, and Applications ... — Cognitive science is an interdisciplinary approach to the study of human and animal cognition (Frankish and Ramsey, 2012, Friedenberg and Silverman, 2015). Abrahamsen and Bechtel (2012) provide an exposition and core themes of cognitive science. Cognitive computing is an emerging field ushered in by the synergistic confluence of cognitive science, data science, and an array of computing ...
- Overview of AI Libraries in Java - Baeldung — I built the security material as two full courses - Core and OAuth, ... Deeplearning4j is a deep learning library for the JVM, and it also provides an API for neural network creation. 4. Natural Language Processing ... Deep Java Library is an open-source library developed by AWS Labs. It provides an intuitive, framework-independent Java API for ...
- Deep Reinforcement Learning In Action [PDF] [6ppasj45qt40] - E-book library — We trained it to produce accurate estimates of the expected reward for taking an action given a state. Our policy function was the softmax function over the output of the neural network. We've covered many of the foundational concepts in reinforcement learning just by using n-armed and contextual bandits as examples.








