Reinforcement Learning_ Part 10_ Policy-Gradient Methods — REINFORCE, Actor-Critic _ by…
- User
Reinforcement Learning_ Part 10_ Policy-Gradient Methods — REINFORCE, Actor-Critic _ by Mehul Jain _ Medium.pdfPDFLook at the document and check the idea of policy-based learning and softmax policy and help me to implement the following code:
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[0], agent_pos[1], 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 = 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 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_episodeNotice that you only need to check the code under "TODO" part, other thing is most guarunteed to work well, but if you have problem, just let me know.
- Assistant
The document you provided discusses policy-gradient methods, including the REINFORCE algorithm and softmax-based policies. Here’s how you can complete the missing parts in your code:
- Initialize the state in the policy table python複製編輯if state not in policy_table: policy_table[state] = np.ones(env.action_space.n) / env.action_space.n
You already included this correctly.
- Select action using softmax policy To select an action using the softmax probabilities, we need to compute action probabilities using the softmax function: python複製編輯action_probs = softmax(policy_table[state]) # Compute softmax over action probabilities action = np.random.choice(env.action_space.n, p=action_probs)
- User
The code seems to run very slow after some episode like 14 or 15. It stuck at 17 episodes now. Why would this happen?
- Assistant
- User
I find a problem that size of trajectory grows quite large on some episode, what is the problen here?
- Assistant
- User
If the machine correctly converge, what should I see in the trend of size of trajectory?
- Assistant
- User
I find the problem that is the agent will doing useless action before going in to the goal so the action before gain reward unitentionally. For example, hitting a wall or doing something useless in action space(like picking up a key when the environment doesn't include any key).
So first, the reward function in the api is "1 - 0.9 * (step_count / max_steps)’ is given for success, and ‘0’ for failure". Do my implication about useless action correct?
Second, since it result in 0 on failure. Will this effect learning when I truncate trajectory that is too long and do useless actions?
- Assistant