The user wants Python code to create a Reinforcement Learning (RL) agent that solves a maze using the Q-learning algorithm.
-
Understand the Goal: The objective is to demonstrate Q-learning in a grid-world (maze) environment. I need to define the environment (the maze), the agent (the Q-learner), and the interaction loop (training).
-
Key Components of Q-Learning:
- State (S): The position in the maze (row, column).
- Action (A): Up, Down, Left, Right.
- Reward (R): Negative for walls/steps (to encourage speed), Positive for the goal, maybe negative for hitting a wall.
- Q-Table: A matrix/table where rows are states and columns are actions. Stores the estimated value of taking action a in state s.
- Update Rule: Q(s,a)←Q(s,a)+α[R+γ.
- Exploration vs. Exploitation: Epsilon-greedy strategy.
-
Designing the Code Structure:
- Imports:
numpy is essential for array manipulation.
- The Environment Class (
Maze):
- Attributes: Grid layout, start position, goal position, current position.
- Methods:
reset() (return to start), step(action) (move, return new_state, reward, done).
- The Agent Class (
QAgent):
- Attributes: Q-table, learning rate (α), discount factor (γ), exploration rate (ϵ).
- Methods:
get_action(state) (epsilon-greedy), update(state, action, reward, next_state) (Bellman equation).
- The Training Loop:
- Iterate over episodes.
- Inside, iterate over steps until the goal is reached.
- Track total rewards to plot progress (optional but good for demonstration).
-
Drafting the Maze Environment:
- Let's make a simple grid.
- 0 = Empty, 1 = Wall.
- Example:
[0, 1, 0, 0, 0]
[0, 1, 0, 1, 0]
[0, 0, 0, 1, 0]
[0, 1, 1, 1, 0]
[0, 0, 0, 0, 0] -> Goal at (4,4)
- Rewards:
- Goal: +10 (or 100)
- Move: -1 (small penalty to find shortest path)
- Wall hit: -10 (penalty) or just stay in place with move penalty.
-
Drafting the Q-Learning Logic:
- Initialize Q-table with zeros. Shape:
(rows * cols, num_actions).
- Actions: 0: Up, 1: Down, 2: Left, 3: Right.
- Epsilon decay: It's good practice to reduce ϵ over time so the agent stops exploring and starts exploiting.
-
Refining the Code (Self-Correction during drafting):
- Issue: How to handle boundaries?
- Solution: In the
step function, check if new_row, new_col is inside grid bounds and not a wall. If invalid, stay in the same state but give a negative reward (punishment for hitting a wall).
- Visualization: A text-based printout of the path is helpful to verify it works.
-
Writing the Code (Mental or Scratchpad):
import numpy as np
# Define Maze
maze = np.array(...)
# Define Actions
actions = ['UP', 'DOWN', 'LEFT', 'RIGHT']
# Q-Learning Parameters
alpha = 0.1
gamma = 0.9
epsilon = 0.1
# Loop
for episode in range(1000):
state = start
done = False
while not done:
# Epsilon greedy action selection
# Take step
# Update Q-table
# state = next_state
-
Adding Polish:
- A function to visualize the result (the path taken).
- Comments explaining the math.
- Clear separation of Environment and Agent logic makes it more "standard" RL practice.
-
Final Code Structure Plan:
- Imports (
numpy).
- Environment definition (a hard-coded maze).
- Parameters (learning rate, discount, episodes).
- Q-table initialization.
- Training loop (Epsilon-greedy logic, Bellman update).
- Testing loop (Greedy logic only).
- Visualization function.
-
Review against constraints: The user asked for code to solve a maze using Q-learning. The provided solution should be self-contained, runnable, and commented.
Self-Correction: I should use a class-based structure? Or a script-based structure? A script is easier for a beginner to read top-to-bottom, but classes are cleaner. I will provide a script-based approach with clear functions, as it's often easier to copy-paste and run for a quick demo, but structure it logically like classes.
Specifics:
- Maze: 5x5.
- Start: Top-left (0,0).
- End: Bottom-right (4,4).
- Rewards: +10 for goal, -1 for step (efficiency), -10 for wall.
Let's write the actual Python code based on this plan.
Check: Is the Bellman equation correct?
Q
Yes.
It uses NumPy for the Q-table and environment handling. No external RL libraries (like Gym) are required, making it easy to understand the underlying logic.
The Python Code
import numpy as np
import random
import time
# 1. Define the Environment (The Maze)
# 0 = Empty space, 1 = Wall, 2 = Start, 3 = Goal
maze_layout = [
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 3]
]
class MazeEnvironment:
def __init__(self, maze):
self.maze = np.array(maze)
self.rows, self.cols = self.maze.shape
self.start_pos = self._find_pos(2)
self.goal_pos = self._find_pos(3)
self.state = self.start_pos
# Actions: 0: Up, 1: Down, 2: Left, 3: Right
self.actions = ['UP', 'DOWN', 'LEFT', 'RIGHT']
def _find_pos(self, value):
"""Helper to find coordinates of a specific value (Start/Goal)"""
arr = np.argwhere(self.maze == value)
return tuple(arr[0])
def reset(self):
"""Reset the agent to the start position"""
self.state = self.start_pos
return self.state
def step(self, action):
"""Execute action and return (new_state, reward, done)"""
row, col = self.state
# Calculate tentative new position
if action == 0: # UP
new_row, new_col = row - 1, col
elif action == 1: # DOWN
new_row, new_col = row + 1, col
elif action == 2: # LEFT
new_row, new_col = row, col - 1
elif action == 3: # RIGHT
new_row, new_col = row, col + 1
# Check bounds and walls
if (0 <= new_row < self.rows and
0 <= new_col < self.cols and
self.maze[new_row, new_col] != 1):
# Valid move
self.state = (new_row, new_col)
# Check if Goal reached
if self.state == self.goal_pos:
return self.state, 100, True # Reward: 100, Done: True
else:
return self.state, -1, False # Reward: -1 (small penalty for time), Done: False
else:
# Invalid move (Hit wall or boundary)
return self.state, -10, False # Reward: -10 (penalty), Done: False
# 2. The Q-Learning Agent
class QLearningAgent:
def __init__(self, env, learning_rate=0.1, discount_factor=0.95, epsilon=1.0):
self.env = env
self.lr = learning_rate # Alpha: How much we accept new information
self.gamma = discount_factor # Gamma: How much we care about future rewards
self.epsilon = epsilon # Epsilon: Exploration rate (1.0 = 100% random initially)
self.epsilon_decay = 0.995 # Reduce exploration over time
self.epsilon_min = 0.01
# Initialize Q-Table with zeros
# Dimensions: (Rows, Cols, Number of Actions)
self.q_table = np.zeros((env.rows, env.cols, len(env.actions)))
def choose_action(self, state):
"""Epsilon-Greedy Strategy"""
if random.uniform(0, 1) < self.epsilon:
# Explore: Random action
return random.randint(0, 3)
else:
# Exploit: Best action based on current Q-table
row, col = state
return np.argmax(self.q_table[row, col])
def update_q_table(self, state, action, reward, next_state):
"""The Q-Learning Bellman Equation"""
row, col = state
next_row, next_col = next_state
# Max Q-value for the next state
max_next_q = np.max(self.q_table[next_row, next_col])
# Current Q-value
current_q = self.q_table[row, col, action]
# Q-Learning Formula
# New Q = Current Q + LR * (Reward + (Gamma * Max Future Q) - Current Q)
new_q = current_q + self.lr * (reward + self.gamma * max_next_q - current_q)
self.q_table[row, col, action] = new_q
def decay_epsilon(self):
"""Reduce exploration rate"""
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
# 3. Training Loop
def train_agent():
env = MazeEnvironment(maze_layout)
agent = QLearningAgent(env)
episodes = 1000
print("Training started...")
for episode in range(episodes):
state = env.reset()
done = False
total_reward = 0
while not done:
# 1. Choose action
action = agent.choose_action(state)
# 2. Take action
next_state, reward, done = env.step(action)
# 3. Learn
agent.update_q_table(state, action, reward, next_state)
state = next_state
total_reward += reward
# Decay exploration after every episode
agent.decay_epsilon()
# Optional: Print progress every 100 episodes
if (episode + 1) % 100 == 0:
print(f"Episode {episode + 1}/{episodes} | Total Reward: {total_reward} | Epsilon: {agent.epsilon:.2f}")
print("Training finished!\n")
return env, agent
# 4. Visualization
def visualize_solution(env, agent):
"""Runs the agent greedily to show the solved path"""
state = env.reset()
path = [state]
done = False
steps = 0
print("Optimal Path Found:")
while not done:
# Always choose the best action (Exploit only)
row, col = state
action = np.argmax(agent.q_table[row, col])
next_state, _, done = env.step(action)
path.append(next_state)
state = next_state
steps += 1
if steps > 20: # Safety break if it loops forever
print("Stuck in a loop!")
break
# Draw the path on the maze
maze_visual = [list(row) for row in maze_layout]
for r, c in path:
if maze_visual[r][c] == 0:
maze_visual[r][c] = '.' # Path marker
# Mark start and goal specifically
maze_visual[env.start_pos[0]][env.start_pos[1]] = 'S'
maze_visual[env.goal_pos[0]][env.goal_pos[1]] = 'G'
for row in maze_visual:
print(" ".join(row))
print(f"Steps taken: {len(path)-1}")
# Run the code
if __name__ == "__main__":
env, agent = train_agent()
visualize_solution(env, agent)
How It Works
-
The Environment (MazeEnvironment):
- The maze is a 2D grid.
- The
step function handles the physics. If the agent hits a wall, it stays in place but gets a negative reward (-10). If it moves to an empty spot, it gets a small time penalty (-1) to encourage finding the shortest path. If it reaches the goal, it gets a large reward (+100).
-
The Q-Table (agent.q_table):
- This is the "brain" of the agent. It is a 3D array:
(Rows, Cols, Actions).
- It stores the estimated value (Q-value) of taking a specific action (Up, Down, Left, Right) at every specific coordinate in the maze. Initially, all values are 0.
-
The Learning Process:
- Epsilon-Greedy: At first,
epsilon is 1.0, so the agent moves completely randomly (Exploration). As training progresses, epsilon decays, and the agent starts using its Q-table to choose the best moves (Exploitation).
- The Bellman Equation: This is the core math of Q-learning:
Q(
Interpreting the Output
When you run the code, you will see:
- Training Logs: The epsilon value drops, meaning the agent stops exploring and starts exploiting what it has learned.
- Optimal Path: The visualization prints the maze with
. markers showing the path the agent chose. It should go from S (Start) to G (Goal) avoiding walls 1.