Skip to content
AI360Xpert
Beta

Basic Concepts in Reinforcement Learning

Reinforcement learning is trial-and-error learning where an agent discovers how to act in an environment by receiving rewards and aiming to maximize cumulative gain over time.

The reinforcement learning loop connects five core pillars: state observation, policy action, environment transition, reward feedback, and cumulative return optimization.
The reinforcement learning loop connects five core pillars: state observation, policy action, environment transition, reward feedback, and cumulative return optimization.

Why Does This Exist?

In supervised learning, an external supervisor gives an explicit ground-truth label for every input. The model is told immediately what output it should have produced. In unsupervised learning, an algorithm searches for latent structure without any task feedback or external score.

Real-world autonomous intelligence does not fit either regime. When a robotic arm learns manipulation, an autonomous vehicle navigates rush-hour traffic, or an agent plays chess, there is no supervisor standing by to score every micro-action at step 37 of a thousand-step episode. The agent only receives evaluative feedback: occasional positive or negative rewards indicating whether intermediate states and final outcomes were beneficial.

Without the formal framework of Reinforcement Learning (RL), learning by trial and error breaks down in three critical ways:

  1. Delayed credit assignment: An action taken early in an episode may produce consequences dozens or hundreds of steps later. Naive optimization cannot tell which past decision caused a delayed success or failure.
  2. Distributional shift through action: In static machine learning, the dataset is fixed. In sequential decision-making, every action taken alters the future distribution of states the agent visits. A single mistake moves the agent into unfamiliar regions of the state space.
  3. Evaluative vs. instructive feedback: Evaluative feedback tells an agent how well it performed, but not what the optimal action was. The agent must actively explore alternative actions to discover superior strategies.

Reinforcement learning formalizes this interaction into a rigorous mathematical loop where agents learn goal-directed behavior by maximizing long-term cumulative reward.

Think of It Like This

Anatomy of a board game championship

Think of reinforcement learning as mastering a high-stakes board game:

  • State (StS_t): The exact arrangement of pieces on the board at your turn. It captures everything you need to know about the current situation to decide your next move.
  • Action (AtA_t): Any legal move you can play from the current board position.
  • Policy (π\pi): Your personal playbook or strategy—a systematic rulebook that dictates which move you select given any board configuration.
  • Environment Dynamics / Transition (PP): The game rules and your opponent's reaction. Once you move a piece, the board updates according to the rules and your opponent responds, producing the new board state.
  • Reward (RtR_t): Immediate points awarded or lost (e.g., capturing an opponent piece awards +2+2; losing a piece costs −1-1).
  • Return (GtG_t): Your total score across the entire game, where points scored soon are valued more predictably than hypothetical captures far into the future.
  • Where the analogy stops: In a board game, turns are discrete, the entire board is usually visible, and rules are deterministic. In real-world reinforcement learning, states can be noisy continuous sensor feeds, transitions are often stochastic with unknown physical dynamics, and tasks may run infinitely without rounds or turns.

How It Actually Works

The Five Pillars and the Agent-Environment Loop

At each discrete time step t=0,1,2,…t = 0, 1, 2, \dots, the interaction between the agent and the environment proceeds through five interconnected pillars:

PillarSymbolFormal DefinitionRole in the RL Loop
StateSt∈SS_t \in \mathcal{S}Complete description of the environment at step ttSensory representation observed by the agent
ActionAt∈A(St)A_t \in \mathcal{A}(S_t)Choice selected from available action space A\mathcal{A}Decision emitted by the agent to influence the world
TransitionP(s′,r∣s,a)P(s', r \mid s, a)Pr⁡(St+1=s′,Rt+1=r∣St=s,At=a)\Pr(S_{t+1}=s', R_{t+1}=r \mid S_t=s, A_t=a)World dynamics governing state evolution
RewardRt+1∈RR_{t+1} \in \mathbb{R}Scalar feedback signal emitted by the environmentImmediate evaluative score for the transition
Policyπ(a∣s)\pi(a \mid s)Pr⁡(At=a∣St=s)\Pr(A_t = a \mid S_t = s) or a=μ(s)a = \mu(s)Decision function mapping states to actions

The cycle repeats indefinitely or until a terminal state is reached:

  1. The agent observes the current state St∈SS_t \in \mathcal{S}.
  2. The agent selects an action At∼π(⋅∣St)A_t \sim \pi(\cdot \mid S_t) according to its policy π\pi.
  3. The environment processes AtA_t, transitions to a new state St+1∼P(⋅∣St,At)S_{t+1} \sim P(\cdot \mid S_t, A_t), and emits a scalar reward Rt+1R_{t+1}.
  4. The agent receives St+1S_{t+1} and Rt+1R_{t+1}, updating its internal policy or value estimates.

Trajectories, Returns, and the Discount Factor

A sequence of interactions produces an experience trajectory τ\tau:

τ=(S0,A0,R1,S1,A1,R2,…,ST)\tau = (S_0, A_0, R_1, S_1, A_1, R_2, \dots, S_T)

Tasks fall into two primary structures:

  • Episodic Tasks: Interaction naturally breaks into distinct episodes that terminate at time step TT upon reaching an absorbing terminal state (e.g., checkmate, game over, reaching a maze exit).
  • Continuing Tasks: Interaction proceeds infinitely without termination (T=∞T = \infty), such as an automated thermostat, industrial process control, or continuous inventory management.

To evaluate an agent's performance, we do not optimize isolated immediate rewards. Instead, we optimize the cumulative return GtG_t, defined from time step tt onward with a discount factor γ∈[0,1)\gamma \in [0, 1):

Gt=∑k=0∞γkRt+k+1=Rt+1+γRt+2+γ2Rt+3+…G_t = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1} = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots

This definition yields the fundamental recursive relationship used throughout reinforcement learning:

Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}

The discount factor γ\gamma plays two vital roles:

  • Mathematical Convergence: When tasks are continuing (T=∞T = \infty), summing unweighted rewards bounded by Rmax⁡R_{\max} would diverge to infinity. When γ<1\gamma < 1, the geometric series bounds the maximum possible return: Gt≤∑k=0∞γkRmax⁡=Rmax⁡1−γG_t \le \sum_{k=0}^{\infty} \gamma^k R_{\max} = \frac{R_{\max}}{1 - \gamma}
  • Behavioral Horizon: The discount factor tunes the agent's effective planning horizon Heff≈11−γH_{\text{eff}} \approx \frac{1}{1 - \gamma}. When γ=0\gamma = 0, the agent is purely myopic, maximizing only the immediate reward Rt+1R_{t+1}. As γ→1\gamma \to 1, the agent becomes farsighted, weighting distant consequences heavily.

Value Functions and the Optimization Target

Because future state transitions and policies can be stochastic, the return GtG_t is a random variable. An agent evaluates states using expected returns:

  • State-Value Function Vπ(s)V^\pi(s): The expected return starting from state ss under policy π\pi: Vπ(s)=Eπ[Gt∣St=s]V^\pi(s) = \mathbb{E}_\pi [G_t \mid S_t = s]
  • Action-Value Function Qπ(s,a)Q^\pi(s, a): The expected return of taking action aa in state ss and thereafter following π\pi: Qπ(s,a)=Eπ[Gt∣St=s,At=a]Q^\pi(s, a) = \mathbb{E}_\pi [G_t \mid S_t = s, A_t = a]

The overarching objective of reinforcement learning is to discover an optimal policy π∗\pi^* that maximizes the expected return from the start:

π∗=arg⁡max⁡πEτ∼π[G0]\pi^* = \arg\max_\pi \mathbb{E}_{\tau \sim \pi} [G_0]

Worked numerical example

Consider a 4-step episodic trajectory generated by an agent navigating an obstacle course:

τ=(S0,A0,R1=+2.0,S1,A1,R2=−1.0,S2,A2,R3=0.0,S3,A3,R4=+10.0,S4)\tau = (S_0, A_0, R_1=+2.0, S_1, A_1, R_2=-1.0, S_2, A_2, R_3=0.0, S_3, A_3, R_4=+10.0, S_4)

At step 4, the agent reaches the terminal goal state S4S_4. Because S4S_4 is terminal, no subsequent rewards exist, so G4=0.0G_4 = 0.0.

Let the discount factor be γ=0.9\gamma = 0.9. We compute the return GtG_t at each step by propagating backwards using Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}:

  1. Terminal step t=4t = 4: G4=0.0G_4 = 0.0
  2. Step t=3t = 3: Transition to terminal goal S4S_4 yielding reward R4=+10.0R_4 = +10.0: G3=R4+γG4=10.0+0.9×0.0=10.0G_3 = R_4 + \gamma G_4 = 10.0 + 0.9 \times 0.0 = 10.0
  3. Step t=2t = 2: Transition to intermediate state S3S_3 yielding reward R3=0.0R_3 = 0.0: G2=R3+γG3=0.0+0.9×10.0=9.0G_2 = R_3 + \gamma G_3 = 0.0 + 0.9 \times 10.0 = 9.0
  4. Step t=1t = 1: Step across rough terrain to S2S_2 yielding penalty R2=−1.0R_2 = -1.0: G1=R2+γG2=−1.0+0.9×9.0=−1.0+8.1=7.1G_1 = R_2 + \gamma G_2 = -1.0 + 0.9 \times 9.0 = -1.0 + 8.1 = 7.1
  5. Initial step t=0t = 0: Initial transition from S0S_0 to S1S_1 yielding reward R1=+2.0R_1 = +2.0: G0=R1+γG1=2.0+0.9×7.1=2.0+6.39=8.39G_0 = R_1 + \gamma G_1 = 2.0 + 0.9 \times 7.1 = 2.0 + 6.39 = 8.39

We verify G0G_0 by expanding the full power series directly:

G0=R1+γR2+γ2R3+γ3R4G_0 = R_1 + \gamma R_2 + \gamma^2 R_3 + \gamma^3 R_4 G0=2.0+0.9(−1.0)+(0.9)2(0.0)+(0.9)3(10.0)G_0 = 2.0 + 0.9(-1.0) + (0.9)^2(0.0) + (0.9)^3(10.0) G0=2.0−0.90+0.0+0.729×10.0=1.10+7.29=8.39G_0 = 2.0 - 0.90 + 0.0 + 0.729 \times 10.0 = 1.10 + 7.29 = 8.39

Comparing the return at t=0t=0 under different values of γ\gamma illustrates the impact of discounting:

  • γ=0.0\gamma = 0.0 (myopic): G0=2.00G_0 = 2.00 (ignores both the −1.0-1.0 penalty and the +10.0+10.0 goal)
  • γ=0.5\gamma = 0.5 (short-sighted): G0=2.0−0.5+0.0+1.25=2.75G_0 = 2.0 - 0.5 + 0.0 + 1.25 = 2.75
  • γ=0.9\gamma = 0.9 (farsighted): G0=8.39G_0 = 8.39
  • γ=1.0\gamma = 1.0 (undiscounted sum): G0=2.0−1.0+0.0+10.0=11.00G_0 = 2.0 - 1.0 + 0.0 + 10.0 = 11.00

Code

from dataclasses import dataclassfrom typing import List, Sequence
@dataclass(frozen=True)class TransitionStep:    state: str    action: str    reward: float    next_state: str
def compute_discounted_returns(    rewards: Sequence[float],    gamma: float) -> List[float]:    """Compute backwards cumulative discounted return G_t for each step.        Uses the recursive formulation: G_t = R_{t+1} + gamma * G_{t+1}.    Runs in O(N) time and O(N) auxiliary space.    """    if not (0.0 <= gamma <= 1.0):        raise ValueError(f"Gamma must be in [0.0, 1.0], got {gamma}")        n = len(rewards)    returns: List[float] = [0.0] * n    running_return = 0.0        # Backwards accumulation from terminal step T to step 0    for t in reversed(range(n)):        running_return = rewards[t] + gamma * running_return        returns[t] = running_return            return returns
# Sample episodic trajectory: 4 steps leading to a goal statetrajectory: List[TransitionStep] = [    TransitionStep(state="S0", action="East",  reward=2.0,  next_state="S1"),    TransitionStep(state="S1", action="South", reward=-1.0, next_state="S2"),    TransitionStep(state="S2", action="East",  reward=0.0,  next_state="S3"),    TransitionStep(state="S3", action="North", reward=10.0, next_state="S4_goal"),]
rewards = [step.reward for step in trajectory]gammas = [0.0, 0.5, 0.9, 1.0]
print("Step-by-step Discounted Returns G_t across Gammas:")header = f"{'Step':<6} | {'Reward':<8} | " + " | ".join([f"gamma={g:<4}" for g in gammas])print(header)print("-" * len(header))
all_returns = {g: compute_discounted_returns(rewards, g) for g in gammas}
for t, step in enumerate(trajectory):    ret_str = " | ".join([f"{all_returns[g][t]:<6.2f}" for g in gammas])    print(f"t={t:<4} | R_{t+1}={step.reward:<4.1f} | {ret_str}")

Expected output:

Step-by-step Discounted Returns G_t across Gammas:Step   | Reward   | gamma=0.0  | gamma=0.5  | gamma=0.9  | gamma=1.0 ---------------------------------------------------------------------t=0    | R_1=2.0  | 2.00   | 2.75   | 8.39   | 11.00 t=1    | R_2=-1.0 | -1.00  | 1.50   | 7.10   | 9.00  t=2    | R_3=0.0  | 0.00   | 5.00   | 9.00   | 10.00 t=3    | R_4=10.0 | 10.00  | 10.00  | 10.00  | 10.00 

Watch Out For

Confusing immediate reward with expected return

Failure mode: Designing an agent or choosing actions greedily based on immediate reward Rt+1R_{t+1} rather than cumulative return GtG_t or value function Q(s,a)Q(s, a).

Symptom: The agent exhibits severe myopic failure. It falls into obvious traps by grabbing small instant rewards (e.g., picking up an isolated coin in front of a pit), refuses to accept short-term costs necessary for long-term gains (e.g., refusing to pay an engine acceleration cost or sacrifice a chess piece), or circles repeatedly in loops of minor positive rewards.

Concrete fix: Never optimize individual step rewards in isolation. Formulate all policy decisions through value functions V(s)V(s) or Q(s,a)Q(s, a) that estimate the expectation of total discounted future return E[Gt]\mathbb{E}[G_t]. Always set the discount factor γ\gamma high enough to cover the task's natural credit assignment horizon (H≈11−γH \approx \frac{1}{1 - \gamma}).

Setting discount factor gamma = 1.0 in continuing tasks

Failure mode: Setting γ=1.0\gamma = 1.0 in continuing tasks where no terminal state exists.

Symptom: When episodes do not terminate, the cumulative return ∑t=0∞Rt\sum_{t=0}^\infty R_t diverges to +∞+\infty or −∞-\infty. Temporal difference errors explode, neural network value targets blow up to numerical overflow, and gradient descent destabilizes.

Concrete fix: For infinite-horizon continuing environments, strictly set γ∈[0,1)\gamma \in [0, 1) (commonly between 0.950.95 and 0.9990.999) so returns remain geometrically bounded, or reformulate the optimization objective using the average-reward MDP formulation.

The Quick Version

  • Reinforcement learning models sequential decision-making through an agent-environment interaction loop governed by States, Actions, and Rewards.
  • The policy π\pi determines the agent's behavior, while environment transition dynamics P(s′,r∣s,a)P(s', r \mid s, a) dictate physics, transitions, and feedback.
  • The core objective is maximizing expected discounted return Gt=∑k=0∞γkRt+k+1=Rt+1+γGt+1G_t = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1} = R_{t+1} + \gamma G_{t+1}, rather than picking greedy immediate rewards.
  • The discount factor γ∈[0,1)\gamma \in [0, 1) balances short-term survival against long-term planning, and guarantees finite returns in infinite-horizon continuing tasks.