write a neural network that plays ping-pong with a player named paygame. first in…
- User
write a neural network that plays ping-pong with a player named paygame. first in train.py we train the model, and in play.py we use pytorch.
- Assistant
write a neural network that plays ping-pong with a player named paygame. first in train.py we train the model, and in play.py we use pytorch.
Sure! I'll help you create a neural network that plays a ping-pong game (Pong) using PyTorch. We'll create two Python scripts:
train.py: This script will train a neural network model using reinforcement learning (RL) to play Pong.play.py: This script will load the trained model and let you play against the AI agent.We'll use the OpenAI Gym environment for the Pong game and PyTorch for building and training the neural network.
Note: Ensure you have the necessary packages installed:
pip install gym gym[classic_control] torch numpy matplotlib
train.pyimport gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os
# Parameters
learning_rate = 1e-4
gamma = 0.99
batch_size = 5
save_path = 'pong_model.pth'
# Create Pong environment
env = gym.make('Pong-v0')
# Define the neural network
class PolicyNetwork(nn.Module):
def __init__(self):
super(PolicyNetwork, self).__init__()
self.fc1 = nn.Linear(80 * 80, 200)
self.fc2 = nn.Linear(200, env.action_space.n)
def forward(self, x):
x = F.relu(self.fc1(x))
action_scores = self.fc2(x)
return F.softmax(action_scores, dim=1)
policy_net = PolicyNetwork()
optimizer = optim.Adam(policy_net.parameters(), lr=learning_rate)
# Functions to preprocess frames
def preprocess(obs):
obs = obs[35:195] # Crop
obs = obs[::2, ::2, 0] # Downsample by factor of 2
obs[obs == 144] = 0 # Erase background type 1
obs[obs == 109] = 0 # Erase background type 2
obs[obs != 0] = 1 # Everything else (paddles, ball) set to 1
return obs.astype(np.float).ravel()
def discount_rewards(rewards):
discounted_r = np.zeros_like(rewards)
running_add = 0
for t in reversed(range(rewards.size)):
if rewards[t] != 0: # Reset the sum for a new episode
running_add = 0
running_add = running_add * gamma + rewards[t]
discounted_r[t] = running_add
return discounted_r
# Training loop
episode_number = 0
observation = env.reset()
prev_x = None
xs, hs, action_history, rewards = [], [], [], []
running_reward = None
while True:
# Preprocess the observation
cur_x = preprocess(observation)
x = cur_x - prev_x if prev_x is not None else np.zeros(80*80)
prev_x = cur_x
# Convert observation to PyTorch tensor
x_tensor = torch.from_numpy(x).float().unsqueeze(0)
aprob = policy_net(x_tensor)
aprob_np = aprob.detach().numpy()
# Sample action
action = np.random.choice(env.action_space.n, p=aprob_np[0])
xs.append(x)
action_history.append(action)
# Step the environment
observation, reward, done, info = env.step(action)
rewards.append(reward)
if done:
episode_number += 1
epx = np.vstack(xs)
epr = np.vstack(rewards)
epa = np.array(action_history)
# Compute discounted rewards
discounted_epr = discount_rewards(epr)
# Standardize the rewards
discounted_epr -= np.mean(discounted_epr)
discounted_epr /= np.std(discounted_epr)
# Convert to PyTorch tensors
t_epx = torch.from_numpy(epx).float()
t_discounted_epr = torch.from_numpy(discounted_epr).float()
t_epa = torch.from_numpy(epa).long()
# Compute loss and backpropagate
optimizer.zero_grad()
probs = policy_net(t_epx)
neg_log_probs = F.nll_loss(torch.log(probs), t_epa, reduction='none')
loss = (neg_log_probs * t_discounted_epr).mean()
loss.backward()
optimizer.step()
# Reset variables
xs, hs, action_history, rewards = [], [], [], []
observation = env.reset()
prev_x = None
# Print progress
if episode_number % 10 == 0:
print(f'Episode {episode_number}')
# Save the model
if episode_number % 100 == 0:
torch.save(policy_net.state_dict(), save_path)
print(f'Model saved after {episode_number} episodes')
This script sets up the environment, defines a policy network, and uses the REINFORCE algorithm to train the agent. It saves the model every 100 episodes.
play.pyimport gym
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# Parameters
save_path = 'pong_model.pth'
# Create Pong environment
env = gym.make('Pong-v0')
# Define the same policy network as in training
class PolicyNetwork(nn.Module):
def __init__(self):
super(PolicyNetwork, self).__init__()
self.fc1 = nn.Linear(80 * 80, 200)
self.fc2 = nn.Linear(200, env.action_space.n)
def forward(self, x):
x = F.relu(self.fc1(x))
action_scores = self.fc2(x)
return F.softmax(action_scores, dim=1)
policy_net = PolicyNetwork()
policy_net.load_state_dict(torch.load(save_path))
policy_net.eval()
# Preprocess function
def preprocess(obs):
obs = obs[35:195] # Crop
obs = obs[::2, ::2, 0] # Downsample by factor of 2
obs[obs == 144] = 0 # Erase background type 1
obs[obs == 109] = 0 # Erase background type 2
obs[obs != 0] = 1 # Everything else (paddles, ball) set to 1
return obs.astype(np.float).ravel()
# Play the game
observation = env.reset()
prev_x = None
while True:
env.render()
# Preprocess the observation
cur_x = preprocess(observation)
x = cur_x - prev_x if prev_x is not None else np.zeros(80*80)
prev_x = cur_x
# Convert observation to PyTorch tensor
x_tensor = torch.from_numpy(x).float().unsqueeze(0)
with torch.no_grad():
aprob = policy_net(x_tensor)
aprob_np = aprob.numpy()
# Choose the action with highest probability
action = np.argmax(aprob_np)
# Step the environment
observation, reward, done, info = env.step(action)
if done:
observation = env.reset()
prev_x = None
This script loads the trained model and lets the agent play Pong. It uses the trained policy network to decide actions and renders the game so you can watch the AI play.
Training:
train.py to start training the agent.learning_rate and gamma to see how they affect training.Playing:
play.py to watch the agent play Pong.save_path in play.py matches the path where the model was saved during training.Monitoring Training:
Hyperparameter Tuning:
Resume Training:
train.py to load an existing model if you want to resume training from a saved checkpoint.Disclaimer: Training a Pong agent from scratch using policy gradients can be challenging and may not converge easily without proper tuning and computational resources. Consider using advanced algorithms like Proximal Policy Optimization (PPO) for better performance if needed.
Not yet included in a published release.