Loading

IIT-M RL-ASSIGNMENT-2-GRIDWORLD

Solution for submission 132364

A detailed solution for submission 132364 submitted for challenge IIT-M RL-ASSIGNMENT-2-GRIDWORLD

nachiket_dev_me18b017

What is the notebook about?

Problem - Gridworld Environment Algorithms

This problem deals with a grid world and stochastic actions. The tasks you have to do are:

  • Implement Policy Iteration
  • Implement Value Iteration
  • Implement TD lamdda
  • Visualize the results
  • Explain the results

How to use this notebook? 📝

  • This is a shared template and any edits you make here will not be saved.You should make a copy in your own drive. Click the "File" menu (top-left), then "Save a Copy in Drive". You will be working in your copy however you like.

  • Update the config parameters. You can define the common variables here

Variable Description
AICROWD_DATASET_PATH Path to the file containing test data. This should be an absolute path.
AICROWD_RESULTS_DIR Path to write the output to.
AICROWD_ASSETS_DIR In case your notebook needs additional files (like model weights, etc.,), you can add them to a directory and specify the path to the directory here (please specify relative path). The contents of this directory will be sent to AIcrowd for evaluation.
AICROWD_API_KEY In order to submit your code to AIcrowd, you need to provide your account's API key. This key is available at https://www.aicrowd.com/participants/me

Setup AIcrowd Utilities 🛠

We use this to bundle the files for submission and create a submission on AIcrowd. Do not edit this block.

In [219]:
!pip install aicrowd-cli > /dev/null

AIcrowd Runtime Configuration 🧷

Get login API key from https://www.aicrowd.com/participants/me

In [220]:
import os

AICROWD_DATASET_PATH = os.getenv("DATASET_PATH", os.getcwd()+"/a5562c7d-55f0-4d06-841c-110655bb04ec_a2_gridworld_inputs.zip")
AICROWD_RESULTS_DIR = os.getenv("OUTPUTS_DIR", "results")
In [221]:

API Key valid
Saved API Key successfully!
a5562c7d-55f0-4d06-841c-110655bb04ec_a2_gridworld_inputs.zip: 100% 14.2k/14.2k [00:00<00:00, 518kB/s]
In [222]:
!unzip -q $AICROWD_DATASET_PATH
replace inputs/inputs_base.npy? [y]es, [n]o, [A]ll, [N]one, [r]ename: A
In [223]:
DATASET_DIR = 'inputs/'

GridWorld Environment

Read the code for the environment thoroughly

Do not edit the code for the environment

In [224]:
import numpy as np

class GridEnv_HW2:
    def __init__(self, 
                 goal_location, 
                 action_stochasticity,
                 non_terminal_reward,
                 terminal_reward,
                 grey_in,
                 brown_in,
                 grey_out,
                 brown_out
                ):

        # Do not edit this section 
        self.action_stochasticity = action_stochasticity
        self.non_terminal_reward = non_terminal_reward
        self.terminal_reward = terminal_reward
        self.grid_size = [10, 10]

        # Index of the actions 
        self.actions = {'N': (1, 0), 
                        'E': (0,1),
                        'S': (-1,0), 
                        'W': (0,-1)}
        
        self.perpendicular_order = ['N', 'E', 'S', 'W']
        
        l = ['normal' for _ in range(self.grid_size[0]) ]
        self.grid = np.array([l for _ in range(self.grid_size[1]) ], dtype=object)

        self.grid[goal_location[0], goal_location[1]] = 'goal'
        self.goal_location = goal_location

        for gi in grey_in:
            self.grid[gi[0],gi[1]] = 'grey_in'
        for bi in brown_in:    
            self.grid[bi[0], bi[1]] = 'brown_in'

        for go in grey_out:    
            self.grid[go[0], go[1]] = 'grey_out'
        for bo in brown_out:    
            self.grid[bo[0], bo[1]] = 'brown_out'

        self.grey_outs = grey_out
        self.brown_outs = brown_out

    def _out_of_grid(self, state):
        if state[0] < 0 or state[1] < 0:
            return True
        elif state[0] > self.grid_size[0] - 1:
            return True
        elif state[1] > self.grid_size[1] - 1:
            return True
        else:
            return False

    def _grid_state(self, state):
        return self.grid[state[0], state[1]]        
        
    def get_transition_probabilites_and_reward(self, state, action):
        """ 
        Returns the probabiltity of all possible transitions for the given action in the form:
        A list of tuples of (next_state, probability, reward)
        Note that based on number of state and action there can be many different next states
        Unless the state is All the probabilities of next states should add up to 1
        """

        grid_state = self._grid_state(state)
        
        if grid_state == 'goal':
            return [(self.goal_location, 1.0, 0.0)]
        elif grid_state == 'grey_in':
            npr = []
            for go in self.grey_outs:
                npr.append((go, 1/len(self.grey_outs), 
                            self.non_terminal_reward))
            return npr
        elif grid_state == 'brown_in':
            npr = []
            for bo in self.brown_outs:
                npr.append((bo, 1/len(self.brown_outs), 
                            self.non_terminal_reward))
            return npr
        
        direction = self.actions.get(action, None)
        if direction is None:
            raise ValueError("Invalid action %s , please select among" % action, list(self.actions.keys()))

        dir_index = self.perpendicular_order.index(action)
        wrap_acts = self.perpendicular_order[dir_index:] + self.perpendicular_order[:dir_index]
        next_state_probs = {}
        for prob, a in zip(self.action_stochasticity, wrap_acts):
            d = self.actions[a]
            next_state = (state[0] + d[0]), (state[1] + d[1])
            if self._out_of_grid(next_state):
                next_state = state
            next_state_probs.setdefault(next_state, 0.0)
            next_state_probs[next_state] += prob

        npr = []
        for ns, prob in next_state_probs.items():
            next_grid_state = self._grid_state(ns)
            reward = self.terminal_reward if next_grid_state == 'goal' else self.non_terminal_reward
            npr.append((ns, prob, reward))

        return npr

    def step(self, state, action):
        npr = self.get_transition_probabilites_and_reward(state, action)
        probs = [t[1] for t in npr]
        sampled_idx = np.random.choice(range(len(npr)), p=probs)
        sampled_npr = npr[sampled_idx]
        next_state = sampled_npr[0]
        reward = sampled_npr[2]
        is_terminal = next_state == tuple(self.goal_location)
        return next_state, reward, is_terminal

Example environment

This has the same setup as the pdf, do not edit the settings

In [225]:
def get_base_kwargs():
    goal_location = (9,9)
    action_stochasticity = [0.8, 0.2/3, 0.2/3, 0.2/3]
    grey_out = [(3,2), (4,2), (5,2), (6,2)]
    brown_in = [(9,7)]
    grey_in = [(0,0)]
    brown_out = [(1,7)]
    non_terminal_reward = 0
    terminal_reward = 10

    base_kwargs =  {"goal_location": goal_location, 
            "action_stochasticity": action_stochasticity,
            "brown_in": brown_in, 
            "grey_in": grey_in, 
            "brown_out": brown_out,
            "non_terminal_reward": non_terminal_reward,
            "terminal_reward": terminal_reward,
            "grey_out": grey_out,}
    
    return base_kwargs

base_kwargs = get_base_kwargs()

Task 2.1 - Value Iteration

Run value iteration on the environment and generate the policy and expected reward

In [226]:
def value_iteration(env, gamma):
    # Initial Values
    values = np.zeros((10, 10))
    values_list=[]

    # Initial policy
    policy = np.empty((10, 10), object)
    policy[:] = 'N' # Make all the policy values as 'N'

    # Begin code here
    iter=0
    while True:
      iter+=1
      delta = 0
      values_old = values.copy()
      values_list.append(values_old)
      for x in range(10):
        for y in range(10):
          values_temp={'N': 0,
                       'E': 0,
                       'S': 0,
                       'W': 0}
          for a in env.actions.keys():
            ns_prob_reward = env.get_transition_probabilites_and_reward((x,y),a)
            for (ns, prob, reward) in ns_prob_reward:
              value_temp= prob*( reward + gamma*values_old[ns[0],ns[1]] )
              values_temp[a] += value_temp
          action=max(values_temp,key=values_temp.get)
          policy[x,y]=action
          values[x,y] = values_temp[action]
          delta = max(delta,abs(values[x,y]-values_old[x,y]))
      if delta < 1e-8:
        break


        



    # Put your extra information needed for plots etc in this dictionary
    extra_info = {"list":values_list,'Iter':iter-1}

    # End code

    # Do not change the number of output values
    return {"Values": values, "Policy": policy}, extra_info
In [227]:
env = GridEnv_HW2(**base_kwargs)
res, extra_info = value_iteration(env, 0.7)

 # The rounding off is just for making print statement cleaner
print(np.flipud(np.round(res['Values'], decimals=2)))
print(np.flipud(res['Policy']))
[[0.1  0.15 0.24 0.37 0.56 0.86 1.29 0.12 8.68 0.  ]
 [0.13 0.2  0.31 0.5  0.81 1.31 2.12 3.43 5.75 8.95]
 [0.1  0.16 0.25 0.39 0.62 0.97 1.52 2.38 3.7  5.61]
 [0.07 0.11 0.17 0.26 0.41 0.64 0.99 1.54 2.38 3.52]
 [0.05 0.07 0.11 0.17 0.27 0.41 0.64 0.99 1.53 2.21]
 [0.03 0.05 0.07 0.11 0.17 0.27 0.41 0.64 0.98 1.39]
 [0.02 0.03 0.05 0.07 0.11 0.17 0.27 0.41 0.63 0.87]
 [0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.27 0.4  0.55]
 [0.04 0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.26 0.35]
 [0.07 0.04 0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.22]]
[['E' 'E' 'E' 'E' 'E' 'S' 'S' 'N' 'E' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N']
 ['N' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N' 'N']
 ['N' 'E' 'E' 'E' 'E' 'E' 'N' 'N' 'N' 'N']
 ['N' 'N' 'E' 'E' 'E' 'N' 'N' 'N' 'N' 'N']
 ['S' 'N' 'E' 'E' 'E' 'N' 'N' 'N' 'N' 'N']
 ['S' 'S' 'E' 'E' 'E' 'E' 'N' 'N' 'N' 'N']
 ['N' 'W' 'W' 'E' 'E' 'E' 'E' 'N' 'N' 'N']]
In [228]:
"""
2.1

[[0.1  0.15 0.24 0.37 0.56 0.86 1.29 0.12 8.68 0.  ]
 [0.13 0.2  0.31 0.5  0.81 1.31 2.12 3.43 5.75 8.95]
 [0.1  0.16 0.25 0.39 0.62 0.97 1.52 2.38 3.7  5.61]
 [0.07 0.11 0.17 0.26 0.41 0.64 0.99 1.54 2.38 3.52]
 [0.05 0.07 0.11 0.17 0.27 0.41 0.64 0.99 1.53 2.21]
 [0.03 0.05 0.07 0.11 0.17 0.27 0.41 0.64 0.98 1.39]
 [0.02 0.03 0.05 0.07 0.11 0.17 0.27 0.41 0.63 0.87]
 [0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.27 0.4  0.55]
 [0.04 0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.26 0.35]
 [0.07 0.04 0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.22]]

 is the optimal policy for VI
 """
Out[228]:
'\n2.1\n\n[[0.1  0.15 0.24 0.37 0.56 0.86 1.29 0.12 8.68 0.  ]\n [0.13 0.2  0.31 0.5  0.81 1.31 2.12 3.43 5.75 8.95]\n [0.1  0.16 0.25 0.39 0.62 0.97 1.52 2.38 3.7  5.61]\n [0.07 0.11 0.17 0.26 0.41 0.64 0.99 1.54 2.38 3.52]\n [0.05 0.07 0.11 0.17 0.27 0.41 0.64 0.99 1.53 2.21]\n [0.03 0.05 0.07 0.11 0.17 0.27 0.41 0.64 0.98 1.39]\n [0.02 0.03 0.05 0.07 0.11 0.17 0.27 0.41 0.63 0.87]\n [0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.27 0.4  0.55]\n [0.04 0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.26 0.35]\n [0.07 0.04 0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.22]]\n\n is the optimal policy for VI\n '

Task 2.2 - Policy Iteration

Run policy iteration on the environment and generate the policy and expected reward

In [229]:
def policy_iteration(env, gamma):
    # Initial Values
    values = np.zeros((10, 10))

    # Initial policy
    policy = np.empty((10, 10), object)
    policy[:] = 'N' # Make all the policy values as 'N'

    # Begin code here
    i=0 
    values_list=[]
    flag = False

    while not flag:
      i=i+1   
      #policy evalutation part
      while True:
        delta=0
        values_old=values.copy()
        for x in range(10):
          for y in range(10):
            values[x,y]=0
            a=policy[x,y]
            ns_prob_reward = env.get_transition_probabilites_and_reward((x,y),a)
            for (ns, prob, reward) in ns_prob_reward:
              values[x,y]+= prob*( reward + gamma*values_old[ns[0],ns[1]] )
            delta=max(delta,abs(values[x,y]-values_old[x,y]))
        if delta <= 1e-8:     
          break


      #policy improvement part
      flag= True
      for x in range(10):
        for y in range(10):
          values_temp={ 'N': 0, 'E': 0,'S': 0, 'W': 0}
          for a in env.actions.keys():
              ns_prob_reward = env.get_transition_probabilites_and_reward((x,y),a)
              for (ns, prob, reward) in ns_prob_reward:
                value_temp= prob*( reward + gamma*values[ns[0],ns[1]] )
                values_temp[a] += value_temp

          action=max(values_temp,key=values_temp.get)
          policy_action=policy[x,y]
          
          if policy_action != action :

              policy[x,y]=action
              flag = False
      values_list.append(values.copy())


    
    # Put your extra information needed for plots etc in this dictionary
    extra_info = {"Iter":i,'list':values_list}

    # End code

    # Do not change the number of output values
    return {"Values": values, "Policy": policy}, extra_info
In [230]:
env = GridEnv_HW2(**base_kwargs)
res, extra_info = policy_iteration(env, 0.7)

 # The rounding off is just for making print statement cleaner
print(np.flipud(np.round(res['Values'], decimals=2)))
print(np.flipud(res['Policy']))
print(extra_info["Iter"])
[[0.1  0.15 0.24 0.37 0.56 0.86 1.29 0.12 8.68 0.  ]
 [0.13 0.2  0.31 0.5  0.81 1.31 2.12 3.43 5.75 8.95]
 [0.1  0.16 0.25 0.39 0.62 0.97 1.52 2.38 3.7  5.61]
 [0.07 0.11 0.17 0.26 0.41 0.64 0.99 1.54 2.38 3.52]
 [0.05 0.07 0.11 0.17 0.27 0.41 0.64 0.99 1.53 2.21]
 [0.03 0.05 0.07 0.11 0.17 0.27 0.41 0.64 0.98 1.39]
 [0.02 0.03 0.05 0.07 0.11 0.17 0.27 0.41 0.63 0.87]
 [0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.27 0.4  0.55]
 [0.04 0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.26 0.35]
 [0.07 0.04 0.03 0.02 0.03 0.05 0.07 0.11 0.17 0.22]]
[['E' 'E' 'E' 'E' 'E' 'S' 'S' 'N' 'E' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N']
 ['N' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N' 'N']
 ['N' 'E' 'E' 'E' 'E' 'E' 'N' 'N' 'N' 'N']
 ['N' 'N' 'E' 'E' 'E' 'N' 'N' 'N' 'N' 'N']
 ['S' 'N' 'E' 'E' 'E' 'N' 'N' 'N' 'N' 'N']
 ['S' 'S' 'E' 'E' 'E' 'E' 'N' 'N' 'N' 'N']
 ['N' 'W' 'W' 'E' 'E' 'E' 'E' 'N' 'N' 'N']]
6
In [231]:
"""
2.2 this is the optimal policy from policy iteration
[['E' 'E' 'E' 'E' 'E' 'S' 'S' 'N' 'E' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N']
 ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N']
 ['N' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N' 'N']
 ['N' 'E' 'E' 'E' 'E' 'E' 'N' 'N' 'N' 'N']
 ['N' 'N' 'E' 'E' 'E' 'N' 'N' 'N' 'N' 'N']
 ['S' 'N' 'E' 'E' 'E' 'N' 'N' 'N' 'N' 'N']
 ['S' 'S' 'E' 'E' 'E' 'E' 'N' 'N' 'N' 'N']
 ['N' 'W' 'W' 'E' 'E' 'E' 'E' 'N' 'N' 'N']]
 """
Out[231]:
"\n2.2 this is the optimal policy from policy iteration\n[['E' 'E' 'E' 'E' 'E' 'S' 'S' 'N' 'E' 'N']\n ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N']\n ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N']\n ['E' 'E' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N']\n ['N' 'E' 'E' 'E' 'E' 'E' 'E' 'N' 'N' 'N']\n ['N' 'E' 'E' 'E' 'E' 'E' 'N' 'N' 'N' 'N']\n ['N' 'N' 'E' 'E' 'E' 'N' 'N' 'N' 'N' 'N']\n ['S' 'N' 'E' 'E' 'E' 'N' 'N' 'N' 'N' 'N']\n ['S' 'S' 'E' 'E' 'E' 'E' 'N' 'N' 'N' 'N']\n ['N' 'W' 'W' 'E' 'E' 'E' 'E' 'N' 'N' 'N']]\n "

Task 2.3 - TD Lambda

Use the heuristic policy and implement TD lambda to find values on the gridworld

In [232]:
# The policy mentioned in the pdf to be used for TD lambda, do not modify this
def heuristic_policy(env, state):
    goal = env.goal_location
    dx = goal[0] - state[0]
    dy = goal[1] - state[1]
    if abs(dx) >= abs(dy):
        direction = (np.sign(dx), 0)
    else:
        direction = (0, np.sign(dy))
    for action, dir_val in env.actions.items():
        if dir_val == direction:
            target_action = action
            break
    return target_action
In [233]:
def td_lambda(env, lamda, seeds):
    alpha = 0.5
    gamma = 0.7
    N = len(seeds)
    # Usage of input_policy
    # heuristic_policy(env, state) -> action
    example_action = heuristic_policy(env, (1,2)) # Returns 'N' if goal is (9,9)

    # Example of env.step
    # env.step(state, action) -> Returns next_state, reward, is_terminal

    # Initial values
    values = np.zeros((10, 10))
    es = np.zeros((10,10))
    values_list = []

    for episode_idx in range(N):
         # Do not change this else the results will not match due to environment stochas
        np.random.seed(seeds[episode_idx])
        grey_in_loc = np.where(env.grid == 'grey_in')
        state = grey_in_loc[0][0], grey_in_loc[1][0]
        done = False
        while not done:
            action = heuristic_policy(env, state)
            ns, rew, is_terminal = env.step(state, action) 
            # env.step is already taken inside the loop for you, 
            # Don't use env.step anywhere else in your code

            # Begin code here
            delta = rew + gamma*values[ns[0],ns[1]] - values[state[0], state[1]]
            es[state[0],state[1]]+=1
            
            for x in range(10):
              for y in range(10):
                values[state[0], state[1]] += alpha * delta * es[state[0], state[1]]
                es[state[0],state[1]]=gamma*lamda*es[state[0],state[1]]

            state=ns
            if is_terminal:
              done=True

        values_list.append(values.copy())  
    # Put your extra information needed for plots etc in this dictionary
    extra_info = {'list':values_list}

    # End code

    # Do not change the number of output values
    return {"Values": values}, extra_info
In [234]:
env = GridEnv_HW2(**base_kwargs)
res, extra_info = td_lambda(env, lamda=0.5, seeds=np.arange(1000))

 # The rounding off is just for making print statement cleaner
print(np.flipud(np.round(res['Values'], decimals=2)))
[[ 0.    0.    0.01  0.01  0.03  0.05  0.06  0.09 10.    0.  ]
 [ 0.    0.    0.03  0.06  0.63  1.01  1.54  4.9   7.   10.  ]
 [ 0.    0.08  0.17  0.37  0.46  0.23  2.26  3.42  4.25  4.75]
 [ 0.    0.02  0.14  0.17  0.34  0.46  1.15  1.97  2.62  3.05]
 [ 0.01  0.03  0.08  0.08  0.14  0.24  0.57  1.16  1.46  1.  ]
 [ 0.    0.02  0.05  0.08  0.08  0.21  0.22  0.52  0.91  0.53]
 [ 0.    0.01  0.03  0.04  0.05  0.07  0.14  0.42  0.48  0.  ]
 [ 0.    0.    0.02  0.01  0.03  0.07  0.1   0.18  0.16  0.05]
 [ 0.    0.    0.    0.    0.01  0.    0.05  0.13  0.18  0.  ]
 [ 0.15  0.    0.    0.    0.    0.    0.    0.04  0.04  0.  ]]

Task 2.4 - TD Lamdba for multiple values of $\lambda$

Ideally this code should run as is

In [235]:
# This cell is only for your subjective evaluation results, display the results as asked in the pdf
# You can change it as you require, this code should run TD lamdba by default for different values of lambda

lamda_values = np.arange(0, 100+5, 5)/100
td_lamda_results = {}
extra_info_TD = {}
for lamda in lamda_values:
    env = GridEnv_HW2(**base_kwargs)
    td_lamda_results[lamda], extra_info_TD[lamda] = td_lambda(env, lamda,
                                                           seeds=np.arange(1000))
In [236]:
for lamda in lamda_values:
  print(np.flipud(np.round(td_lamda_results[lamda]['Values'], decimals=2)))
[[0.   0.   0.   0.01 0.03 0.05 0.08 0.1  9.99 0.  ]
 [0.   0.   0.03 0.09 0.69 1.09 1.56 4.79 6.95 9.91]
 [0.   0.05 0.19 0.38 0.55 0.61 1.68 3.13 3.42 5.59]
 [0.   0.05 0.18 0.2  0.27 0.47 0.82 1.5  2.29 3.52]
 [0.01 0.05 0.1  0.11 0.19 0.26 0.48 0.96 1.55 1.08]
 [0.01 0.03 0.05 0.09 0.14 0.22 0.3  0.57 0.99 0.35]
 [0.   0.02 0.04 0.04 0.07 0.12 0.14 0.33 0.55 0.  ]
 [0.   0.01 0.02 0.02 0.04 0.07 0.13 0.22 0.19 0.07]
 [0.   0.   0.01 0.   0.01 0.   0.08 0.15 0.14 0.  ]
 [0.11 0.   0.   0.   0.   0.   0.   0.07 0.07 0.  ]]
[[0.   0.   0.   0.01 0.03 0.05 0.08 0.1  9.99 0.  ]
 [0.   0.   0.04 0.09 0.68 1.08 1.56 4.81 6.95 9.92]
 [0.   0.05 0.19 0.38 0.55 0.58 1.73 3.18 3.47 5.55]
 [0.   0.05 0.17 0.19 0.27 0.47 0.83 1.53 2.29 3.51]
 [0.01 0.05 0.1  0.11 0.18 0.25 0.48 0.97 1.54 1.09]
 [0.01 0.03 0.05 0.09 0.14 0.22 0.3  0.57 0.99 0.37]
 [0.   0.02 0.04 0.04 0.07 0.12 0.14 0.33 0.56 0.  ]
 [0.   0.01 0.02 0.02 0.04 0.07 0.13 0.22 0.18 0.07]
 [0.   0.   0.01 0.   0.01 0.   0.08 0.15 0.14 0.  ]
 [0.11 0.   0.   0.   0.   0.   0.   0.06 0.07 0.  ]]
[[ 0.    0.    0.    0.01  0.03  0.05  0.08  0.1  10.    0.  ]
 [ 0.    0.    0.04  0.09  0.66  1.07  1.55  4.82  6.96  9.94]
 [ 0.    0.05  0.19  0.38  0.54  0.56  1.78  3.22  3.52  5.51]
 [ 0.    0.04  0.17  0.19  0.27  0.48  0.85  1.56  2.3   3.49]
 [ 0.01  0.05  0.1   0.1   0.18  0.25  0.49  0.97  1.54  1.09]
 [ 0.01  0.03  0.05  0.09  0.13  0.22  0.29  0.57  0.98  0.38]
 [ 0.    0.02  0.04  0.04  0.07  0.12  0.14  0.33  0.56  0.  ]
 [ 0.    0.01  0.02  0.02  0.03  0.07  0.13  0.21  0.18  0.07]
 [ 0.    0.    0.01  0.    0.01  0.    0.08  0.15  0.15  0.  ]
 [ 0.12  0.    0.    0.    0.    0.    0.    0.06  0.07  0.  ]]
[[ 0.    0.    0.    0.01  0.03  0.05  0.08  0.1  10.    0.  ]
 [ 0.    0.    0.04  0.09  0.65  1.07  1.55  4.84  6.97  9.95]
 [ 0.    0.05  0.19  0.38  0.54  0.53  1.84  3.26  3.58  5.46]
 [ 0.    0.04  0.17  0.18  0.28  0.48  0.87  1.6   2.31  3.47]
 [ 0.01  0.05  0.1   0.1   0.17  0.24  0.49  0.98  1.53  1.09]
 [ 0.    0.03  0.05  0.09  0.13  0.22  0.29  0.57  0.98  0.4 ]
 [ 0.    0.02  0.04  0.04  0.07  0.12  0.14  0.33  0.56  0.  ]
 [ 0.    0.01  0.02  0.02  0.03  0.07  0.12  0.21  0.18  0.07]
 [ 0.    0.    0.01  0.    0.01  0.    0.08  0.15  0.15  0.  ]
 [ 0.12  0.    0.    0.    0.    0.    0.    0.06  0.07  0.  ]]
[[ 0.    0.    0.    0.01  0.03  0.05  0.07  0.1  10.    0.  ]
 [ 0.    0.    0.04  0.09  0.64  1.06  1.54  4.85  6.98  9.96]
 [ 0.    0.05  0.19  0.38  0.54  0.5   1.89  3.29  3.65  5.4 ]
 [ 0.    0.04  0.16  0.18  0.28  0.48  0.9   1.64  2.33  3.44]
 [ 0.01  0.05  0.1   0.1   0.17  0.24  0.49  0.99  1.53  1.08]
 [ 0.    0.03  0.05  0.09  0.13  0.22  0.28  0.57  0.97  0.42]
 [ 0.    0.02  0.04  0.04  0.07  0.11  0.14  0.34  0.55  0.  ]
 [ 0.    0.01  0.02  0.02  0.03  0.07  0.12  0.21  0.17  0.07]
 [ 0.    0.    0.01  0.    0.01  0.    0.08  0.15  0.15  0.  ]
 [ 0.12  0.    0.    0.    0.    0.    0.    0.06  0.06  0.  ]]
[[ 0.    0.    0.    0.01  0.03  0.05  0.07  0.1  10.    0.  ]
 [ 0.    0.    0.04  0.09  0.62  1.05  1.54  4.86  6.98  9.97]
 [ 0.    0.06  0.19  0.38  0.53  0.46  1.96  3.33  3.73  5.33]
 [ 0.    0.04  0.16  0.17  0.28  0.49  0.93  1.68  2.35  3.4 ]
 [ 0.01  0.05  0.1   0.1   0.16  0.24  0.5   1.    1.52  1.08]
 [ 0.    0.02  0.05  0.09  0.12  0.22  0.27  0.57  0.96  0.44]
 [ 0.    0.01  0.04  0.04  0.06  0.11  0.14  0.34  0.55  0.  ]
 [ 0.    0.01  0.02  0.01  0.03  0.07  0.12  0.2   0.17  0.07]
 [ 0.    0.    0.01  0.    0.01  0.    0.07  0.15  0.15  0.  ]
 [ 0.12  0.    0.    0.    0.    0.    0.    0.05  0.06  0.  ]]
[[ 0.    0.    0.    0.01  0.03  0.05  0.07  0.1  10.    0.  ]
 [ 0.    0.    0.04  0.09  0.61  1.04  1.54  4.87  6.99  9.98]
 [ 0.    0.06  0.19  0.38  0.52  0.42  2.02  3.35  3.81  5.25]
 [ 0.    0.04  0.16  0.17  0.29  0.49  0.96  1.73  2.38  3.36]
 [ 0.01  0.04  0.1   0.09  0.16  0.23  0.5   1.01  1.52  1.07]
 [ 0.    0.02  0.05  0.09  0.12  0.22  0.27  0.57  0.96  0.46]
 [ 0.    0.01  0.04  0.04  0.06  0.1   0.14  0.35  0.55  0.  ]
 [ 0.    0.01  0.02  0.01  0.03  0.07  0.12  0.19  0.17  0.07]
 [ 0.    0.    0.01  0.    0.01  0.    0.07  0.15  0.16  0.  ]
 [ 0.13  0.    0.    0.    0.    0.    0.    0.05  0.06  0.  ]]
[[ 0.    0.    0.    0.01  0.03  0.05  0.07  0.1  10.    0.  ]
 [ 0.    0.    0.04  0.08  0.6   1.04  1.53  4.88  6.99  9.98]
 [ 0.    0.06  0.19  0.38  0.51  0.38  2.08  3.38  3.91  5.16]
 [ 0.    0.03  0.15  0.17  0.3   0.49  0.99  1.78  2.41  3.3 ]
 [ 0.01  0.04  0.1   0.09  0.15  0.23  0.51  1.03  1.51  1.06]
 [ 0.    0.02  0.05  0.09  0.11  0.22  0.26  0.56  0.95  0.48]
 [ 0.    0.01  0.03  0.04  0.06  0.1   0.14  0.36  0.54  0.  ]
 [ 0.    0.01  0.02  0.01  0.03  0.07  0.11  0.19  0.17  0.06]
 [ 0.    0.    0.01  0.    0.01  0.    0.07  0.15  0.16  0.  ]
 [ 0.13  0.    0.    0.    0.    0.    0.    0.05  0.05  0.  ]]
[[ 0.    0.    0.    0.01  0.03  0.05  0.07  0.1  10.    0.  ]
 [ 0.    0.    0.04  0.08  0.59  1.03  1.53  4.89  6.99  9.99]
 [ 0.    0.07  0.19  0.38  0.5   0.33  2.14  3.4   4.01  5.05]
 [ 0.    0.03  0.15  0.17  0.31  0.49  1.04  1.84  2.47  3.23]
 [ 0.01  0.04  0.09  0.09  0.14  0.23  0.52  1.06  1.5   1.04]
 [ 0.    0.02  0.05  0.09  0.1   0.21  0.25  0.56  0.94  0.5 ]
 [ 0.    0.01  0.03  0.04  0.06  0.09  0.14  0.38  0.52  0.  ]
 [ 0.    0.01  0.02  0.01  0.03  0.07  0.11  0.18  0.17  0.06]
 [ 0.    0.    0.01  0.    0.01  0.    0.06  0.14  0.17  0.  ]
 [ 0.13  0.    0.    0.    0.    0.    0.    0.05  0.05  0.  ]]
[[ 0.    0.    0.    0.01  0.03  0.05  0.07  0.1  10.    0.  ]
 [ 0.    0.    0.04  0.07  0.6   1.02  1.54  4.89  7.    9.99]
 [ 0.    0.08  0.18  0.38  0.48  0.28  2.2   3.41  4.13  4.91]
 [ 0.    0.03  0.14  0.17  0.32  0.48  1.09  1.9   2.53  3.15]
 [ 0.01  0.04  0.09  0.08  0.14  0.23  0.54  1.1   1.48  1.02]
 [ 0.    0.02  0.05  0.09  0.1   0.21  0.24  0.54  0.92  0.51]
 [ 0.    0.01  0.03  0.04  0.05  0.08  0.14  0.4   0.5   0.  ]
 [ 0.    0.    0.02  0.01  0.03  0.07  0.1   0.18  0.16  0.05]
 [ 0.    0.    0.01  0.    0.01  0.    0.06  0.14  0.17  0.  ]
 [ 0.14  0.    0.    0.    0.    0.    0.    0.04  0.04  0.  ]]
[[ 0.    0.    0.01  0.01  0.03  0.05  0.06  0.09 10.    0.  ]
 [ 0.    0.    0.03  0.06  0.63  1.01  1.54  4.9   7.   10.  ]
 [ 0.    0.08  0.17  0.37  0.46  0.23  2.26  3.42  4.25  4.75]
 [ 0.    0.02  0.14  0.17  0.34  0.46  1.15  1.97  2.62  3.05]
 [ 0.01  0.03  0.08  0.08  0.14  0.24  0.57  1.16  1.46  1.  ]
 [ 0.    0.02  0.05  0.08  0.08  0.21  0.22  0.52  0.91  0.53]
 [ 0.    0.01  0.03  0.04  0.05  0.07  0.14  0.42  0.48  0.  ]
 [ 0.    0.    0.02  0.01  0.03  0.07  0.1   0.18  0.16  0.05]
 [ 0.    0.    0.    0.    0.01  0.    0.05  0.13  0.18  0.  ]
 [ 0.15  0.    0.    0.    0.    0.    0.    0.04  0.04  0.  ]]
[[ 0.    0.    0.01  0.01  0.04  0.05  0.06  0.09 10.    0.  ]
 [ 0.    0.    0.03  0.05  0.7   0.98  1.56  4.9   7.   10.  ]
 [ 0.    0.1   0.16  0.36  0.43  0.18  2.31  3.43  4.39  4.54]
 [ 0.    0.02  0.13  0.18  0.36  0.43  1.23  2.05  2.74  2.93]
 [ 0.    0.03  0.07  0.08  0.13  0.25  0.63  1.24  1.43  0.96]
 [ 0.    0.01  0.05  0.08  0.07  0.21  0.2   0.5   0.9   0.54]
 [ 0.    0.01  0.03  0.04  0.04  0.06  0.14  0.45  0.43  0.  ]
 [ 0.    0.    0.01  0.01  0.02  0.07  0.09  0.18  0.16  0.04]
 [ 0.    0.    0.    0.    0.01  0.    0.05  0.12  0.18  0.  ]
 [ 0.16  0.    0.    0.    0.    0.    0.    0.04  0.03  0.  ]]
[[ 0.    0.    0.    0.01  0.04  0.05  0.06  0.08 10.    0.  ]
 [ 0.    0.    0.02  0.03  0.83  0.93  1.58  4.9   7.   10.  ]
 [ 0.    0.11  0.15  0.33  0.39  0.13  2.35  3.43  4.53  4.29]
 [ 0.    0.01  0.12  0.18  0.37  0.38  1.32  2.14  2.89  2.79]
 [ 0.    0.02  0.05  0.08  0.14  0.27  0.72  1.34  1.38  0.92]
 [ 0.    0.01  0.04  0.07  0.06  0.21  0.16  0.48  0.89  0.55]
 [ 0.    0.01  0.02  0.05  0.04  0.05  0.14  0.47  0.37  0.  ]
 [ 0.    0.    0.01  0.    0.02  0.06  0.08  0.2   0.15  0.03]
 [ 0.    0.    0.    0.    0.01  0.    0.04  0.1   0.18  0.  ]
 [ 0.18  0.    0.    0.    0.    0.    0.    0.03  0.02  0.  ]]
[[ 0.    0.    0.    0.01  0.05  0.05  0.05  0.07 10.    0.  ]
 [ 0.    0.    0.01  0.01  1.07  0.84  1.61  4.9   7.   10.  ]
 [ 0.    0.13  0.12  0.26  0.34  0.09  2.38  3.43  4.69  3.97]
 [ 0.    0.01  0.1   0.18  0.38  0.31  1.45  2.24  3.09  2.63]
 [ 0.    0.02  0.04  0.07  0.14  0.31  0.88  1.47  1.31  0.88]
 [ 0.    0.01  0.03  0.06  0.04  0.22  0.12  0.48  0.88  0.56]
 [ 0.    0.01  0.01  0.06  0.03  0.03  0.15  0.48  0.26  0.  ]
 [ 0.    0.    0.01  0.    0.02  0.05  0.07  0.22  0.12  0.02]
 [ 0.    0.    0.    0.    0.01  0.    0.03  0.08  0.17  0.  ]
 [ 0.22  0.    0.    0.    0.    0.    0.    0.02  0.01  0.  ]]
[[ 0.    0.    0.    0.    0.08  0.04  0.05  0.07 10.    0.  ]
 [ 0.    0.    0.    0.    1.5   0.65  1.66  4.9   7.   10.  ]
 [ 0.    0.18  0.08  0.09  0.29  0.03  2.4   3.43  4.85  3.57]
 [ 0.    0.    0.06  0.15  0.4   0.18  1.62  2.36  3.35  2.45]
 [ 0.    0.01  0.01  0.04  0.14  0.38  1.1   1.63  1.21  0.83]
 [ 0.    0.    0.01  0.06  0.02  0.26  0.06  0.54  0.85  0.57]
 [ 0.    0.    0.    0.09  0.01  0.01  0.14  0.43  0.08  0.  ]
 [ 0.    0.    0.    0.    0.01  0.04  0.04  0.27  0.07  0.01]
 [ 0.    0.    0.    0.    0.    0.    0.02  0.04  0.15  0.  ]
 [ 0.27  0.    0.    0.    0.    0.    0.    0.01  0.    0.  ]]
[[ 0.    0.   -0.01  0.01  0.17 -0.03  0.05  0.06 10.    0.  ]
 [ 0.    0.    0.    0.01  2.27  0.3   1.74  4.9   7.   10.  ]
 [ 0.    0.28  0.03 -0.29  0.28 -0.06  2.39  3.43  5.03  3.03]
 [-0.    0.01 -0.    0.07  0.45 -0.01  1.86  2.52  3.66  2.28]
 [ 0.    0.   -0.01 -0.05  0.13  0.5   1.38  1.82  1.07  0.81]
 [-0.   -0.   -0.05  0.11 -0.04  0.38  0.02  0.76  0.72  0.6 ]
 [ 0.   -0.   -0.    0.13 -0.03 -0.03  0.12  0.28 -0.25  0.  ]
 [ 0.    0.    0.    0.   -0.    0.01 -0.05  0.33 -0.04 -0.02]
 [ 0.    0.   -0.    0.   -0.   -0.    0.01 -0.02  0.09  0.  ]
 [ 0.33  0.    0.    0.    0.    0.    0.   -0.03  0.    0.  ]]
[[ 0.    0.   -0.03  0.06  0.45 -0.54  0.07 -0.03 10.    0.  ]
 [ 0.    0.    0.05  0.07  3.64 -0.36  1.85  4.9   7.   10.  ]
 [ 0.    0.62 -0.   -1.16  0.39 -0.24  2.36  3.43  5.26  2.31]
 [-0.    0.03 -0.08 -0.21  0.69 -0.34  2.18  2.74  4.04  2.17]
 [ 0.   -0.05 -0.01 -0.27  0.08  0.76  1.58  2.09  0.89  0.85]
 [-0.01 -0.03 -0.25  0.33 -0.23  0.67  0.03  1.31  0.27  0.62]
 [ 0.   -0.01  0.05  0.19 -0.13 -0.1   0.06 -0.06 -0.79  0.  ]
 [ 0.    0.01  0.03 -0.01 -0.06 -0.07 -0.42  0.4  -0.29 -0.06]
 [ 0.    0.    0.01  0.   -0.01 -0.   -0.01 -0.04 -0.01  0.  ]
 [ 0.37  0.    0.    0.    0.    0.    0.   -0.12  0.03  0.  ]]
[[ 0.    0.   -0.01  0.15  1.45 -3.58  0.01 -0.65 10.    0.  ]
 [ 0.    0.    0.27  0.32  6.06 -1.5   2.02  4.89  7.   10.  ]
 [ 0.    1.87  0.07 -3.4   0.79 -0.6   2.34  3.42  5.67  1.25]
 [ 0.    0.18 -0.3  -1.17  1.78 -1.1   2.54  3.06  4.49  2.26]
 [-0.02 -0.29  0.43 -0.58 -0.1   1.36  1.57  2.59  0.65  1.01]
 [-0.17 -0.28 -1.09  1.04 -0.9   1.2   0.07  2.09 -1.09  0.61]
 [ 0.02  0.16  0.55  0.35 -0.29  0.05  0.05 -0.28 -1.49  0.  ]
 [ 0.    0.07  0.25 -0.14 -0.   -0.25 -2.07  0.12 -0.99 -0.15]
 [ 0.    0.    0.18  0.    0.   -0.   -0.14  1.11 -0.05  0.  ]
 [ 1.08  0.    0.    0.    0.    0.    0.   -0.68  0.06  0.  ]]
[[ 0.000e+00  0.000e+00  4.060e+00 -6.040e+00  3.100e-01 -1.880e+00
  -1.023e+01 -5.480e+00  1.000e+01  0.000e+00]
 [ 0.000e+00  0.000e+00  2.380e+00  1.370e+00  1.375e+01 -2.570e+00
   2.690e+00  4.830e+00  7.040e+00  1.005e+01]
 [ 0.000e+00  7.330e+00  8.900e-01 -1.122e+01 -1.380e+00 -1.360e+00
   2.680e+00  3.290e+00  6.640e+00 -5.700e-01]
 [ 3.000e-02  3.450e+00 -1.964e+01 -2.350e+00  7.760e+00 -6.260e+00
   3.430e+00  4.410e+00  5.020e+00  2.910e+00]
 [ 1.660e+00 -2.200e+00  9.600e-01 -2.600e-01 -1.750e+00  4.440e+00
  -1.890e+00  4.560e+00  4.900e-01  1.370e+00]
 [-3.110e+00 -1.100e-01 -1.390e+00  6.840e+00 -7.020e+00  3.800e-01
   2.360e+00  2.730e+00 -4.370e+00  3.800e-01]
 [ 9.800e-01  4.980e+00 -9.890e+00 -5.450e+00  2.570e+00  2.220e+00
   8.600e-01  7.530e+00 -5.200e-01  0.000e+00]
 [ 0.000e+00  1.180e+00  1.430e+00  1.530e+00  5.070e+00  6.200e-01
  -9.790e+00 -4.330e+00 -5.680e+00 -4.200e-01]
 [ 0.000e+00  0.000e+00  4.450e+00  0.000e+00  1.690e+00  7.000e-02
  -1.730e+00  1.469e+01 -3.820e+00  0.000e+00]
 [ 3.267e+01  0.000e+00  0.000e+00  0.000e+00  0.000e+00 -6.000e-02
   0.000e+00 -3.860e+00  5.400e-01  0.000e+00]]
[[ 0.00000000e+00  0.00000000e+00 -6.53460000e+02  3.46195000e+03
   1.72561138e+10 -1.40318070e+11 -4.03946506e+12 -8.74949543e+11
  -1.76441348e+08  0.00000000e+00]
 [ 0.00000000e+00  0.00000000e+00 -4.51434000e+03 -4.35393000e+03
   5.88367334e+11  5.29159127e+11 -3.56148122e+11  1.95414466e+10
  -8.56550990e+08  1.17916143e+09]
 [ 0.00000000e+00 -2.10640710e+08  3.86591364e+10 -5.27825513e+10
   1.06929480e+10 -1.82708392e+12  1.94484019e+11 -4.66646373e+10
   2.14114216e+10 -2.28020466e+10]
 [ 2.40000000e-01 -4.30742644e+11 -2.02786064e+13  3.07406976e+12
   2.67890913e+12  4.94022423e+12 -3.11360049e+12 -2.78158584e+12
   1.28708298e+12 -4.54403620e+08]
 [-8.94977837e+07  4.49736042e+12 -2.97497505e+13  1.72420842e+12
   1.49004552e+13 -1.26187122e+12 -3.12911293e+13  9.34984208e+12
   7.52969015e+11 -2.28962735e+06]
 [-3.07879009e+07  1.27284972e+13  3.25266012e+12  4.26389590e+13
  -4.11853177e+13  1.12014605e+13  2.43452484e+13  1.04026394e+13
   2.33729834e+10  8.28319700e+04]
 [ 2.19690000e+02  6.10135385e+11 -3.81389889e+13 -3.14577685e+13
   6.63880589e+12 -4.29624266e+12 -5.83863612e+09  1.74124884e+12
   1.41061814e+10  0.00000000e+00]
 [ 0.00000000e+00  1.14487590e+12  1.54181672e+11  1.50172077e+13
  -4.52634604e+10 -1.85187405e+09  6.44564714e+11 -8.38579400e+11
  -3.58055181e+09 -1.47756426e+07]
 [ 0.00000000e+00  0.00000000e+00  1.40661928e+11  0.00000000e+00
   2.95489127e+07  9.28000000e+01  7.37551012e+08  2.46736067e+12
  -4.24539022e+11  0.00000000e+00]
 [ 1.58594998e+13  0.00000000e+00  0.00000000e+00  0.00000000e+00
   0.00000000e+00 -3.49900000e+01  0.00000000e+00  5.00177397e+11
   1.55055550e+08  0.00000000e+00]]
[[ 0.00000000e+00  0.00000000e+00 -5.42009134e+07  6.64087907e+09
   1.55850803e+32  2.66226526e+33  1.16272777e+37  2.05264691e+38
   1.40935670e+35  0.00000000e+00]
 [ 0.00000000e+00  0.00000000e+00 -7.61697921e+12 -6.52883669e+12
   3.61419460e+34 -3.11352077e+36 -3.78975890e+37 -1.33221289e+37
   1.15605769e+36  7.35926117e+32]
 [ 0.00000000e+00  2.01485420e+30 -7.31652102e+35  3.12096601e+36
  -3.27022308e+36 -3.98829597e+36 -1.16538268e+38  4.23505320e+36
   7.97840665e+36 -3.03814177e+33]
 [-6.26300000e+01  1.64344236e+38  5.45815940e+38  1.68712926e+39
  -3.19625921e+39  1.84801903e+39 -1.09786895e+38 -9.74896217e+37
  -2.88493840e+37 -1.61636048e+33]
 [-8.82929172e+29 -5.79620225e+38  2.32047173e+38 -6.62214190e+38
   7.65211839e+38 -1.09226722e+39  8.02216383e+38 -2.26422674e+38
  -2.49565623e+37 -2.25697755e+27]
 [ 2.65933164e+22 -1.11276371e+39  1.25174043e+39 -8.64744290e+38
   1.17187875e+39 -1.81296963e+38 -7.16366860e+38 -2.25258295e+38
   4.53121637e+34 -1.56145925e+16]
 [-1.08703410e+05 -4.58708756e+37 -1.12621033e+39  6.43016006e+38
  -5.10961125e+38 -6.97449782e+37 -5.93982600e+34  1.30281193e+38
   3.97647976e+33  0.00000000e+00]
 [ 0.00000000e+00 -1.92028526e+38 -2.69373600e+38  2.00184789e+38
  -1.19370814e+36 -9.61267335e+27 -8.36372910e+34 -1.04338853e+36
  -7.75772514e+34  1.50836059e+24]
 [ 0.00000000e+00  0.00000000e+00  7.75706744e+38  0.00000000e+00
  -2.88016854e+24 -3.23681382e+07 -1.20764686e+29 -6.02596400e+37
   1.79328983e+38  0.00000000e+00]
 [-5.87633379e+38  0.00000000e+00  0.00000000e+00  0.00000000e+00
   0.00000000e+00  2.26576968e+06  0.00000000e+00 -2.71131928e+36
  -7.89041593e+26  0.00000000e+00]]

Generate Results ✅

In [248]:
def get_results(kwargs):

    gridenv = GridEnv_HW2(**kwargs)

    policy_iteration_results = policy_iteration(gridenv, 0.7)[0]
    value_iteration_results = value_iteration(gridenv, 0.7)[0]
    td_lambda_results = td_lambda(env, 0.5, np.arange(1000))[0]

    final_results = {}
    final_results["policy_iteration"] = policy_iteration_results
    final_results["value_iteration"] = value_iteration_results
    final_results["td_lambda"] = td_lambda_results

    return final_results
In [250]:
# Do not edit this cell, generate results with it as is
if not os.path.exists(AICROWD_RESULTS_DIR):
    os.mkdir(AICROWD_RESULTS_DIR)

for params_file in os.listdir(DATASET_DIR):
  kwargs = np.load(os.path.join(DATASET_DIR, params_file), allow_pickle=True).item()
  results = get_results(kwargs)
  idx = params_file.split('_')[-1][:-4]
  np.save(os.path.join(AICROWD_RESULTS_DIR, 'results_' + idx), results)

Check your score on the public data

This scores is not your final score, and it doesn't use the marks weightages. This is only for your reference of how arrays are matched and with what tolerance.

In [251]:
# Check your score on the given test cases (There are more private test cases not provided)
target_folder = 'targets'
result_folder = AICROWD_RESULTS_DIR

def check_algo_match(results, targets):
    if 'Policy' in results:
        policy_match = results['Policy'] == targets['Policy']
    else:
        policy_match = True
    # Reference https://numpy.org/doc/stable/reference/generated/numpy.allclose.html
    rewards_match = np.allclose(results['Values'], targets['Values'], rtol=3)
    equal = rewards_match and policy_match
    return equal

def check_score(target_folder, result_folder):
    match = []
    for out_file in os.listdir(result_folder):
        res_file = os.path.join(result_folder, out_file)
        results = np.load(res_file, allow_pickle=True).item()
        idx = out_file.split('_')[-1][:-4]  # Extract the file number
        target_file = os.path.join(target_folder, f"targets_{idx}.npy")
        targets = np.load(target_file, allow_pickle=True).item()
        algo_match = []
        for k in targets:
            algo_results = results[k]
            algo_targets = targets[k]
            algo_match.append(check_algo_match(algo_results, algo_targets))
        match.append(np.mean(algo_match))
    return np.mean(match)

if os.path.exists(target_folder):
    print("Shared data Score (normalized to 1):", check_score(target_folder, result_folder))
Shared data Score (normalized to 1): 1.0
/usr/local/lib/python3.7/dist-packages/numpy/core/_asarray.py:136: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  return array(a, dtype, copy=False, order=order, subok=True)

Display Results of TD lambda

Display Results of TD lambda with lambda values from 0 to 1 with steps of 0.05

Add code/text as required

Subjective questions

2.a Value Iteration vs Policy Iteration

  1. Compare value iteration and policy iteration for states Brown in, Brown Out, Grey out and Grey In
  2. Which one converges faster and why
In [240]:
env = GridEnv_HW2(**base_kwargs)
res, extra_info = value_iteration(env, 0.7)
grey_out = [(3,2), (4,2), (5,2), (6,2)]
brown_in = [(9,7)]
grey_in = [(0,0)]
brown_out = [(1,7)]
In [241]:
import matplotlib.pyplot as plt
points = [(9,7), (0,0), (1,7)]
labels = ["Brown_in", "Brown_out", "Grey_in"]


plt.figure(figsize=(16, 5), dpi=80)
plt.title("VI for Selected Points")
plt.xlabel('Iterations')
plt.ylabel('Expected Reward')
for point, label in zip(points, labels):
  plt.plot(range(1,extra_info['Iter']+1), [extra_info['list'][i][point] for i in range(extra_info['Iter'])], marker='o', linewidth=1, markersize=5, label = label)
plt.legend()
plt.xticks(range(1,extra_info['Iter']+1))
plt.show()
In [242]:
res, extra_info = policy_iteration(env, 0.7)
plt.figure(figsize=(12, 6), dpi=80)
plt.title("Policy iteration")
plt.xlabel('Number of iterations')
plt.ylabel('Expected rewards J(s)')
for point,  label in zip(points, labels):
  plt.plot(range(1,extra_info['Iter']+1), [extra_info['list'][i][point] for i in range(extra_info['Iter'])], marker='o', linewidth=1, markersize=5, label = label)
plt.legend()
plt.xticks(range(1,extra_info['Iter']+1))
plt.show()

Here we see policy iteration converging much faster than the value iteration as the set of all possible policies is finite and there for with the policy improvement step we would be making larger increases towards our optimum. while for value iteration near the convergence point the increase towards convergences drastically drops.

another thing to consider is how the value iteration step is already within in the policy iteraration in a sense and the policy improvment step gives us larger gains towards convergence

2.b How changing $\lambda$ affecting TD Lambda

In [243]:
import matplotlib.pyplot as plt

def J_error(J, J_v):
    assert len(J.flatten()) == len(J_v.flatten())
    error = 0
    for j, j_v in zip(J.flatten(), J_v.flatten()):
        error += pow((j - j_v),2)
    return error/len(J.flatten())
In [244]:
res, extra_info = value_iteration(env, 0.7)
J_value = res['Values']
N=1000
plt.figure(figsize=(16, 8), dpi=80)
lamda_values = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.85]
plt.title("Error Vs Number of Iterations")
plt.xlabel("Iterations")
plt.ylabel('Error value')
for lamda in lamda_values:
    errors = [J_error(J, J_value) for J in extra_info_TD[lamda]['list']]
    plt.plot(range(1,N+1), errors, linewidth=1, label = lamda)
plt.legend()
plt.show()

Here we see that for lambda less than or equale to 0.7 , we are getting errors than converge well . but for larger Lambda this is not the case. higher than 0.7 error starts to increase more as we go with more lambda

2.c Policy iteration error curve

Plot error curve of $J_i$ vs iteration $i$ for policy iteration

In [261]:
res, extra_info = value_iteration(env, 0.7)
res1, extra_infonew = policy_iteration(env, 0.7)

J_values = res['Values']
errors = [J_error(J, J_values) for J in extra_infonew['list']]

plt.figure()

plt.plot( range( 1, extra_infonew['Iter']+1),  errors )
plt.title( "Error Graph")
plt.xlabel( "Iteration")
plt.ylabel('Error')

plt.xticks(range(1,extra_infonew['Iter']+1))

plt.show()

2.d TD Lamdba error curve

Plot error curve of $J_i$ vs iteration $i$ for TD Lambda for $\lambda = [0, 0.25, 0.5, 0.75, 1]$

In [ ]:
res, extra_info = value_iteration(env, 0.7)
J_values = res['Values']
lamda_values = [0, 0.25, 0.5, 0.75]
N = 1000
lamda_TD_res= {}
extra_info = {}

for lamda in lamda_values:
    env = GridEnv_HW2(**base_kwargs)
    lamda_TD_res[lamda], extra_info[lamda] = td_lambda(env, lamda,seeds=np.arange(1000))

plt.figure(figsize=(16, 8), dpi=80)
plt.title("Graph of Errors")
plt.xlabel('Iterations')
plt.ylabel('Error')
for lamda in lamda_values:
    errors = [J_error(J, J_values) for J in extra_info_TD[lamda]['list']]
    plt.plot(range(1,1001), errors, linewidth=1, label = lamda)
plt.legend()
plt.show()

Submit to AIcrowd 🚀

In [262]:
!DATASET_PATH=$AICROWD_DATASET_PATH aicrowd notebook submit --no-verify -c iit-m-rl-assignment-2-gridworld -a assets
No jupyter lab module found. Using jupyter notebook.
Using notebook: /content/Copy%20of%20Copy%20of%20IITM_Assignment_2_Gridworld_Release.ipynb for submission...
Removing existing files from submission directory...
No jupyter lab module found. Using jupyter notebook.
Scrubbing API keys from the notebook...
Collecting notebook...
No jupyter lab module found. Using jupyter notebook.
submission.zip โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 100.0% โ€ข 1.1/1.1 MB โ€ข 1.5 MB/s โ€ข 0:00:00
                                                             โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ                                                             
                                                             โ”‚ Successfully submitted! โ”‚                                                             
                                                             โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ                                                             
                                                                   Important links                                                                   
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  This submission โ”‚ https://www.aicrowd.com/challenges/iit-m-assignment-2/problems/iit-m-rl-assignment-2-gridworld/submissions/132362              โ”‚
โ”‚                  โ”‚                                                                                                                                โ”‚
โ”‚  All submissions โ”‚ https://www.aicrowd.com/challenges/iit-m-assignment-2/problems/iit-m-rl-assignment-2-gridworld/submissions?my_submissions=true โ”‚
โ”‚                  โ”‚                                                                                                                                โ”‚
โ”‚      Leaderboard โ”‚ https://www.aicrowd.com/challenges/iit-m-assignment-2/problems/iit-m-rl-assignment-2-gridworld/leaderboards                    โ”‚
โ”‚                  โ”‚                                                                                                                                โ”‚
โ”‚ Discussion forum โ”‚ https://discourse.aicrowd.com/c/iit-m-assignment-2                                                                             โ”‚
โ”‚                  โ”‚                                                                                                                                โ”‚
โ”‚   Challenge page โ”‚ https://www.aicrowd.com/challenges/iit-m-assignment-2/problems/iit-m-rl-assignment-2-gridworld                                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
In [ ]:

102

Comments

You must login before you can post a comment.

Execute