How can I make this machine learning algorithm for continuous action learn better? [code]
- User
How can I make this machine learning algorithm for continuous action learn better?
python - Assistant
How can I make this machine learning algorithm for continuous action learn better?
from torch import nn
import gymnasium as gym
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.linear_stack = nn.Sequential(
nn.Linear(3, 4),
nn.LeakyReLU(),
nn.Linear(4, 11),
nn.LeakyReLU()
)
self.mean = nn.Linear(11, 1)
self.std = nn.Linear(11, 1)
def forward(self, x):
x = self.linear_stack(x)
mean = self.mean(x)
std = self.std(x)
std = F.sigmoid(std)
return mean, std
def train(model):
optimizer = optim.AdamW(model.parameters(), lr=0.01)
env = gym.make("Pendulum-v1")
for episode in range(300): # Number of episodes to train on
observation, info = env.reset()
obs_tensor = torch.tensor(observation, dtype=torch.float32)
log_probs = []
rewards = []
for step in range(500): # Max steps per episode
# Forward pass
mean, std = model(obs_tensor)
normal_distributions = torch.distributions.normal.Normal(mean, std)
action = normal_distributions.sample()
log_prob = normal_distributions.log_prob(action)
action_np = np.clip(action.detach().numpy(), -2, 2)
# Step in the environment
observation, reward, terminated, truncated, info = env.step(action_np)
obs_tensor = torch.tensor(observation, dtype=torch.float32)
log_probs.append(log_prob)
rewards.append(reward)
if terminated or truncated:
break
# Compute cumulative discounted rewards
R = 0
gamma = 0.99 # Discount factor
discounted_rewards = []
for r in rewards[::-1]:
R = r + gamma * R
discounted_rewards.insert(0, R)
discounted_rewards = torch.tensor(discounted_rewards)
# Normalize rewards
discounted_rewards = (discounted_rewards - discounted_rewards.mean()) / (
discounted_rewards.std() + 1e-8
)
# Compute loss
policy_losses = []
for log_prob, R in zip(log_probs, discounted_rewards):
policy_losses.append(-log_prob * R)
loss = torch.stack(policy_losses).sum()
# Perform backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_reward = sum(rewards)
print(f"Episode {episode + 1}\tTotal Reward: {total_reward}")
env.close()
def main():
model = NeuralNetwork()
model.load_state_dict(torch.load("pendulum_1.pt", weights_only=True))
# train(model)
# torch.save(model.state_dict(), "pendulum_1.pt")
env = gym.make("Pendulum-v1", render_mode="human")
observation, info = env.reset()
for step in range(300):
obs_tensor = torch.tensor(observation, dtype=torch.float32)
with torch.no_grad():
mean, _ = model(obs_tensor)
action = np.clip(mean.detach().numpy(), -2, 2)
print(action)
observation, reward, terminated, truncated, info = env.step(action)
if terminated or truncated:
observation, info = env.reset()
env.close()
if __name__ == "__main__":
main()
To improve the learning of your machine learning algorithm for continuous action spaces like the Pendulum-v1 environment, you can make several key adjustments to your code:
Adjust Standard Deviation Calculation:
F.sigmoid for the standard deviation (std) constrains it between 0 and 1, which is too restrictive for continuous control tasks.F.softplus to ensure that std is positive but not limited to a specific range. Alternatively, output log_std and exponentiate it to get std, which is a common practice in continuous action spaces.Code Changes:
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.linear_stack = nn.Sequential(
nn.Linear(3, 128),
nn.ReLU(),
nn.Linear(128, 128),
nn.ReLU()
)
self.mean = nn.Linear(128, 1)
self.log_std = nn.Linear(128, 1)
def forward(self, x):
x = self.linear_stack(x)
mean = self.mean(x)
log_std = self.log_std(x)
std = torch.exp(log_std)
return mean, std
Increase Neural Network Capacity:
Normalize Observations:
Code Changes:
# Assuming you have an observation scaler
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
# Fit the scaler on some initial data or the entire observation set
# Inside your training loop
observation = scaler.transform([observation])[0]
obs_tensor = torch.tensor(observation, dtype=torch.float32)
Adjust Learning Rate and Optimizer:
1e-3 or 1e-4.AdamW to Adam.Code Changes:
optimizer = optim.Adam(model.parameters(), lr=1e-4)
Handle Action Bounds Properly:
tanh to ensure actions are within bounds without clipping. Also, adjust the log probability calculation to account for this transformation.Code Changes:
# Sampling actions with tanh squashing
normal_distributions = torch.distributions.Normal(mean, std)
action_unbounded = normal_distributions.rsample()
action = torch.tanh(action_unbounded) * 2 # Scale to [-2, 2]
# Correct log probability calculation with Tanh transformation
log_prob = normal_distributions.log_prob(action_unbounded) - torch.log(1 - torch.tanh(action_unbounded).pow(2) + 1e-7)
Add Entropy Regularization:
Code Changes:
# Compute entropy
entropy = normal_distributions.entropy().mean()
entropy_weight = 0.01 # You can adjust this weight
# Modify loss function
loss = torch.stack(policy_losses).sum() - entropy_weight * entropy
Increase Training Episodes:
Consider Advanced Algorithms:
By making these changes, your agent should learn more effectively and perform better on the Pendulum-v1 environment.
Here's the updated training function incorporating the changes:
def train(model):
optimizer = optim.Adam(model.parameters(), lr=1e-4)
env = gym.make("Pendulum-v1")
for episode in range(1000): # Increased number of episodes
observation, info = env.reset()
log_probs = []
rewards = []
entropy_term = 0
for step in range(500):
obs_tensor = torch.tensor(observation, dtype=torch.float32)
mean, std = model(obs_tensor)
normal_distributions = torch.distributions.Normal(mean, std)
action_unbounded = normal_distributions.rsample()
action = torch.tanh(action_unbounded) * 2 # Scale action to [-2, 2]
log_prob = normal_distributions.log_prob(action_unbounded) - torch.log(1 - torch.tanh(action_unbounded).pow(2) + 1e-7)
entropy = normal_distributions.entropy()
observation, reward, terminated, truncated, info = env.step([action.item()])
log_probs.append(log_prob)
rewards.append(reward)
entropy_term += entropy
if terminated or truncated:
break
# Compute cumulative discounted rewards
R = 0
gamma = 0.99
discounted_rewards = []
for r in rewards[::-1]:
R = r + gamma * R
discounted_rewards.insert(0, R)
discounted_rewards = torch.tensor(discounted_rewards)
discounted_rewards = (discounted_rewards - discounted_rewards.mean()) / (discounted_rewards.std() + 1e-8)
# Compute loss
policy_losses = []
for log_prob, R in zip(log_probs, discounted_rewards):
policy_losses.append(-log_prob * R)
loss = torch.stack(policy_losses).sum() - 0.01 * entropy_term # Entropy regularization
# Perform backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_reward = sum(rewards)
print(f"Episode {episode + 1}\tTotal Reward: {total_reward}")
env.close()
By implementing these adjustments, you should see improved learning performance from your algorithm.
Not yet included in a published release.