Chapter 1: Introduction to Reinforcement Learning

WIA-AI-025 Reinforcement Learning Standard | ๐ŸŽฎ Learn by Interaction

1.1 What is Reinforcement Learning?

Reinforcement Learning (RL) is a branch of machine learning where an agent learns to make decisions by interacting with an environment. Unlike supervised learning, which relies on labeled examples, or unsupervised learning, which finds patterns in unlabeled data, reinforcement learning learns through trial and error, receiving feedback in the form of rewards or penalties.

Key Insight:

RL is about learning WHAT to doโ€”mapping situations to actionsโ€”to maximize a numerical reward signal. The learner is not told which actions to take but must discover which actions yield the most reward by trying them.

The reinforcement learning framework consists of three fundamental components:

The Agent-Environment Interface

At each time step t, the agent:

  1. Observes the current state sโ‚œ of the environment
  2. Selects and executes an action aโ‚œ
  3. Receives a reward rโ‚œโ‚Šโ‚
  4. Observes the new state sโ‚œโ‚Šโ‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Agent  โ”‚
โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜
     โ”‚ aโ‚œ (action)
     โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Environment โ”‚
โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
     โ”‚ sโ‚œโ‚Šโ‚, rโ‚œโ‚Šโ‚ (state, reward)
     โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Agent  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

1.2 The Reinforcement Learning Problem

The goal of reinforcement learning is to find an optimal policy ฯ€* that maximizes the expected cumulative reward over time. This is formalized as maximizing the expected return:

Gโ‚œ = Rโ‚œโ‚Šโ‚ + ฮณRโ‚œโ‚Šโ‚‚ + ฮณยฒRโ‚œโ‚Šโ‚ƒ + ... = ฮฃ ฮณแตRโ‚œโ‚Šโ‚–โ‚Šโ‚

where:
- Gโ‚œ is the return from time step t
- ฮณ is the discount factor (0 โ‰ค ฮณ โ‰ค 1)
- Rโ‚œ is the reward at time t

The Discount Factor ฮณ

The discount factor ฮณ determines the present value of future rewards:

Important:

The discount factor serves two purposes: (1) mathematically convenient for infinite-horizon problems, and (2) represents uncertainty about the futureโ€”rewards now are more certain than rewards far in the future.

1.3 Types of RL Problems

Episodic vs. Continuing Tasks

Episodic Tasks Continuing Tasks
Natural termination point No natural termination
Example: Chess game, maze navigation Example: Stock trading, process control
Episodes are independent Continuous interaction
Can use ฮณ = 1 within episode Must use ฮณ < 1 for convergence

Model-Based vs. Model-Free RL

Model-Based RL: The agent has access to (or learns) a model of the environment's dynamics p(s', r | s, a). This allows planning by simulating future trajectories.

// Model-Based: Plan ahead using the model
function plan(state, model, depth):
    best_action = null
    best_value = -infinity

    for action in possible_actions:
        value = 0
        for next_state, reward, prob in model.predict(state, action):
            value += prob * (reward + ฮณ * V(next_state))

        if value > best_value:
            best_value = value
            best_action = action

    return best_action

Model-Free RL: The agent learns directly from experience without building an explicit model. This is simpler but may require more samples.

// Model-Free: Learn Q-values directly from experience
function q_learning_update(s, a, r, s_next):
    Q[s][a] = Q[s][a] + ฮฑ * (r + ฮณ * max(Q[s_next]) - Q[s][a])

1.4 Exploration vs. Exploitation

One of the most fundamental dilemmas in RL is the exploration-exploitation tradeoff:

The Dilemma:

To obtain a lot of reward, you must prefer actions you've tried in the past and found effective (exploit). But to discover such actions, you must try actions you haven't selected before (explore).

Epsilon-Greedy Strategy

A simple but effective approach to balance exploration and exploitation:

function epsilon_greedy(Q, state, epsilon):
    if random() < epsilon:
        // Explore: choose random action
        return random_action()
    else:
        // Exploit: choose best known action
        return argmax(Q[state])

Other Exploration Strategies

Strategy Description Advantages
ฮต-greedy Random with probability ฮต Simple, widely used
Boltzmann Sample based on softmax probabilities Graded exploration
UCB Upper Confidence Bound Principled uncertainty-based
Thompson Sampling Bayesian probability matching Optimal in many cases

1.5 RL vs. Other ML Paradigms

Comparison with Supervised Learning

Aspect Supervised Learning Reinforcement Learning
Training Signal Correct labels provided Reward signal (evaluative)
Feedback Instructive (what's correct) Evaluative (how good)
Data Collection Static dataset Agent gathers data by interaction
Goal Minimize prediction error Maximize cumulative reward
Temporal Aspect Independent samples Sequential decision making

When to Use RL?

Reinforcement learning is particularly suitable when:

1.6 Real-World Applications

Game Playing

RL has achieved superhuman performance in games:

Robotics

// Robot Control with RL
class RobotAgent:
    def __init__(self):
        self.policy_network = PolicyNetwork()
        self.value_network = ValueNetwork()

    def act(self, observation):
        # Joint angles, velocities, tactile feedback
        state = self.process_sensors(observation)

        # Output: motor commands
        action = self.policy_network(state)
        return action

    def train(self, trajectory):
        # Learn from interaction with physical environment
        # Reward: task completion, energy efficiency, safety
        self.update_policy(trajectory)

Applications include:

Autonomous Vehicles

Self-driving cars use RL for:

Resource Management

Finance

// Trading Agent
class TradingAgent:
    def __init__(self):
        self.portfolio = Portfolio()
        self.q_function = QNetwork()

    def observe(self, market_state):
        # State: prices, volumes, technical indicators, news sentiment
        return {
            'prices': market_state.prices,
            'portfolio': self.portfolio.holdings,
            'indicators': self.compute_indicators(market_state)
        }

    def trade(self, state):
        # Actions: buy, sell, hold for each asset
        actions = self.q_function.get_best_actions(state)

        # Reward: PnL, Sharpe ratio, risk-adjusted returns
        return actions

Healthcare

1.7 Challenges in Reinforcement Learning

Sample Efficiency

RL often requires millions of interactions to learn effective policies. This is problematic when:

Solutions:
  • Transfer learning and meta-learning
  • Simulation-to-reality transfer
  • Offline RL from logged data
  • Model-based RL for planning

Credit Assignment Problem

When a reward is received, which past actions were responsible? This is challenging when:

Exploration in Large State Spaces

How can an agent efficiently explore when:

Stability and Convergence

Deep RL can be unstable because:

1.8 The RL Toolbox

Popular RL Libraries

// Stable-Baselines3 (PyTorch)
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env

# Create environment
env = make_vec_env('CartPole-v1', n_envs=4)

# Initialize agent
model = PPO('MlpPolicy', env, verbose=1)

# Train
model.learn(total_timesteps=100000)

# Evaluate
obs = env.reset()
for _ in range(1000):
    action, _ = model.predict(obs)
    obs, reward, done, info = env.step(action)

Environment Standards

// OpenAI Gym Interface
import gym

class CustomEnv(gym.Env):
    def __init__(self):
        self.action_space = gym.spaces.Discrete(4)
        self.observation_space = gym.spaces.Box(
            low=0, high=255, shape=(84, 84, 3), dtype=np.uint8
        )

    def reset(self):
        # Reset environment to initial state
        return observation

    def step(self, action):
        # Execute action
        # Return (observation, reward, done, info)
        return obs, reward, done, info

    def render(self, mode='human'):
        # Visualize environment
        pass

Key Libraries and Frameworks

Library Description Best For
OpenAI Gym Standard environment interface Environment development
Stable-Baselines3 Reliable RL algorithm implementations Production-ready agents
Ray RLlib Distributed RL at scale Large-scale training
TF-Agents TensorFlow-based RL TensorFlow ecosystem
Dopamine Research framework Experimentation

1.9 Getting Started with RL

Your First RL Agent

import numpy as np
import gym

# Create environment
env = gym.make('FrozenLake-v1')

# Initialize Q-table
Q = np.zeros([env.observation_space.n, env.action_space.n])

# Hyperparameters
alpha = 0.1      # Learning rate
gamma = 0.99     # Discount factor
epsilon = 0.1    # Exploration rate
episodes = 10000

# Training loop
for episode in range(episodes):
    state = env.reset()
    done = False

    while not done:
        # Epsilon-greedy action selection
        if np.random.random() < epsilon:
            action = env.action_space.sample()  # Explore
        else:
            action = np.argmax(Q[state])        # Exploit

        # Take action
        next_state, reward, done, _ = env.step(action)

        # Q-learning update
        Q[state, action] = Q[state, action] + alpha * (
            reward + gamma * np.max(Q[next_state]) - Q[state, action]
        )

        state = next_state

print("Training completed!")
print("Learned Q-table:")
print(Q)
Exercise:

Run this code and observe how the Q-values change over time. Try modifying the hyperparameters to see their effect on learning speed and final performance.

1.10 The Road Ahead

This chapter introduced the fundamentals of reinforcement learning. In the following chapters, we'll dive deeper into:

Summary

In this chapter, we covered:

  • Reinforcement learning is learning through interaction to maximize cumulative reward
  • The agent-environment interface: states, actions, rewards
  • The exploration-exploitation dilemma is fundamental to RL
  • RL differs from supervised learning in its evaluative, sequential nature
  • Real-world applications span games, robotics, finance, healthcare, and more
  • Key challenges include sample efficiency, credit assignment, and stability
  • Modern tools like Gym and Stable-Baselines3 make RL accessible
  • The discount factor ฮณ balances immediate and future rewards
  • Model-based and model-free approaches offer different tradeoffs
  • RL is particularly suitable for sequential decision-making problems

Review Questions

1. What are the three main components of a reinforcement learning system?

Answer: Agent (the learner), Environment (the world the agent interacts with), and Reward (the feedback signal).

2. Explain the exploration-exploitation tradeoff. Why is it important?

Answer: Exploitation means choosing actions that have worked well before to maximize immediate reward. Exploration means trying new actions to discover potentially better strategies. The tradeoff is important because you need both: exploit to gain reward, explore to find better actions.

3. What is the purpose of the discount factor ฮณ in RL?

Answer: The discount factor (1) makes infinite-horizon problems mathematically tractable, and (2) represents the idea that immediate rewards are more valuable than future rewards due to uncertainty.

4. How does RL differ from supervised learning?

Answer: RL uses evaluative feedback (how good an action was) rather than instructive feedback (what the correct action is). RL deals with sequential decisions where actions affect future states, while supervised learning typically assumes independent samples.

5. What is the credit assignment problem in RL?

Answer: The credit assignment problem is determining which past actions were responsible for a received reward, especially when rewards are delayed or sparse. It's challenging because many actions may have contributed to the eventual outcome.

6. Name three real-world applications of reinforcement learning.

Answer: Examples include: game playing (AlphaGo), robotics (manipulation and locomotion), autonomous vehicles, resource management (data center cooling), finance (algorithmic trading), and healthcare (treatment planning).

7. What is the difference between episodic and continuing tasks?

Answer: Episodic tasks have natural termination points (e.g., chess games, maze navigation) and consist of independent episodes. Continuing tasks have no natural end (e.g., process control, stock trading) and involve continuous interaction.

8. Why might model-based RL be preferred over model-free RL?

Answer: Model-based RL can be more sample-efficient because it can plan ahead by simulating future trajectories using the learned model, rather than relying solely on direct experience like model-free methods.