def tabularqlearningadjust(envname="MiniGrid-DoorKey-5x5-v0", episodes=10000, alpha=0.1,…
- User
def tabular_q_learning_adjust(env_name="MiniGrid-DoorKey-5x5-v0", episodes=10000, alpha=0.1, gamma=0.99, epsilon_start=1.0, epsilon_end=0.1, decay_rate=0.9999, reward_shaping=True, q_table=None, debug=False): """ ✅ Implement Tabular Q-learning with Reward Shaping - Modify reward shaping to accelerate learning. - Adjust epsilon decay to ensure sufficient exploration. - Ensure the agent learns the full sequence: "pick up key → open door → reach goal". """ env = gym.make(env_name)
if q_table is None: q_table = {} rewards_per_episode = [] epsilon = epsilon_start def get_state(env, prev_door_open): """✅ Extract the agent's state (position, direction, key possession, and door status).""" # TODO: Represent the state using agent position, direction, key possession, and door status. for episode in range(episodes): obs, _ = env.reset() state = get_state(env, False) # Initially, the door is closed. done = False total_reward = 0 prev_has_key = state[2] prev_door_open = state[3] episode_step = 0 while not done: # TODO: Initialize the state in the Q-table if not already present. # TODO: Implement ε-greedy policy for action selection. # Execute the selected action. prev_carrying = env.carrying obs, reward, done, truncated, _ = env.step(action) next_state = get_state(env, prev_door_open) episode_step += 1 # ✅ TODO: Implement reward shaping. # Update total reward. reward += shaped_reward total_reward += reward # TODO: Initialize the next state in the Q-table if not already present. # TODO: Apply Q-learning update rule (Bellman equation). # Move to the next state. state = next_state rewards_per_episode.append(total_reward) epsilon = max(epsilon_end, epsilon * decay_rate) if (episode + 1) % 100 == 0: avg_reward = np.mean(rewards_per_episode[-100:]) print(f"🚀 Episode {episode + 1}/{episodes}, Average Reward: {avg_reward:.2f}, Epsilon: {epsilon:.3f}") env.close() return q_table, rewards_per_episodeThis is a more complex environment where q learning will not work, so I need to do reward shaping. Can you help me to fill the "TODO"s?
- Assistant