[python] python

Viewer

  1. import argparse
  2. import numpy as np
  3.  
  4. from environment import MountainCar, GridWorld
  5.  
  6. """
  7. Please read: THE ENVIRONMENT INTERFACE
  8.  
  9. In this homework, we provide the environment (either MountainCar or GridWorld) 
  10. to you. The environment returns states, represented as 1D numpy arrays, rewards, 
  11. and a Boolean flag indicating whether the episode has terminated. The environment 
  12. accepts actions, represented as integers.
  13.  
  14. The only file you need to modify/read is this one. We describe the environment 
  15. interface below.
  16.  
  17. class Environment: # either MountainCar or GridWorld
  18.  
  19.     def __init__(self, mode, debug=False):
  20.         Initialize the environment with the mode, which can be either "raw" 
  21.         (for the raw state representation) or "tile" (for the tiled state 
  22.         representation). The raw state representation contains the position and 
  23.         velocity; the tile representation contains zeroes for the non-active 
  24.         tile indices and ones for the active indices. GridWorld must be used in 
  25.         tile mode. The debug flag will log additional information for you; 
  26.         make sure that this is turned off when you submit to the autograder.
  27.  
  28.         self.state_space = an integer representing the size of the state vector
  29.         self.action_space = an integer representing the range for the valid actions
  30.  
  31.         You should make use of env.state_space and env.action_space when creating 
  32.         your weight matrix.
  33.  
  34.     def reset(self):
  35.         Resets the environment to initial conditions. Returns:
  36.  
  37.             (1) state : A numpy array of size self.state_space, representing 
  38.                         the initial state.
  39.     
  40.     def step(self, action):
  41.         Updates itself based on the action taken. The action parameter is an 
  42.         integer in the range [0, 1, ..., self.action_space). Returns:
  43.  
  44.             (1) state : A numpy array of size self.state_space, representing 
  45.                         the new state that the agent is in after taking its 
  46.                         specified action.
  47.             
  48.             (2) reward : A float indicating the reward received at this step.
  49.  
  50.             (3) done : A Boolean flag indicating whether the episode has 
  51.                         terminated; if this is True, you should reset the 
  52.                         environment and move on to the next episode.
  53.     
  54.     def render(self, mode="human"):
  55.         Renders the environment at the current step. Only supported for MountainCar.
  56.  
  57.  
  58. For example, for the GridWorld environment, you could do:
  59.  
  60.     env = GridWorld(mode="tile")
  61.  
  62. Then, you can initialize your weight matrix to all zeroes with shape 
  63. (env.action_space, env.state_space+1) (if you choose to fold the bias term in). 
  64. Note that the states returned by the environment do *not* have the bias term 
  65. folded in.
  66. """
  67.  
  68. def parse_args() -> tuple:
  69.     """
  70.     Parses all args and returns them. Returns:
  71.  
  72.         (1) env_type : A string, either "mc" or "gw" indicating the type of 
  73.                     environment you should use
  74.         (2) mode : A string, either "raw" or "tile"
  75.         (3) weight_out : The output path of the file containing your weights
  76.         (4) returns_out : The output path of the file containing your returns
  77.         (5) episodes : An integer indicating the number of episodes to train for
  78.         (6) max_iterations : An integer representing the max number of iterations 
  79.                     your agent should run in each episode
  80.         (7) epsilon : A float representing the epsilon parameter for 
  81.                     epsilon-greedy action selection
  82.         (8) gamma : A float representing the discount factor gamma
  83.         (9) lr : A float representing the learning rate
  84.     
  85.     Usage:
  86.         env_type, mode, weight_out, returns_out, episodes, max_iterations, epsilon, gamma, lr = parse_args()
  87.     """
  88.     parser = argparse.ArgumentParser()
  89.     parser.add_argument("env", type=str, choices=["mc", "gw"])
  90.     parser.add_argument("mode", type=str, choices=["raw", "tile"])
  91.     parser.add_argument("weight_out", type=str)
  92.     parser.add_argument("returns_out", type=str)
  93.     parser.add_argument("episodes", type=int)
  94.     parser.add_argument("max_iterations", type=int)
  95.     parser.add_argument("epsilon", type=float)
  96.     parser.add_argument("gamma", type=float)
  97.     parser.add_argument("learning_rate", type=float)
  98.  
  99.     args = parser.parse_args()
  100.  
  101.     return args.env, args.mode, args.weight_out, args.returns_out, args.episodes, args.max_iterations, args.epsilon, args.gamma, args.learning_rate
  102.  
  103.     
  104.  
  105. def select_action(weights, state, epsilon, action_space):
  106.     random_number = np.random.uniform(0, 1)
  107.     picked_action = 0
  108.     best_action = 0
  109.     if random_number < epsilon:
  110.         picked_action = np.random.randint(0, action_space)
  111.         results = np.matmul(weights, state, dtype=np.float64)
  112.         best_action = np.argmax(results)
  113.     else:
  114.         results = np.matmul(weights, state, dtype=np.float64)
  115.         picked_action = np.argmax(results)
  116.         best_action = np.argmax(results)
  117.  
  118.         temp_all = []
  119.         for i in range(action_space):
  120.             temp = np.dot(state, weights[i])
  121.             temp_all.append(temp)
  122.         temp_all = np.array(temp_all, dtype=np.float64)
  123.  
  124.         # print("results = ", results)
  125.         # print("temp_all = ", temp_all)
  126.  
  127.     return picked_action, best_action
  128.  
  129.  
  130. def select_action_next(weights, state, epsilon, action_space):
  131.     results = np.matmul(weights, state, dtype=np.float64)
  132.     picked_action = np.argmax(results)
  133.  
  134.     return picked_action
  135.  
  136.  
  137.  
  138. if __name__ == "__main__":
  139.  
  140.     env_type, mode, weight_out, returns_out, episodes, max_iterations, epsilon, gamma, lr = parse_args()
  141.  
  142.     if env_type == "mc":
  143.         env = MountainCar(mode=mode) 
  144.     elif env_type == "gw":
  145.         env = GridWorld(mode=mode) 
  146.     elseraise Exception(f"Invalid environment type {env_type}")
  147.  
  148.  
  149.     weights = np.zeros((env.action_space, env.state_space+1), dtype=np.float64) 
  150.     all_rewards = []
  151.  
  152.     for episode in range(episodes):
  153.  
  154.         # Get the initial state by calling env.reset()
  155.         cur_state = env.reset()
  156.         cur_state = np.insert(cur_state, 0, 1) # bias's term's correspoding state value should be 1 at position 0
  157.         cur_reward = 0
  158.  
  159.         for iteration in range(max_iterations):
  160.  
  161.             # Select an action based on the state via the epsilon-greedy strategy
  162.             selected_action, best_action = select_action(weights, cur_state, epsilon, env.action_space)
  163.             
  164.             # Take a step in the environment with this action, and get the 
  165.             # returned next state, reward, and done flag
  166.             next_state, reward, done = env.step(best_action)
  167.             next_state = np.insert(next_state, 0, 1)
  168.  
  169.             # Using the original state, the action, the next state, and 
  170.             # the reward, update the parameters. Don't forget to update the 
  171.             # bias term!
  172.             selected_action_next = select_action_next(weights, next_state, epsilon, env.action_space)
  173.             
  174.             weights[best_action] = weights[best_action] - lr * (np.dot(cur_state, weights[best_action]) - (reward + gamma * np.dot(next_state, weights[selected_action_next]))) * cur_state
  175.             # weights[selected_action] = weights[selected_action] - lr * (np.dot(cur_state, weights[selected_action]) - (reward + gamma * np.dot(next_state, weights[selected_action_next]))) * cur_state
  176.  
  177.             cur_reward += reward
  178.  
  179.             # Remember to break out of this inner loop if the environment signals done!
  180.             if done:
  181.                 break
  182.             
  183.             cur_state = next_state
  184.  
  185.         all_rewards.append(cur_reward)
  186.     
  187.  
  188.     # Save your weights and returns. The reference solution uses 
  189.     # np.savetxt(..., fmt="%.18e", delimiter=" ")
  190.     np.savetxt(returns_out, all_rewards, delimiter=' ')
  191.     np.savetxt(weight_out, weights, delimiter=' ')
  192.  
  193.  

Editor

You can edit this paste and save as new:


File Description
  • python
  • Paste Code
  • 02 Dec-2022
  • 7.86 Kb
You can Share it: