import math def tabularpolicylearning(env_name="MiniGrid-Empty-8x8-v0", episodes=5000,…
- User
import math
def tabular_policy_learning(env_name="MiniGrid-Empty-8x8-v0", episodes=5000, alpha=0.1, gamma=0.99): """ ✅ Implementing Tabular Policy Learning using Softmax Policy - Uses a policy table to store action probabilities for each state. - Updates policy using a policy gradient (REINFORCE-like update). - Uses softmax action selection for exploration. """ env = gym.make(env_name) # TODO: Initialize an empty policy table to store action probabilities. policy_table = {}
rewards_per_episode = [] def get_state(env): """✅ Extracts the state representation from the MiniGrid environment.""" agent_pos = tuple(env.agent_pos) direction = env.agent_dir return (agent_pos, direction) def softmax(x): """✅ Compute softmax values for an array.""" exp_x = np.exp(x - np.max(x)) # Numeric stability return exp_x / exp_x.sum() for episode in range(episodes): obs, _ = env.reset() state = get_state(env) done = False total_reward = 0 trajectory = [] # Store (state, action, reward) for policy update while not done: # TODO: Initialize the state in the policy table if it is not already present. if state not in policy_table: policy_table[state] = np.ones(env.action_space.n) / env.action_space.n # TODO: Select action using the softmax policy. action_probs = policy_table[state] action = np.random.choice(env.action_space.n, p=action_probs) # TODO: Execute the action and observe the next state and reward. obs, reward, done, truncated, _ = env.step(action) next_state = get_state(env) total_reward += reward # TODO: Initialize next_state in the policy table if it is not already present. if next_state not in policy_table: policy_table[next_state] = np.ones(env.action_space.n) / env.action_space.n # Store transition for policy update trajectory.append((state, action, reward)) # Update state state = next_state rewards_per_episode.append(total_reward) # ✅ **Policy Update (REINFORCE-like)** G = 0 # Return (discounted sum of rewards) for t in reversed(range(len(trajectory))): state, action, reward = trajectory[t] G = reward + gamma * G # Discounted reward # TODO: Update policy table using policy gradient policy_table[state][action] += alpha * (G - np.sum(policy_table[state])) * action_probs[action] if (episode + 1) % 100 == 0: avg_reward = np.mean(rewards_per_episode[-100:]) print(f"Episode {episode + 1}/{episodes}, Avg Reward: {avg_reward:.4f}") env.close() return policy_table, rewards_per_episodeI want to implement a function for policy based learning, but I realized that I never use softmax function, how to apply it? You just need to look at "TODO" section, other part is guarunteed to work.
- Assistant
You're right! The softmax function isn't currently being used. To apply it properly, you should use it when selecting an action based on the policy table and when updating the policy table to ensure probabilities remain valid. Changes needed:
Apply softmax when selecting an action:
Instead of directly using policy_table[state] as probabilities, apply softmax(policy_table[state]) to ensure it's a valid probability distribution.
Apply softmax after updating the policy table:
After modifying policy_table[state][action], apply softmax again to normalize the action probabilities.
Updated TODO Sections: 1️⃣ Select action using softmax: Modify this part: python複製編輯action_probs = policy_table[state]
To: python複製編輯action_probs = softmax(policy_table[state]) # Ensure probabilities are valid
2️⃣ Update policy table and normalize with softmax: Modify this part: python複製編輯policy_table[state][action] += alpha * (G - np.sum(policy_table[state])) * action_probs[action]
To: python複製編輯policy_table[state][action] += alpha * (G - np.sum(policy_table[state])) * action_probs[action] policy_table[state] = softmax(policy_table[state]) # Normalize after update