in the below code i need to add two attributes(minimum reward value in that episode and maximum reward value in that episode) from each episode, in the following logging file and metrics_log file
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Check if a previous training state exists and load it
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode']
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
node_features_tensor, edge_index, performance_metrics = env.reset()
state = (node_features_tensor, edge_index)
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
start_time2 = time.time()
for t in range(max_timesteps):
start_time1 = time.time()
# Selecting action based on the current state
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
start_time = time.time()
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics)
end_time = time.time()
runtime = end_time - start_time
print(f"runtime: {runtime} seconds")
next_state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(state[0]).item()) # Ensure Critic can handle state format
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
end_time1 = time.time()
runtime1 = end_time1 - start_time1
print(f"runtime1: {runtime1} seconds")
if done:
break
next_value = agent.critic(state[0]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
# Correcting format for updating the policy
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
# Update the policy with collected data
average_loss_actor, average_loss_critic = agent.update_policy(states, actions, log_probs, returns, advantages)
episode_length = len(episode_rewards)
total_reward = sum(episode_rewards)
# Compute mean episode reward and deployment accuracy (example placeholders)
mean_episode_reward = total_reward / episode_length
deployment_accuracy = calculate_accuracy(perf_metrics_log)
# Log episode information
print(f'Episode {episode + 1}/{num_episodes}, Total Reward: {total_reward}')
# Logging
logging.info(f"Episode {episode + 1} - Reward: {total_reward}, Length: {episode_length}, Actor Loss: {average_loss_actor}, Critic Loss: {average_loss_critic}")
logging.info(f"Episode {episode + 1} - Mean Episode Reward: {mean_episode_reward}, Deployment Accuracy: {deployment_accuracy}")
# Append to logs for pandas DataFrame
rewards_log.append({'episode': episode + 1, 'total_reward': total_reward})
losses_log.append({'episode': episode + 1, 'actor_loss': average_loss_actor, 'critic_loss': average_loss_critic})
metrics_log.append({'episode': episode + 1, 'Mean Episode Reward': mean_episode_reward, 'Deployment Accuracy': deployment_accuracy})
episode_lengths.append(episode_length)
To add the minimum reward and maximum reward value in the episode to the logging and metrics_log, you only need to compute the minimum and maximum reward values from the episode_rewards list at the end of each episode and then include them in the logging and metrics logs.
Here's the updated code with the modifications:
python
import logging
import time
import torch
def train(env, agent, num_episodes, max_timesteps):
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Check if a previous training state exists and load it
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode']
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
node_features_tensor, edge_index, performance_metrics = env.reset()
state = (node_features_tensor, edge_index)
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
start_time2 = time.time()
for t in range(max_timesteps):
start_time1 = time.time()
# Selecting action based on the current state
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
start_time = time.time()
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics)
end_time = time.time()
runtime = end_time - start_time
print(f"runtime: {runtime} seconds")
next_state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(state[0]).item()) # Ensure Critic can handle state format
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
end_time1 = time.time()
runtime1 = end_time1 - start_time1
print(f"runtime1: {runtime1} seconds")
if done:
break
next_value = agent.critic(state[0]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
# Correcting format for updating the policy
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
# Update the policy with collected data
average_loss_actor, average_loss_critic = agent.update_policy(states, actions, log_probs, returns, advantages)
episode_length = len(episode_rewards)
total_reward = sum(episode_rewards)
# Compute mean episode reward and deployment accuracy (example placeholders)
mean_episode_reward = total_reward / episode_length
deployment_accuracy = calculate_accuracy(perf_metrics_log)
# Compute minimum and maximum episode rewards
min_episode_reward = min(episode_rewards)
max_episode_reward = max(episode_rewards)
# Log episode information
print(f'Episode {episode + 1}/{num_episodes}, Total Reward: {total_reward}')
# Logging
logging.info(f"Episode {episode + 1} - Reward: {total_reward}, Length: {episode_length}, Actor Loss: {average_loss_actor}, Critic Loss: {average_loss_critic}")
logging.info(f"Episode {episode + 1} - Mean Episode Reward: {mean_episode_reward}, Deployment Accuracy: {deployment_accuracy}")
logging.info(f"Episode {episode + 1} - Min Episode Reward: {min_episode_reward}, Max Episode Reward: {max_episode_reward}")
# Append to logs for pandas DataFrame
rewards_log.append({'episode': episode + 1, 'total_reward': total_reward})
losses_log.append({'episode': episode + 1, 'actor_loss': average_loss_actor, 'critic_loss': average_loss_critic})
metrics_log.append({'episode': episode + 1, 'Mean Episode Reward': mean_episode_reward, 'Deployment Accuracy': deployment_accuracy, 'Min Episode Reward': min_episode_reward, 'Max Episode Reward': max_episode_reward})
episode_lengths.append(episode_length)
In this updated code, the minimum and maximum rewards are computed using the Python built-in min() and max() functions on the episode_rewards list, and then these values are logged and added to the metrics_log.