The user wants a program that implements reinforcement learning (RL) agents.
This is a broad request. I need to create a self-contained, educational example that demonstrates the core concepts of RL without being overly complex (like requiring a specific external environment like OpenAI Gym, though I could use it, standard libraries are safer for a standalone script) or too trivial.
Key Components of an RL System:
- Environment: The world the agent interacts with. It needs
step(action) and reset() methods.
- Agent: The learner. It needs
act(state) (policy) and learn(state, action, reward, next_state) (update rule).
- Training Loop: The process of running episodes.
Choosing the Algorithm:
- Q-Learning: Classic, tabular, easy to understand. Good for a grid world.
- Deep Q-Networks (DQN): Neural networks involved. Requires libraries like PyTorch or TensorFlow. Might be too heavy for a "hello world" style script, but very popular.
- Policy Gradients: A bit more complex to implement from scratch stably.
Decision: I will provide two approaches:
- Tabular Q-Learning: Using
numpy. This is the best way to understand the math.
- A simple custom Environment: A "GridWorld" is standard and visualizable.
Structure of the Code:
-
The Environment (GridWorld):
- 2D grid (e.g., 5x5).
- Start state, Goal state, maybe some obstacles or a "trap".
- Actions: Up, Down, Left, Right.
- Rewards: +10 for goal, -10 for trap, -1 for each step (to encourage efficiency).
-
The Agent (QLearningAgent):
- Q-table: A dictionary or array mapping (state) -> (action_values).
- Hyperparameters: Learning rate (α), Discount factor (γ), Exploration rate (ϵ).
- Methods:
get_action(), update().
-
The Training Script:
- Loop through episodes.
- Implement the exploration/exploitation tradeoff (epsilon-greedy).
- Print progress.
-
Bonus/Next Steps:
- Mention Deep Q-Learning (DQN) briefly or provide a snippet if requested, but keep the main solution pure Python/Numpy for maximum compatibility and clarity.
Refining the Code:
- Imports:
numpy, random, time.
- Visualization: A simple ASCII print of the grid helps see what's happening.
Drafting the Q-Learning Update Rule:
Q(s,a)←Q(s,a)+α[r+
Let's write the actual Python code.
- Environment Class:
step(action) returns next_state, reward, done.
- Agent Class: Needs to handle state discretization if necessary, but in GridWorld, states are discrete coordinates.
Self-Correction/Constraint Check:
The user asked for "a program". I should make it a complete, runnable script.
I will structure it using standard Object-Oriented Programming (OOP) patterns used in RL libraries (like Gym) because that's best practice.
Plan:
- Define the
GridEnvironment.
- Define the
QLearningAgent.
- Main execution block to train and then visualize the result.
Let's add a "render" function to the environment so the user can watch the agent move.
Code details:
- Grid size: 5x5.
- Actions: 0: Up, 1: Down, 2: Left, 3: Right.
- Epsilon decay: Start high (1.0), decay over time.
This looks solid. It covers the "Agent", the "Environment", and the "Learning" loop.
Alternative:
Should I include a DQN example?
It adds dependency on PyTorch. Standard Q-learning is better for a fundamental understanding. I will stick to Tabular Q-Learning but write comments explaining how to extend it.
Final Code Structure:
- Imports.
GridWorld Class.
QLearningAgent Class.
train() function.
play() function.
if __name__ == "__main__": block.
This provides a complete, runnable educational tool.
Self-Correction during drafting: Make sure the Q-table handles states correctly. A simple dictionary (row, col) -> [q_up, q_down, q_left, q_right] is easiest.
Let's go.
Here is a complete, runnable Python program that implements a Reinforcement Learning (RL) system from scratch.
To make this easy to understand and run without downloading external environments (like Gym), I have built a custom Grid World environment.
The solution includes:
- The Environment: A 5x5 grid where the agent must navigate from Start to Goal while avoiding traps.
- The Agent: Implements Q-Learning (a classic RL algorithm) using a Q-Table to store state-action values.
The Python Program
You can save this code as rl_agent.py and run it.
import numpy as np
import time
import os
# ==========================================
# 1. The Environment (Grid World)
# ==========================================
class GridWorld:
"""
A simple 5x5 grid environment.
Agent starts at (0,0) [Top-Left].
Goal is at (4,4) [Bottom-Right].
Obstacles/Traps are placed in the middle.
"""
def __init__(self, rows=5, cols=5):
self.rows = rows
self.cols = cols
self.start_pos = (0, 0)
self.goal_pos = (rows-1, cols-1)
# Define obstacles (Traps)
self.traps = [(1, 2), (2, 2), (3, 2), (2, 1)]
self.state = self.start_pos
# Actions: 0: Up, 1: Down, 2: Left, 3: Right
self.action_space = 4
def reset(self):
"""Resets the environment to the starting state."""
self.state = self.start_pos
return self.state
def step(self, action):
"""
Takes an action and returns (new_state, reward, done).
"""
row, col = self.state
# Calculate new position based on action
if action == 0: # Up
row = max(row - 1, 0)
elif action == 1: # Down
row = min(row + 1, self.rows - 1)
elif action == 2: # Left
col = max(col - 1, 0)
elif action == 3: # Right
col = min(col + 1, self.cols - 1)
new_state = (row, col)
self.state = new_state
# Determine Reward and Done status
reward = -1 # Small penalty for every move to encourage speed
done = False
if new_state == self.goal_pos:
reward = 100 # Big reward for reaching goal
done = True
elif new_state in self.traps:
reward = -100 # Big penalty for hitting a trap
done = True
return new_state, reward, done
def render(self):
"""Displays the grid in the console."""
grid = []
for r in range(self.rows):
row_str = ""
for c in range(self.cols):
pos = (r, c)
if pos == self.state:
row_str += "🤖 " # Agent
elif pos == self.goal_pos:
row_str += "🏁 " # Goal
elif pos in self.traps:
row_str += "💀 " # Trap
else:
row_str += "⬜ " # Empty
print(row_str)
print("-" * 20)
# ==========================================
# 2. The Agent (Q-Learning Algorithm)
# ==========================================
class QLearningAgent:
def __init__(self, env, learning_rate=0.1, discount_factor=0.95, epsilon=1.0):
self.env = env
self.alpha = learning_rate # How much we accept new information
self.gamma = discount_factor # How much we care about future rewards
self.epsilon = epsilon # Exploration rate (1.0 = 100% random moves initially)
# Initialize Q-Table with zeros
# Dimensions: (Rows, Cols, Actions)
self.q_table = np.zeros((env.rows, env.cols, env.action_space))
def choose_action(self, state):
"""
Epsilon-Greedy Strategy:
With probability epsilon, explore (random move).
Otherwise, exploit (choose best known move).
"""
if np.random.random() < self.epsilon:
return np.random.randint(0, self.env.action_space)
else:
# Return action with highest Q-value for current state
row, col = state
return np.argmax(self.q_table[row, col])
def learn(self, state, action, reward, next_state):
"""
The core Q-Learning update equation:
Q(s,a) = Q(s,a) + alpha * [reward + gamma * max(Q(s',a')) - Q(s,a)]
"""
row, col = state
next_row, next_col = next_state
# Best estimated value for the next state
best_next_q = np.max(self.q_table[next_row, next_col])
# Current Q-value
current_q = self.q_table[row, col, action]
# Calculate new Q-value
new_q = current_q + self.alpha * (reward + self.gamma * best_next_q - current_q)
# Update table
self.q_table[row, col, action] = new_q
# ==========================================
# 3. Main Training Loop
# ==========================================
def main():
# Initialize environment and agent
env = GridWorld()
agent = QLearningAgent(env)
episodes = 50 # How many games to play
max_steps = 100 # Max steps per game
print("Training the agent...")
for episode in range(episodes):
state = env.reset()
total_reward = 0
done = False
# Decay epsilon: Reduce exploration over time
# As the agent learns the map, it should rely less on randomness
agent.epsilon = max(0.01, agent.epsilon * 0.95)
for step in range(max_steps):
action = agent.choose_action(state)
next_state, reward, done = env.step(action)
agent.learn(state, action, reward, next_state)
state = next_state
total_reward += reward
if done:
break
print(f"Episode {episode + 1}: Total Reward: {total_reward}")
print("\nTraining Complete! Watch the agent solve the maze.")
print("Path taken:\n")
# ==========================================
# 4. Visualization (Testing)
# ==========================================
# Set epsilon to 0 so the agent only uses its brain (no random moves)
agent.epsilon = 0
state = env.reset()
env.render()
for _ in range(20):
action = agent.choose_action(state)
next_state, reward, done = env.step(action)
state = next_state
# Clear console for animation effect (works in most terminals)
time.sleep(0.3)
os.system('cls' if os.name == 'nt' else 'clear')
env.render()
if done:
if reward > 0:
print("SUCCESS! The agent reached the goal.")
else:
print("FAIL! The agent hit a trap.")
break
if __name__ == "__main__":
main()
How It Works
- The Grid (Environment):
- The world is a 5x5 grid.
- Start: Top Left (0,0).
- Goal: Bottom Right (4,4).
- Traps: Placed in the middle to block the path.
- Q-Learning (The Brain):
- We create a table (Q-Table) that initializes every possible state (grid position) and action (Up, Down, Left, Right) to 0.
- As the agent plays, it updates this table. If it moves to a square that gives a reward, it updates the value of the action that got it there.
- Exploration vs. Exploitation:
- The
epsilon variable controls this.
- Initially,
epsilon is high (1.0), so the agent moves randomly to discover the map (Exploration).
- As training progresses, we decrease
epsilon. The agent starts using its Q-Table memory to choose the best moves (Exploitation).
Output Explanation
When you run the script:
- Training Phase: You will see text output showing the total reward per episode. Initially, rewards will be very negative (hitting traps or wandering). By the end, rewards should be close to +100 (reaching the goal).
- Visual Phase: The console will clear and draw the grid (
🤖). You will see the agent move step-by-step. If trained correctly, it will navigate around the skulls (💀) to reach the flag (🏁).