The user wants a program that implements reinforcement learning (RL) agents.
This is a broad request. To provide a useful and illustrative answer, I need to:
- Choose a framework: Python is the standard language, and
gymnasium (formerly gym) is the standard environment library. For the algorithms, I can write them from scratch (using NumPy) or use a library like stable-baselines3. Writing from scratch is better for educational purposes, but using a library is more practical for "real" use. I should probably provide a simple Q-learning implementation from scratch (good for understanding) and perhaps mention or show a Deep Q-Network (DQN) example using a library or PyTorch.
- Select an environment: The "FrozenLake" environment from Gymnasium is a classic. It's simple enough to visualize and train quickly without a GPU, but complex enough to show learning.
- Determine the specific agents to implement:
- Random Agent: A baseline to compare against.
- Q-Learning Agent: A classic tabular method. It's the "Hello World" of RL.
- SARSA (Optional but good): On-policy vs Off-policy comparison. I'll stick to Q-Learning for simplicity unless the code gets too long.
- Deep Q-Network (DQN) Agent: Introduces neural networks. This makes it "modern" RL. I'll write a simple PyTorch version of this.
- Structure the code:
- Imports.
- Environment setup.
- A class structure for agents (BaseAgent, QLearningAgent, DQNAgent).
- A training loop.
- A testing/visualization loop.
Plan:
- Introduction: Briefly explain what we are building (Q-Learning and DQN).
- Prerequisites: List necessary libraries (
gymnasium, numpy, matplotlib, torch).
- Part 1: Tabular Q-Learning (The "Classic" Approach):
- Define the Q-table.
- Implement the update rule: Q(s,a)←Q(s,a)+α[r+γmaxa′Q(s.
- Handle exploration (epsilon-greedy).
- Part 2: Deep Q-Learning (The "Modern" Approach):
- Define a simple Neural Network (PyTorch).
- Implement Experience Replay (Memory buffer).
- Implement the DQN training step (sample batch, compute loss, backprop).
- Main Execution Block:
- Train both agents on
CartPole-v1 (better for DQN than FrozenLake).
- Plot results.
Self-Correction during thought process: FrozenLake is good for Q-learning, but CartPole-v1 is the standard benchmark for DQN. I should probably use CartPole for the DQN part and Q-learning can work on CartPole if the state space is discretized, but that's messy.
Revised Plan: I will stick to CartPole-v1 for the whole example. I will implement:
- A Random Agent (Baseline).
- A Simple Policy Gradient / DQN Agent (The "real" RL).
Actually, for a "Create a program" request, showing Q-Learning (Tabular) is crucial for educational value because it's explicit. But Q-Learning fails on continuous spaces like CartPole without binning.
Let's do two separate examples or one unified framework?
Let's stick to CartPole. Why? Because it's more satisfying to see a balance task solved.
However, tabular methods don't work well on CartPole (continuous state space).
Okay, let's go back to FrozenLake. It works perfectly for Q-Learning. DQN is overkill for FrozenLake but it works.
Decision: I will provide a comprehensive script that implements Q-Learning on the FrozenLake environment. This is the most robust way to teach the concepts without getting bogged down in PyTorch debugging or complex replay buffers.
Wait, the user might want something more advanced. Let's provide a modular structure.
I will create a Python script that defines an abstract Agent class.
Then I will implement:
RandomAgent
QLearningAgent (Tabular)
DQNAgent (Deep Q-Network) - I will add this if the code length allows, otherwise just Q-Learning.
Let's aim for Q-Learning as the primary example because it runs without heavy dependencies like PyTorch, making it accessible. I'll add comments on how to extend it.
Refined Plan:
- Setup: Use
gymnasium and numpy.
- Environment:
FrozenLake-v1 (slippery makes it interesting).
- Algorithm: Q-Learning with Epsilon-Greedy decay.
- Visualization: Plot reward over episodes using
matplotlib.
Let's write the code structure mentally:
import gymnasium as gym
import numpy as np
import matplotlib.pyplot as plt
class QLearningAgent:
def __init__(...):
self.q_table = {}
def get_action(...): ...
def update(...): ...
Actually, I will write a cleaner, more Pythonic version using a class-based structure.
Wait, maybe I should do DQN?
If I only do Q-learning, it might look "toy-like".
If I do DQN, the code is 100 lines long and requires PyTorch.
Let's provide a Q-Learning solution for Taxi-v3. Taxi is better than FrozenLake because the reward structure is clearer (-1 per step, +20 dropoff, -10 illegal pickup). It demonstrates the learning curve very well.
Final Decision on Content:
- Environment:
Taxi-v3. It's discrete, tabular methods work perfectly, and it's visual.
- Agent: Q-Learning Agent with decaying epsilon.
- Metrics: Track timesteps and penalties.
- Code: Fully self-contained.
I will also briefly explain how this translates to Deep Learning (DQN) in the text.
Let's write the code.
Key components of the code:
- Hyperparameters: Alpha (learning rate), Gamma (discount), Epsilon (exploration), Episodes.
- The Q-Table: A matrix of (State, Action).
- The Loop:
- Reset env.
- Choose action (Explore vs Exploit).
- Step env.
- Update Q-Table:
Q[state, action] = Q[state, action] + lr * (reward + gamma * np.max(Q[new_state, :]) - Q[state, action]).
- Update state.
- Evaluation: Run without random actions.
I will ensure the code is copy-paste runnable.
Additional thought: Should I add a class hierarchy?
class Agent: abstract methods act, learn.
class RandomAgent(Agent): random actions.
class QAgent(Agent): Q-learning.
This shows good software engineering practice.
Let's go with the Class Hierarchy approach. It makes it easier for the user to plug in different agents later.
Steps:
- Install command (
pip install gymnasium).
- Python code with
Agent base class.
RandomAgent implementation.
QLearningAgent implementation.
train and evaluate helper functions.
- Main execution block running on
Taxi-v3.
Let's check Taxi-v3 details.
State space: 500.
Action space: 6.
Perfect for a dictionary or matrix.
What about CartPole?
If I use CartPole, I must discretize or use a Neural Network.
Discretization adds code complexity (binning logic).
Neural Network adds library dependency (PyTorch/TensorFlow).
I will stick to Taxi-v3 for the cleanest code, but add a note that for continuous spaces, Neural Networks are used.
Let's draft the response.
- Start with prerequisites.
- Provide the complete code.
- Explain the specific RL concepts (State, Action, Reward, Q-Value).
- Explain the Q-Learning algorithm used.
- Show output examples.
Here is a complete, executable Python program that implements Reinforcement Learning (RL) agents.
I have chosen to build this solution using Q-Learning, a classic and foundational algorithm. This example uses the OpenAI Gym library (specifically the Taxi-v3 environment), which is the standard benchmark for learning RL.
Prerequisites
You will need to install the gymnasium library (the maintained version of OpenAI Gym):
pip install gymnasium
The Python Program
This program defines a modular structure:
Agent (Base Class): Defines the structure for any RL agent.
RandomAgent: A baseline agent that acts randomly (for comparison).
QLearningAgent: An intelligent agent that learns from experience using the Q-Learning algorithm.
- Training/Evaluation Loop: Functions to train the agent and then visualize its performance.
import gymnasium as gym
import numpy as np
import random
import time
from collections import defaultdict
# ==========================================
# 1. Define the Agents
# ==========================================
class Agent:
"""Base class for RL agents."""
def __init__(self, env):
self.env = env
self.n_actions = env.action_space.n
def get_action(self, state):
raise NotImplementedError
def update(self, state, action, reward, next_state, done):
pass
class RandomAgent(Agent):
"""An agent that selects actions randomly."""
def get_action(self, state):
return self.env.action_space.sample()
class QLearningAgent(Agent):
"""
An agent that learns using Q-Learning.
Q-Learning updates the value of an action based on the immediate reward
and the best possible future reward (Temporal Difference).
"""
def __init__(self, env, learning_rate=0.1, discount_factor=0.99, epsilon=1.0, epsilon_decay=0.9995, epsilon_min=0.01):
super().__init__(env)
self.lr = learning_rate
self.gamma = discount_factor
self.epsilon = epsilon
self.epsilon_decay = epsilon_decay
self.epsilon_min = epsilon_min
# The "Brain": A table mapping (State) -> [Value of Action 0, Value of Action 1, ...]
# We use defaultdict to initialize unseen states with zeros automatically.
self.q_table = defaultdict(lambda: np.zeros(self.n_actions))
def get_action(self, state):
"""
Epsilon-Greedy Strategy:
- With probability epsilon: Explore (random action)
- With probability 1-epsilon: Exploit (best known action)
"""
if random.random() < self.epsilon:
return self.env.action_space.sample() # Explore
else:
return np.argmax(self.q_table[state]) # Exploit
def update(self, state, action, reward, next_state, done):
"""
The Core Q-Learning Equation:
Q(s,a) = Q(s,a) + alpha * [Reward + gamma * max(Q(s', a')) - Q(s,a)]
"""
current_q = self.q_table[state][action]
if done:
target = reward
else:
# The best we can do in the next state
max_next_q = np.max(self.q_table[next_state])
target = reward + self.gamma * max_next_q
# Update the Q-value
self.q_table[state][action] = current_q + self.lr * (target - current_q)
# Decay exploration rate
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
# ==========================================
# 2. Training & Evaluation Functions
# ==========================================
def train_agent(env, agent, n_episodes=5000):
print(f"Training {agent.__class__.__name__} for {n_episodes} episodes...")
rewards_history = []
for episode in range(n_episodes):
state, info = env.reset()
total_reward = 0
done = False
truncated = False
while not done and not truncated:
# 1. Choose action
action = agent.get_action(state)
# 2. Take action
next_state, reward, done, truncated, info = env.step(action)
# 3. Learn
agent.update(state, action, reward, next_state, done)
state = next_state
total_reward += reward
rewards_history.append(total_reward)
# Print progress every 1000 episodes
if (episode + 1) % 1000 == 0:
avg_reward = np.mean(rewards_history[-1000:])
print(f"Episode {episode + 1}/{n_episodes} | Avg Reward (last 1000): {avg_reward:.2f} | Epsilon: {agent.epsilon:.3f}")
print("Training complete.\n")
def evaluate_agent(env, agent, n_episodes=5):
print(f"Evaluating {agent.__class__.__name__}...")
for episode in range(n_episodes):
state, info = env.reset()
done = False
truncated = False
total_reward = 0
print(f"\n--- Episode {episode + 1} ---")
while not done and not truncated:
# We strictly exploit (no random moves) during evaluation
# However, our QLearningAgent class handles this naturally because epsilon is low now.
# To force optimal behavior, we could specifically request argmax here.
if isinstance(agent, QLearningAgent):
action = np.argmax(agent.q_table[state])
else:
action = agent.get_action(state)
# Render the environment (prints text to console)
# Note: render_mode must be 'ansi' or 'human' for this to print text
# Since we created env with None, we can't visually render here easily without recreating.
# But we will simulate the steps.
next_state, reward, done, truncated, info = env.step(action)
state = next_state
total_reward += reward
print(f"Total Reward: {total_reward}")
if total_reward >= 8: # Taxi-v3 gives +20 for dropoff, -1 per step. A successful run is usually 8-20 points depending on path.
print("Result: SUCCESS")
else:
print("Result: FAIL or INCOMPLETE")
# ==========================================
# 3. Main Execution
# ==========================================
if __name__ == "__main__":
# Create the environment
# Taxi-v3: A grid world where a taxi must pick up a passenger and drop them off.
env = gym.make("Taxi-v3")
# 1. Initialize Agents
smart_agent = QLearningAgent(env)
random_agent = RandomAgent(env)
# 2. Train the Smart Agent
train_agent(env, smart_agent, n_episodes=5000)
# 3. Compare Performance
print("="*40)
print("Comparing Smart Agent vs Random Agent")
print("="*40)
# Evaluate Smart Agent
evaluate_agent(env, smart_agent, n_episodes=3)
# Evaluate Random Agent (Baseline)
evaluate_agent(env, random_agent, n_episodes=1)
env.close()
How it Works
-
The Environment (Taxi-v3):
- There are 4 locations (R, G, Y, B) and a taxi.
- The goal is to pick up a passenger at one location and drop them off at another.
- Rewards: +20 for successful drop-off, -1 for every time-step (to encourage speed), -10 for illegal pick-up/drop-off actions.
-
Q-Learning (The update method):
- The agent maintains a Q-Table, which is a cheat sheet. It says: "If I am in State X and take Action Y, how much reward can I expect in the future?"
- Initially, the table is empty (zeros).
- As the agent explores, it updates the table using the formula:
Q(s,a)←Q(s
What to expect when running
- Training Phase: You will see the average reward start very low (often negative) and then rapidly rise as the agent figures out the game rules.
- Evaluation Phase: The "Smart Agent" will consistently achieve positive scores (around +8 to +20). The "Random Agent" will almost always fail, resulting in large negative scores (like -200) because it never learns the goal.