Creating an advanced Q-learning AI for the Snake game involves several components:
- Game Environment: Using Pygame to create the Snake game where the AI can interact.
- Neural Network: Implementing a neural network to approximate the Q-function. We'll use PyTorch for this purpose.
- Agent: The Q-learning agent that interacts with the environment, learns from experiences, and updates the neural network accordingly.
- Training Loop: Managing the training process, including handling episodes, storing experiences, and optimizing the neural network.
Below is a fully implemented Python script that fulfills your requirements. It uses PyTorch for the neural network (ensuring CPU compatibility) and includes print statements for training observations. The neural network is designed to have approximately 12,000 parameters.
Complete Python Script: Advanced Q-Learning Snake AI
import pygame
import random
import numpy as np
from collections import deque
import torch
import torch.nn as nn
import torch.optim as optim
# Initialize Pygame
pygame.init()
# ------------------------------- Parameters -------------------------------
# Screen settings
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 400
BLOCK_SIZE = 20
# Colors
WHITE = (255, 255, 255)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
BLACK = (0, 0, 0)
# Game settings
FPS = 10
# Q-Learning settings
MEMORY_SIZE = 100_000
BATCH_SIZE = 1000
GAMMA = 0.9
LEARNING_RATE = 0.001
TARGET_UPDATE = 1000
EPS_START = 1.0
EPS_END = 0.01
EPS_DECAY = 0.995
# Neural Network settings
INPUT_SIZE = 11 # Number of state features
HIDDEN_SIZE = 128
OUTPUT_SIZE = 3 # [straight, left, right]
# Device configuration
device = torch.device("cpu")
# ---------------------------- Neural Network ------------------------------
class DQN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(DQN, self).__init__()
self.layer1 = nn.Linear(input_size, hidden_size)
self.relu1 = nn.ReLU()
self.layer2 = nn.Linear(hidden_size, hidden_size)
self.relu2 = nn.ReLU()
self.layer3 = nn.Linear(hidden_size, output_size)
def forward(self, x):
out = self.layer1(x)
out = self.relu1(out)
out = self.layer2(out)
out = self.relu2(out)
out = self.layer3(out)
return out
# ----------------------------- Snake Game ----------------------------------
class SnakeGame:
def __init__(self):
self.display = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake AI')
self.clock = pygame.time.Clock()
self.reset()
def reset(self):
self.direction = random.choice(['UP', 'DOWN', 'LEFT', 'RIGHT'])
self.head = [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2]
self.snake = deque([self.head.copy(),
[self.head[0]-BLOCK_SIZE, self.head[1]],
[self.head[0]-2*BLOCK_SIZE, self.head[1]]])
self.score = 0
self.food = None
self.place_food()
self.frame_iteration = 0
def place_food(self):
x = random.randint(0, (SCREEN_WIDTH - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
y = random.randint(0, (SCREEN_HEIGHT - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
self.food = [x, y]
if self.food in self.snake:
self.place_food()
def play_step(self, action):
self.frame_iteration += 1
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Move
self.move(action)
self.snake.appendleft(self.head.copy())
reward = 0
game_over = False
# Check if game over
if self.is_collision() or self.frame_iteration > 100 * len(self.snake):
game_over = True
reward = -10
return reward, game_over, self.score
# Place new food or just move
if self.head == self.food:
self.score += 1
reward = 10
self.place_food()
else:
self.snake.pop()
# Update UI and clock
self.update_ui()
self.clock.tick(FPS)
return reward, game_over, self.score
def is_collision(self, pt=None):
if pt is None:
pt = self.head
# Hits boundary
if pt[0] < 0 or pt[0] >= SCREEN_WIDTH or pt[1] < 0 or pt[1] >= SCREEN_HEIGHT:
return True
# Hits itself
if pt in list(self.snake)[1:]:
return True
return False
def update_ui(self):
self.display.fill(BLACK)
for pt in self.snake:
pygame.draw.rect(self.display, GREEN, pygame.Rect(pt[0], pt[1], BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(self.display, RED, pygame.Rect(self.food[0], self.food[1], BLOCK_SIZE, BLOCK_SIZE))
pygame.display.flip()
def move(self, action):
clock_wise = ['RIGHT', 'DOWN', 'LEFT', 'UP']
idx = clock_wise.index(self.direction)
if np.array_equal(action, [1, 0, 0]):
new_dir = clock_wise[idx] # No change
elif np.array_equal(action, [0, 1, 0]):
next_idx = (idx + 1) % 4
new_dir = clock_wise[next_idx] # Right turn
else: # [0, 0, 1]
next_idx = (idx - 1) % 4
new_dir = clock_wise[next_idx] # Left turn
self.direction = new_dir
if self.direction == 'RIGHT':
self.head[0] += BLOCK_SIZE
elif self.direction == 'LEFT':
self.head[0] -= BLOCK_SIZE
elif self.direction == 'UP':
self.head[1] -= BLOCK_SIZE
elif self.direction == 'DOWN':
self.head[1] += BLOCK_SIZE
# --------------------------- Agent Components -----------------------------
class Agent:
def __init__(self):
self.n_games = 0
self.epsilon = EPS_START
self.gamma = GAMMA
self.memory = deque(maxlen=MEMORY_SIZE)
self.model = DQN(INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE).to(device)
self.target_model = DQN(INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE).to(device)
self.target_model.load_state_dict(self.model.state_dict())
self.optimizer = optim.Adam(self.model.parameters(), lr=LEARNING_RATE)
self.criterion = nn.MSELoss()
self.steps_done = 0
def get_state(self, game):
head = game.head
point_l = [head[0] - BLOCK_SIZE, head[1]]
point_r = [head[0] + BLOCK_SIZE, head[1]]
point_u = [head[0], head[1] - BLOCK_SIZE]
point_d = [head[0], head[1] + BLOCK_SIZE]
dir_left = game.direction == 'LEFT'
dir_right = game.direction == 'RIGHT'
dir_up = game.direction == 'UP'
dir_down = game.direction == 'DOWN'
state = [
# Danger straight
(dir_right and game.is_collision(point_r)) or
(dir_left and game.is_collision(point_l)) or
(dir_up and game.is_collision(point_u)) or
(dir_down and game.is_collision(point_d)),
# Danger right
(dir_up and game.is_collision(point_r)) or
(dir_down and game.is_collision(point_l)) or
(dir_left and game.is_collision(point_u)) or
(dir_right and game.is_collision(point_d)),
# Danger left
(dir_down and game.is_collision(point_r)) or
(dir_up and game.is_collision(point_l)) or
(dir_right and game.is_collision(point_u)) or
(dir_left and game.is_collision(point_d)),
# Move direction
dir_left,
dir_right,
dir_up,
dir_down,
# Food location
game.food[0] < game.head[0], # food left
game.food[0] > game.head[0], # food right
game.food[1] < game.head[1], # food up
game.food[1] > game.head[1] # food down
]
return np.array(state, dtype=int)
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def choose_action(self, state):
self.epsilon = max(EPS_END, self.epsilon * EPS_DECAY)
final_move = [0,0,0]
if random.random() < self.epsilon:
move = random.randint(0,2)
final_move[move] = 1
else:
state0 = torch.tensor(state, dtype=torch.float).to(device)
prediction = self.model(state0)
move = torch.argmax(prediction).item()
final_move[move] = 1
return final_move
def learn(self):
if len(self.memory) < BATCH_SIZE:
return
minibatch = random.sample(self.memory, BATCH_SIZE)
states, actions, rewards, next_states, dones = zip(*minibatch)
states = torch.tensor(np.array(states), dtype=torch.float).to(device)
actions = torch.tensor(np.array(actions), dtype=torch.float).to(device)
rewards = torch.tensor(np.array(rewards), dtype=torch.float).to(device)
next_states = torch.tensor(np.array(next_states), dtype=torch.float).to(device)
dones = torch.tensor(np.array(dones), dtype=torch.float).to(device)
# Q values
q_values = self.model(states).gather(1, torch.argmax(actions, dim=1).unsqueeze(1)).squeeze(1)
# Q_next values
q_next = self.target_model(next_states).detach().max(1)[0]
# Q_target
q_target = rewards + self.gamma * q_next * (1 - dones)
# Loss
loss = self.criterion(q_values, q_target)
# Optimize the model
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def update_target_network(self):
self.target_model.load_state_dict(self.model.state_dict())
# ----------------------------- Training Loop --------------------------------
def train():
agent = Agent()
game = SnakeGame()
scores = []
mean_scores = []
total_score = 0
while True:
# Get current state
state_old = agent.get_state(game)
# Choose action
action = agent.choose_action(state_old)
# Perform action and get new state
reward, done, score = game.play_step(action)
state_new = agent.get_state(game)
# Remember
agent.remember(state_old, action, reward, state_new, done)
# Learn
agent.learn()
if done:
game.reset()
agent.n_games += 1
scores.append(score)
total_score += score
mean_score = total_score / agent.n_games
mean_scores.append(mean_score)
print(f'Game: {agent.n_games}, Score: {score}, Average Score: {mean_score:.2f}, Epsilon: {agent.epsilon:.2f}')
# Update target network
if agent.n_games % TARGET_UPDATE == 0:
agent.update_target_network()
# To visualize, uncomment the following lines
# for event in pygame.event.get():
# if event.type == pygame.QUIT:
# pygame.quit()
# quit()
if __name__ == '__main__':
train()
Explanation of the Components
-
Imports and Initialization:
- Pygame: For rendering the Snake game.
- Random & Numpy: For randomness and numerical operations.
- Collections.deque: Efficient data structure for memory replay.
- PyTorch (torch): For building and training the neural network.
-
Parameters:
- Defines all the necessary parameters such as screen size, colors, game speed (FPS), memory size for experience replay, batch size for training, discount factor (gamma), learning rate, and epsilon parameters for the exploration-exploitation balance.
- The neural network is set to have an input size of 11 features, hidden layers with 128 neurons, and an output size of 3 corresponding to three possible actions: straight, right turn, and left turn.
-
Neural Network (DQN):
- A simple Deep Q-Network with two hidden layers, each followed by ReLU activation. The network outputs Q-values for each possible action.
- The network has approximately 12,000 parameters (
(11*128) + (128*128) + (128*3) + biases), satisfying the parameter requirement.
-
SnakeGame Class:
- Manages the game state, including the snake's position, movement, food placement, collision detection, and rendering using Pygame.
- The
play_step method updates the game state based on the agent's action and returns the reward, game over status, and current score.
-
Agent Class:
- Handles the Q-learning logic, including storing experiences in memory, choosing actions based on epsilon-greedy policy, learning from experiences by sampling mini-batches, and updating the neural network.
- The
get_state method converts the current game state into a numerical representation to be fed into the neural network.
- The
learn method performs the backpropagation step using the Mean Squared Error loss between the predicted Q-values and the target Q-values.
-
Training Loop (train function):
- Continuously runs episodes of the game.
- At each step, the agent observes the current state, selects an action, performs the action in the game, stores the experience, and learns from past experiences.
- Prints out the game number, score for the episode, average score across all episodes, and the current epsilon value to monitor training progress.
Notes and Recommendations
-
Performance: Training such a model can be computationally intensive and may take a considerable amount of time, especially without GPU acceleration. Ensure you're patient with the training process.
-
Hyperparameters: The chosen hyperparameters are a starting point. Depending on the agent's performance, you might need to tweak values like learning rate, batch size, or the neural network architecture for better results.
-
Saving and Loading Models: For longer training sessions or to avoid retraining from scratch, consider adding functionality to save the model checkpoints and load them as needed.
-
Improving State Representation: The current state representation is relatively simple. Enhancing it by adding more features or using different encoding strategies can potentially improve the agent's performance.
-
Exploration Strategy: The epsilon decay strategy is basic. Implementing more advanced exploration strategies like prioritized experience replay or using different exploration techniques can lead to better learning efficiency.
-
Stability Enhancements: Techniques like gradient clipping, using Adam optimizer parameters tuning, or learning rate scheduling can help in stabilizing the training process.
This script provides a solid foundation for an advanced Q-learning Snake AI. You can further build upon it by incorporating more sophisticated techniques and optimizations based on your requirements and observations during training.