import gym import numpy as np import matplotlib.pyplot as plt class GridWorld(gym.Env):…
- User
import gym import numpy as np import matplotlib.pyplot as plt
class GridWorld(gym.Env): def init(self): self.grid = np.array([ [-1, -1, -1, 0], [-1, 0, 0, 0], [-1, 0, 0, 0], [-1, -1, -1, 10] ])
self.observation_space = gym.spaces.Discrete(16) self.action_space = gym.spaces.Discrete(4) self.reward_range = (-5, 10) self.agent_pos = (0, 0) self.rewards = [] def step(self, action): # Get the current state and action current_state = self.agent_pos action = action # Calculate the next state if action == 0: # up next_state = (current_state[0] - 1, current_state[1]) elif action == 1: # down next_state = (current_state[0] + 1, current_state[1]) elif action == 2: # left next_state = (current_state[0], current_state[1] - 1) elif action == 3: # right next_state = (current_state[0], current_state[1] + 1) # Check if the next state is valid if next_state[0] < 0 or next_state[0] >= self.grid.shape[0] or next_state[1] < 0 or next_state[1] >= self.grid.shape[1]: next_state = current_state # Get the reward reward = self.grid[next_state[0]][next_state[1]] # Check if the episode is done done = reward == 10 # Update the agent's position self.agent_pos = next_state # Return the next state, reward, and done return next_state, reward, done def reset(self): # Reset the agent's position to the start self.agent_pos = (0, 0) return self.agent_pos def render(self): plt.figure(figsize=(5, 5)) # Add grid lines for each cell plt.grid(True, which='both', color='black', linewidth=5) plt.imshow(self.grid, cmap='viridis') plt.xticks([]) plt.yticks([]) # Mark start and end positions with text labels plt.text(0, 0, 'START', horizontalalignment='center', verticalalignment='center', fontsize=14, color='white') plt.text(3, 3, 'END', horizontalalignment='center', verticalalignment='center', fontsize=14, color='white') # Mark agent position with a red circle plt.scatter([self.agent_pos[1]], [self.agent_pos[0]], c='red', s=100) plt.show() def plot_rewards(self): plt.plot(self.rewards) plt.title("Rewards per Episode") plt.xlabel("Episode") plt.ylabel("Reward") plt.show() ------------------------------------------------environment--------------------------------------------------------------------------------------------------------------------------------import gym import numpy as np
Initialize environment, Q-table, and hyperparameters
env = GridWorld() n_states = env.observation_space.n n_actions = env.action_space.n Q = np.zeros((n_states, n_actions))
SARSA hyperparameters
- Assistant
- User
Now that i have implemented saarsa s you said it really worked well , Now i need to implement Part III: Solve your environment using Qlearning [30 points] In this part, we apply Q-learning algorithm to solve the env defined in Part 1. Q-learning is an off-policy reinforcement learning algorithm. It has many similarities with SARSA. The algorithm involves taking action in the current state, observing the reward and next state, and updating the Q-value estimate of the previous state-action pair based on the maximum expected Q-value of the next state. STEPS:
- Apply Q-learning algorithm to solve the environment that was defined in Part I. You can modify your code from Part II.
- Try hyperparameter tuning on at least two parameters to get better results for Qlearning. You explore some of the hyperparameter tuning libraries, e.g. Optuna or make it manually. Parameters to tune: f. Discount factor (γ) g. Epsilon decay rate h. Epsilon min/max values i. Number of episodes j. Max timesteps Try at least 3 different values for each of the parameters that you choose.
- Assistant
- User
I have to write the code for all the hyperparameters, which is a bit lengthy, can you give me a code with the hyperparameters change dynamic code
- Assistant
- User
It really worked, but now I need -------------------------three parameters to change ---------------------------------------------------------------------------------------------------------------case 1 default parameters -- Q1, rewards1, epsilon_values1 = run_q_learning(episodes=500, alpha=0.1, gamma=0.99, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100)
-- case 2 -- Gamma - a. 0.4, 0.8, 1 both epsion delay and total rewards graph ----case 3 - max_time_steps -- 25, 150, 200 - Assistant
I can certainly help you with that! Here's an example of how to run the
run_q_learningfunction with the given hyperparameter combinations for each of the three cases:Case 1: Default parameters - Already provided in the previous response. Repeating it here for clarity:
Q1, rewards1, epsilon_values1 = run_q_learning(episodes=500, alpha=0.1, gamma=0.99, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100)Case 2: Different gamma values - 0.4, 0.8, and 1:
Q2a, rewards2a, epsilon_values2a = run_q_learning(episodes=500, alpha=0.1, gamma=0.4, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100) Q2b, rewards2b, epsilon_values2b = run_q_learning(episodes=500, alpha=0.1, gamma=0.8, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100) Q2c, rewards2c, epsilon_values2c = run_q_learning(episodes=500, alpha=0.1, gamma=1.0, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100) - User
#Case 1: Default parameters
Q1, rewards1, epsilon_values1 = run_q_learning(episodes=500, alpha=0.1, gamma=0.99, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100)
#Case 2: Different gamma values - 0.4, 0.8, and 1:
Q2a, rewards2a, epsilon_values2a = run_q_learning(episodes=500, alpha=0.1, gamma=0.4, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100) Q2b, rewards2b, epsilon_values2b = run_q_learning(episodes=500, alpha=0.1, gamma=0.8, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100) Q2c, rewards2c, epsilon_values2c = run_q_learning(episodes=500, alpha=0.1, gamma=1.0, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=100)
#Case 3: Different max_timesteps values - 25, 150, and 200:
Q3a, rewards3a, epsilon_values3a = run_q_learning(episodes=500, alpha=0.1, gamma=0.99, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=25) Q3b, rewards3b, epsilon_values3b = run_q_learning(episodes=500, alpha=0.1, gamma=0.99, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=150) Q3c, rewards3c, epsilon_values3c = run_q_learning(episodes=500, alpha=0.1, gamma=0.99, epsilon=1.0, epsilon_decay=0.995, epsilon_min=0.01, max_timesteps=200)
Plot rewards and epsilon values for each example
plt.figure(figsize=(12, 6))-----------------------give the code to plot the same
- Assistant
Here's the code to plot the rewards and epsilon values for each of the cases:
plt.figure(figsize=(15, 15)) # Case 1: Default parameters plt.subplot(3, 3, 1) plt.plot(rewards1) plt.title("Case 1: Rewards per Episode") plt.subplot(3, 3, 4) plt.plot(epsilon_values1) plt.title("Case 1: Epsilon Decay per Episode") # Case 2: Different gamma values - 0.4, 0.8, and 1 plt.subplot(3, 3, 2) plt.plot(rewards2a) plt.title("Case 2 (gamma=0.4): Rewards per Episode") plt.subplot(3, 3, 5) plt.plot(epsilon_values2a) plt.title("Case 2 (gamma=0.4): Epsilon Decay per Episode") plt.subplot(3, 3, 3) plt.plot(rewards2b) plt.title("Case 2 (gamma=0.8): Rewards per Episode") plt.subplot(3, 3, 6) plt.plot(epsilon_values2b) plt.title("Case 2 (gamma=0.8): Epsilon Decay per Episode") plt.subplot(3, 3, 9) plt.plot(rewards2c) plt.title("Case 2 (gamma=1.0): Rewards per Episode") plt.subplot(3, 3, 12) plt.plot(epsilon_values2c) plt.title("Case 2 (gamma=1.0): Epsilon Decay per Episode") # Case 3: Different max_timesteps values - 25, 150, and 200 plt.subplot(3, 3, 7) plt.plot(rewards3a) plt.title("Case 3 (max_timesteps=25): Rewards per Episode") plt.subplot(3, 3, 10) plt.plot(epsilon_values3a) plt.title("Case 3 (max_timesteps=25): Epsilon Decay per Episode") plt.subplot(3, 3, 8) plt.plot(rewards3b) plt.title("Case 3 (max_timesteps=150): Rewards per Episode") plt.subplot(3, 3, 11) plt.plot(epsilon_values3b) plt.title("Case 3 (max_timesteps=150): Epsilon Decay per Episode") plt.subplot(3, 3, 9) plt.plot(rewards3c) plt.title("Case 3 (max_timesteps=200): Rewards per Episode") plt.subplot(3, 3, 12) plt.plot(epsilon_values3c) plt.title("Case 3 (max_timesteps=200): Epsilon Decay per Episode") # Adjust plot layout plt.tight_layout() plt.show() - User
- Assistant
Apologies for the confusion. The error is caused by an incorrect subplot index. The indices should be sequential for a 3x3 grid (i.e., 1 to 9), but the code mistakenly has 12 as an index. Here's the corrected plotting code:
plt.figure(figsize=(15, 15)) # Case 1: Default parameters plt.subplot(3, 3, 1) plt.plot(rewards1) plt.title("Case 1: Rewards per Episode") plt.subplot(3, 3, 4) plt.plot(epsilon_values1) plt.title("Case 1: Epsilon Decay per Episode") # Case 2: Different gamma values - 0.4, 0.8, and 1 plt.subplot(3, 3, 2) plt.plot(rewards2a) plt.title("Case 2 (gamma=0.4): Rewards per Episode") plt.subplot(3, 3, 5) plt.plot(epsilon_values2a) plt.title("Case 2 (gamma=0.4): Epsilon Decay per Episode") plt.subplot(3, 3, 3) plt.plot(rewards2b) plt.title("Case 2 (gamma=0.8): Rewards per Episode") plt.subplot(3, 3, 6) plt.plot(epsilon_values2b) plt.title("Case 2 (gamma=0.8): Epsilon Decay per Episode") plt.subplot(3, 3, 9) plt.plot(rewards2c) plt.title("Case 2 (gamma=1.0): Rewards per Episode") plt.subplot(3, 3, 7) plt.plot(epsilon_values2c) plt.title("Case 2 (gamma=1.0): Epsilon Decay per Episode") # Case 3: Different max_timesteps values - 25, 150, and 200 plt.subplot(3, 3, 8) plt.plot(rewards3a) plt.title("Case 3 (max_timesteps=25): Rewards per Episode") plt.subplot(3, 3, 11) plt.plot(epsilon_values3a) plt.title("Case 3 (max_timesteps=25): Epsilon Decay per Episode") plt.subplot(3, 3, 9) plt.plot(rewards3b) plt.title("Case 3 (max_timesteps=150): Rewards per Episode") plt.subplot(3, 3, 12) plt.plot(epsilon_values3b) plt.title("Case 3 (max_timesteps=150): Epsilon Decay per Episode") plt.subplot(3, 3, 10) plt.plot(rewards3c) plt.title("Case 3 (max_timesteps=200): Rewards per Episode") plt.subplot(3, 3, 13) plt.plot(epsilon_values3c)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.