Loading

IIT-M RL-ASSIGNMENT-2-GRIDWORLD

Solution for submission 129384

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

atishay_ganesh_ee17b155

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 [1]:
!pip install aicrowd-cli > /dev/null
ERROR: google-colab 1.0.0 has requirement requests~=2.23.0, but you'll have requests 2.25.1 which is incompatible.
ERROR: datascience 0.10.6 has requirement folium==0.2.1, but you'll have folium 0.8.3 which is incompatible.

AIcrowd Runtime Configuration 🧷

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

In [2]:
import os

AICROWD_DATASET_PATH = os.getenv("DATASET_PATH", os.getcwd()+"/5ed97a57-bc19-4f62-ae9e-f071d8b73317_a2_gridworld_inputs.zip")
AICROWD_RESULTS_DIR = os.getenv("OUTPUTS_DIR", "results")
In [3]:

API Key valid
Saved API Key successfully!
5ed97a57-bc19-4f62-ae9e-f071d8b73317_a2_gridworld_inputs.zip: 100% 14.1k/14.1k [00:00<00:00, 599kB/s]
In [4]:
!unzip -q $AICROWD_DATASET_PATH
In [5]:
DATASET_DIR = 'inputs/'

GridWorld Environment

Read the code for the environment thoroughly

Do not edit the code for the environment

In [6]:
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 [7]:
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 [8]:
def value_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
    value_grids = []
    policies =[]
    iter_length = 0
    tolerance = 10.0**-8
    extra_info = {}

    while True:
      iter_length +=1
      lenx,leny = values.shape
      for i in range(lenx):
          for j in range(leny):
              list_expected_value = []
              best_action = 0
              for action_id,action in enumerate(env.perpendicular_order):
                  action_outcomes = env.get_transition_probabilites_and_reward((i,j),action)
                  
                  expected_value_action = 0
                  for elt in action_outcomes:
                      #added discount to see if that was the issue
                      expected_value_action += elt[1]*(elt[2]+gamma*values[elt[0][0],elt[0][1]])
                  list_expected_value.append(expected_value_action)
                  if action_id !=0:
                      if expected_value_action> list_expected_value[best_action]:
                          best_action = action_id
      
              values[i,j] = list_expected_value[best_action]
              policy[i,j] = env.perpendicular_order[best_action]
      
      value_grids.append(np.copy(values))
      policies.append(np.copy(policy))
      extra_info[iter_length] =np.copy(values)
      if iter_length>1 and np.max(np.abs(value_grids[-1] - value_grids[-2]))<tolerance:
        break
      
    # Put your extra information needed for plots etc in this dictionary

    # End code

    # Do not change the number of output values
    return {"Values": values, "Policy": policy}, extra_info
In [9]:
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']]

Task 2.2 - Policy Iteration

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

In [10]:
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   
    extra_info ={}
    done = 0
    count_iters = 0
    while done == 0:
      count_iters +=1
      delta = 1
      while delta>1e-8:
        delta = 0
        lenx,leny = values.shape
        for i in range(lenx):
            for j in range(leny):
              action = policy[i,j]
              action_outcomes = env.get_transition_probabilites_and_reward((i,j),action) 
              expected_value_action = 0
              for elt in action_outcomes:
                expected_value_action += elt[1]*(elt[2]+gamma*values[elt[0][0],elt[0][1]])

              delta = max(delta,np.abs(expected_value_action-values[i,j]))
              values[i,j] = expected_value_action


      done = 1
      for i in range(lenx):
        for j in range(leny):
          list_expected_value = []
          best_action = 0
          old_policy = policy[i,j]
          for action_id,action in enumerate(env.perpendicular_order):
            action_outcomes = env.get_transition_probabilites_and_reward((i,j),action)
            expected_value_action = 0
            for elt in action_outcomes:
              expected_value_action += elt[1]*(elt[2]+gamma*values[elt[0][0],elt[0][1]])
            list_expected_value.append(expected_value_action)
            if action_id !=0:
              if expected_value_action> list_expected_value[best_action]:
                best_action = action_id

          values[i,j] = list_expected_value[best_action]
          policy[i,j] = env.perpendicular_order[best_action]
          if policy[i,j] != old_policy:
            done=0
    
      extra_info[count_iters] = np.copy(values)

    # Put your extra information needed for plots etc in this dictionary

    # End code

    # Do not change the number of output values
    return {"Values": values, "Policy": policy}, extra_info
In [11]:
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']))
[[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']]

Task 2.3 - TD Lambda

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

In [12]:
# 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 [13]:
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
    extra_info = {}
    values = np.zeros((10, 10))
    es = np.zeros((10,10))
    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
            lenx,leny = values.shape
            for i in range(lenx):
              for j in range(leny):
                values[i,j] = values[i,j]+alpha*delta*es[i,j]
                es[i,j] = lamda*gamma*es[i,j]
   
            state = ns
            done=is_terminal
        extra_info[episode_idx] = np.copy(values)


              
    # Put your extra information needed for plots etc in this dictionary
    

    # End code

    # Do not change the number of output values
    return {"Values": values}, extra_info
In [14]:
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.round(res['Values'], decimals=2)))
[[ 0.12  0.    0.    0.    0.    0.01  0.01  0.11  0.13  0.  ]
 [ 0.    0.    0.01  0.01  0.03  0.03  0.1   0.15  0.16  0.  ]
 [ 0.    0.01  0.03  0.03  0.07  0.1   0.15  0.23  0.18  0.18]
 [ 0.01  0.03  0.03  0.05  0.08  0.17  0.2   0.35  0.58  0.26]
 [ 0.02  0.04  0.05  0.1   0.16  0.23  0.38  0.57  1.08  0.97]
 [ 0.02  0.07  0.08  0.11  0.25  0.4   0.52  0.96  1.62  1.44]
 [ 0.02  0.08  0.21  0.31  0.48  0.82  1.29  1.66  2.2   3.39]
 [ 0.    0.05  0.24  0.42  0.63  0.71  2.08  3.28  3.8   5.89]
 [ 0.    0.    0.04  0.18  0.91  1.4   1.28  4.85  6.98  9.92]
 [ 0.    0.    0.01  0.02  0.03  0.06  0.08  0.11 10.    0.  ]]

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

Ideally this code should run as is

In [15]:
# 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, 25)/100
##This is changed from 0 to 100 in steps of 5 since that lead to timeout errrors.
td_lamda_results = {}
extra_info_td = {}
for lamda in lamda_values:
    env = GridEnv_HW2(**base_kwargs)
    print(lamda)
    td_lamda_results[lamda], extra_info_td[lamda] = td_lambda(env, lamda,
                                                           seeds=np.arange(1000))
0.0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
1.0

Generate Results ✅

In [16]:
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 [17]:
# 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 [18]:
# 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

Results : Error (from VI) as well as Values at some important locations are shown.

A2_1.pngA2_2.pngA2_3.pngA2_4.png

In [19]:
import matplotlib.pyplot as plt
base_kwargs = get_base_kwargs()
env = GridEnv_HW2(**base_kwargs)
res_VI, extra_info_VI = value_iteration(env, 0.7)
res_PI, extra_info_PI = policy_iteration(env,0.7)

# final_error = [np.sqrt(np.sum(np.square(td_lamda_results[i]['Values']-res_VI['Values']))/100) for i in lamda_values]
# plt.figure(1)
# plt.plot(lamda_values,final_error)
# plt.title("Final Error as a function of $\lambda$")
# plt.xlabel("$\lambda$")
# plt.ylabel("Error")
# plt.show()
In [20]:
# bi,bo,gi = (base_kwargs['brown_in'][0],base_kwargs['brown_out'][0],base_kwargs['grey_in'][0])
# bi_val = [td_lamda_results[i]['Values'][bi[0],bi[1]] for i in lamda_values]
# bo_val = [td_lamda_results[i]['Values'][bo[0],bo[1]] for i in lamda_values]
# gi_val = [td_lamda_results[i]['Values'][gi[0],gi[1]] for i in lamda_values]


# plt.figure(1)
# plt.plot(lamda_values,bi_val,'r-')
# plt.plot(lamda_values,len(lamda_values)*[res_VI['Values'][bi[0],bi[1]]])
# plt.title("Value at Brown In as a function of $\lambda$")
# plt.xlabel("$\lambda$")
# plt.ylabel("Value at Brown In")
# plt.legend(("Expected","Actual (via VI)"))

# plt.figure(2)
# plt.plot(lamda_values,bo_val,'r-')
# plt.plot(lamda_values,len(lamda_values)*[res_VI['Values'][bo[0],bo[1]]])

# plt.title("Value at Brown Out as a function of $\lambda$")
# plt.xlabel("$\lambda$")
# plt.ylabel("Value at Brown Out")
# plt.legend(("Expected","Actual (via VI)"))

# plt.figure(3)
# plt.plot(lamda_values,gi_val,'r-')
# plt.plot(lamda_values,len(lamda_values)*[res_VI['Values'][gi[0],gi[1]]])
# plt.title("Value at Grey In as a function of $\lambda$")
# plt.xlabel("$\lambda$")
# plt.ylabel("Value at Grey In")
# plt.legend(("Expected","Actual (via VI)"))
# plt.show()

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

Value Iteration and Policy iteation both converge to the same optimal value for all 3 mentioned states. However They take different number of iterations.

  1. Which one converges faster and why

Policy Iteration takes fewer number of outer loops iterations to converege. This is because each of policy iteration outer loop iteration has 1 round of policy evaluation and 1 round of policy improvement, and the policy evaluation step involves evaluation of the policy, which requires many inner loops.

In [31]:
bi,bo,gi = (base_kwargs['brown_in'][0],base_kwargs['brown_out'][0],base_kwargs['grey_in'][0])

bi_val_VI = [extra_info_VI[i][bi[0],bi[1]] for i in extra_info_VI.keys()]
bo_val_VI = [extra_info_VI[i][bo[0],bo[1]] for i in extra_info_VI.keys()]
gi_val_VI = [extra_info_VI[i][gi[0],gi[1]] for i in extra_info_VI.keys()]

bi_val_PI = [extra_info_PI[i][bi[0],bi[1]] for i in extra_info_PI.keys()]
bo_val_PI = [extra_info_PI[i][bo[0],bo[1]] for i in extra_info_PI.keys()]
gi_val_PI = [extra_info_PI[i][gi[0],gi[1]] for i in extra_info_PI.keys()]

plt.figure(1)
plt.plot(bi_val_VI,'r-')
plt.plot(bi_val_PI,'b-')
plt.title("Estimated Value at Brown In as a function of iteration$")
plt.xlabel("Iterations")
plt.ylabel("Value at Brown In")
plt.legend(("VI","PI"))

plt.figure(2)
plt.plot(bo_val_VI,'r-')
plt.plot(bo_val_PI,'b-')
plt.title("Estimated Value at Brown Out as a function of iteration$")
plt.xlabel("Iterations")
plt.ylabel("Value at Brown Out")
plt.legend(("VI","PI"))

plt.figure(3)
plt.plot(gi_val_VI,'r-')
plt.plot(gi_val_PI,'b-')
plt.title("Estimated Value at Grey In as a function of iteration$")
plt.xlabel("Iterations")
plt.ylabel("Value at Grey In")
plt.legend(("VI","PI"))

plt.show()

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

It is observed that there is a bias variance tradeoff in choosing $\lambda$ values, with lower values of $\lambda$ being more biased, and larger values of $\lambda$ having higher variance. This can be observed from the graphs drawn in section 2.d, where there are sudden large spikes for higher values of $\lambda$ which indicates higher variance.

The final error plot, which was drawn earlier, indicates that the better values of $\lambda$ are somewhere in the middle.

2.c Policy iteration error curve

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

In [22]:
final_error_PI = [np.sqrt(np.sum(np.square(extra_info_PI[i]-res_VI['Values']))/100) for i in extra_info_PI]
plt.figure(1)
plt.semilogy(final_error_PI)
plt.title("Final Error as a function of iteration, in PI")
plt.xlabel("Iteration")
plt.ylabel("Error")
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 [23]:
final_error_TD0 = [np.sqrt(np.sum(np.square(extra_info_td[0.0][i]-res_VI['Values']))/100) for i in extra_info_td[0.0]]
final_error_TD25 = [np.sqrt(np.sum(np.square(extra_info_td[0.25][i]-res_VI['Values']))/100) for i in extra_info_td[0.25]]
final_error_TD50 = [np.sqrt(np.sum(np.square(extra_info_td[0.50][i]-res_VI['Values']))/100) for i in extra_info_td[0.50]]
final_error_TD75 = [np.sqrt(np.sum(np.square(extra_info_td[0.75][i]-res_VI['Values']))/100) for i in extra_info_td[0.75]]
final_error_TD100 = [np.sqrt(np.sum(np.square(extra_info_td[1.0][i]-res_VI['Values']))/100) for i in extra_info_td[1.0]]

plt.figure(1)
plt.plot(final_error_TD0)
plt.title("Final Error as a function of iteration, in TD(0)")
plt.xlabel("Iteration")
plt.ylabel("Error")
plt.show()
plt.figure(2)
plt.plot(final_error_TD25)
plt.title("Final Error as a function of iteration, in TD(0.25)")
plt.xlabel("Iteration")
plt.ylabel("Error")
plt.show()
plt.figure(3)
plt.plot(final_error_TD50)
plt.title("Final Error as a function of iteration, in TD(0.5)")
plt.xlabel("Iteration")
plt.ylabel("Error")
plt.show()
plt.figure(4)
plt.plot(final_error_TD75)
plt.title("Final Error as a function of iteration, in TD(0.75)")
plt.xlabel("Iteration")
plt.ylabel("Error")
plt.show()
plt.figure(5)
plt.plot(final_error_TD100)
plt.title("Final Error as a function of iteration, in TD(1)")
plt.xlabel("Iteration")
plt.ylabel("Error")
plt.show()

Submit to AIcrowd 🚀

In [32]:
!DATASET_PATH=$AICROWD_DATASET_PATH aicrowd notebook submit -c iit-m-rl-assignment-2-gridworld -a assets
No jupyter lab module found. Using jupyter notebook.
Using notebook: /content/EE17B155_IITM_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.
Validating the submission...
Executing install.ipynb...
[NbConvertApp] Converting notebook /content/submission/install.ipynb to notebook
[NbConvertApp] Executing notebook with kernel: python3
[NbConvertApp] Writing 1038 bytes to /content/submission/install.nbconvert.ipynb
Executing predict.ipynb...
[NbConvertApp] Converting notebook /content/submission/predict.ipynb to notebook
[NbConvertApp] Executing notebook with kernel: python3
[NbConvertApp] ERROR | unhandled iopub msg: colab_request
[NbConvertApp] ERROR | unhandled iopub msg: colab_request
[NbConvertApp] ERROR | unhandled iopub msg: colab_request
[NbConvertApp] ERROR | unhandled iopub msg: colab_request
[NbConvertApp] ERROR | unhandled iopub msg: colab_request
[NbConvertApp] ERROR | unhandled iopub msg: colab_request
[NbConvertApp] ERROR | Error while converting '/content/submission/predict.ipynb'
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/nbconvertapp.py", line 408, in export_single_notebook
    output, resources = self.exporter.from_filename(notebook_filename, resources=resources)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/exporters/exporter.py", line 179, in from_filename
    return self.from_file(f, resources=resources, **kw)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/exporters/exporter.py", line 197, in from_file
    return self.from_notebook_node(nbformat.read(file_stream, as_version=4), resources=resources, **kw)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/exporters/notebook.py", line 32, in from_notebook_node
    nb_copy, resources = super(NotebookExporter, self).from_notebook_node(nb, resources, **kw)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/exporters/exporter.py", line 139, in from_notebook_node
    nb_copy, resources = self._preprocess(nb_copy, resources)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/exporters/exporter.py", line 316, in _preprocess
    nbc, resc = preprocessor(nbc, resc)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/preprocessors/base.py", line 47, in __call__
    return self.preprocess(nb, resources)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/preprocessors/execute.py", line 381, in preprocess
    nb, resources = super(ExecutePreprocessor, self).preprocess(nb, resources)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/preprocessors/base.py", line 69, in preprocess
    nb.cells[index], resources = self.preprocess_cell(cell, resources, index)
  File "/usr/local/lib/python2.7/dist-packages/nbconvert/preprocessors/execute.py", line 424, in preprocess_cell
    raise CellExecutionError.from_cell_and_msg(cell, out)
CellExecutionError: An error occurred while executing the following cell:
------------------
bi,bo,gi = (base_kwargs['brown_in'][0],base_kwargs['brown_out'][0],base_kwargs['grey_in'][0])

bi_val_VI = [extra_info_VI[i][bi[0],bi[1]] for i in extra_info_VI.keys()]
bo_val_VI = [extra_info_VI[i][bo[0],bo[1]] for i in extra_info_VI.keys()]
gi_val_VI = [extra_info_VI[i][gi[0],gi[1]] for i in extra_info_VI.keys()]

bi_val_PI = [extra_info_PI[i][bi[0],bi[1]] for i in extra_info_PI.keys()]
bo_val_PI = [extra_info_PI[i][bo[0],bo[1]] for i in extra_info_PI.keys()]
gi_val_PI = [extra_info_PI[i][gi[0],gi[1]] for i in extra_info_PI.keys()]

plt.figure(1)
plt.plot(bi_val_VI,'r-')
plt.plot(bi_val_PI,'b-')
plt.title("Estimated Value at Brown In as a function of iteration$")
plt.xlabel("Iterations")
plt.ylabel("Value at Brown In")
plt.legend(("VI","PI"))

plt.figure(2)
plt.plot(bo_val_VI,'r-')
plt.plot(bo_val_PI,'b-')
plt.title("Estimated Value at Brown Out as a function of iteration$")
plt.xlabel("Iterations")
plt.ylabel("Value at Brown Out")
plt.legend(("VI","PI"))

plt.figure(3)
plt.plot(gi_val_VI,'r-')
plt.plot(gi_val_PI,'b-')
plt.title("Estimated Value at Grey In as a function of iteration$")
plt.xlabel("Iterations")
plt.ylabel("Value at Grey In")
plt.legend(("VI","PI"))

plt.show()
------------------

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-20-9be0acd6ae34> in <module>()
      9 gi_val_PI = [extra_info_PI[i][gi[0],gi[1]] for i in extra_info_PI.keys()]
     10 
---> 11 plt.figure(1)
     12 plt.plot(bi_val_VI,'r-')
     13 plt.plot(bi_val_PI,'b-')

NameError: name 'plt' is not defined
NameError: name 'plt' is not defined

โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Traceback (most recent call last) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ /usr/local/bin/aicrowd:8 in <module>                                         โ”‚
โ”‚                                                                              โ”‚
โ”‚   5 from aicrowd.cli import cli                                              โ”‚
โ”‚   6 if __name__ == '__main__':                                               โ”‚
โ”‚   7 โ”‚   sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])     โ”‚
โ”‚ โฑ 8 โ”‚   sys.exit(cli())                                                      โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/click/core.py:829 in __call__         โ”‚
โ”‚                                                                              โ”‚
โ”‚    826 โ”‚                                                                     โ”‚
โ”‚    827 โ”‚   def __call__(self, *args, **kwargs):                              โ”‚
โ”‚    828 โ”‚   โ”‚   """Alias for :meth:`main`."""                                 โ”‚
โ”‚ โฑ  829 โ”‚   โ”‚   return self.main(*args, **kwargs)                             โ”‚
โ”‚    830                                                                       โ”‚
โ”‚    831                                                                       โ”‚
โ”‚    832 class Command(BaseCommand):                                           โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/click/core.py:782 in main             โ”‚
โ”‚                                                                              โ”‚
โ”‚    779 โ”‚   โ”‚   try:                                                          โ”‚
โ”‚    780 โ”‚   โ”‚   โ”‚   try:                                                      โ”‚
โ”‚    781 โ”‚   โ”‚   โ”‚   โ”‚   with self.make_context(prog_name, args, **extra) as c โ”‚
โ”‚ โฑ  782 โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   rv = self.invoke(ctx)                             โ”‚
โ”‚    783 โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   if not standalone_mode:                           โ”‚
โ”‚    784 โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   return rv                                     โ”‚
โ”‚    785 โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   # it's not safe to `ctx.exit(rv)` here!           โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/click/core.py:1259 in invoke          โ”‚
โ”‚                                                                              โ”‚
โ”‚   1256 โ”‚   โ”‚   โ”‚   โ”‚   Command.invoke(self, ctx)                             โ”‚
โ”‚   1257 โ”‚   โ”‚   โ”‚   โ”‚   sub_ctx = cmd.make_context(cmd_name, args, parent=ctx โ”‚
โ”‚   1258 โ”‚   โ”‚   โ”‚   โ”‚   with sub_ctx:                                         โ”‚
โ”‚ โฑ 1259 โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   return _process_result(sub_ctx.command.invoke(sub โ”‚
โ”‚   1260 โ”‚   โ”‚                                                                 โ”‚
โ”‚   1261 โ”‚   โ”‚   # In chain mode we create the contexts step by step, but afte โ”‚
โ”‚   1262 โ”‚   โ”‚   # base command has been invoked.  Because at that point we do โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/click/core.py:1259 in invoke          โ”‚
โ”‚                                                                              โ”‚
โ”‚   1256 โ”‚   โ”‚   โ”‚   โ”‚   Command.invoke(self, ctx)                             โ”‚
โ”‚   1257 โ”‚   โ”‚   โ”‚   โ”‚   sub_ctx = cmd.make_context(cmd_name, args, parent=ctx โ”‚
โ”‚   1258 โ”‚   โ”‚   โ”‚   โ”‚   with sub_ctx:                                         โ”‚
โ”‚ โฑ 1259 โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   return _process_result(sub_ctx.command.invoke(sub โ”‚
โ”‚   1260 โ”‚   โ”‚                                                                 โ”‚
โ”‚   1261 โ”‚   โ”‚   # In chain mode we create the contexts step by step, but afte โ”‚
โ”‚   1262 โ”‚   โ”‚   # base command has been invoked.  Because at that point we do โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/click/core.py:1066 in invoke          โ”‚
โ”‚                                                                              โ”‚
โ”‚   1063 โ”‚   โ”‚   """                                                           โ”‚
โ”‚   1064 โ”‚   โ”‚   _maybe_show_deprecated_notice(self)                           โ”‚
โ”‚   1065 โ”‚   โ”‚   if self.callback is not None:                                 โ”‚
โ”‚ โฑ 1066 โ”‚   โ”‚   โ”‚   return ctx.invoke(self.callback, **ctx.params)            โ”‚
โ”‚   1067                                                                       โ”‚
โ”‚   1068                                                                       โ”‚
โ”‚   1069 class MultiCommand(Command):                                          โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/click/core.py:610 in invoke           โ”‚
โ”‚                                                                              โ”‚
โ”‚    607 โ”‚   โ”‚   args = args[2:]                                               โ”‚
โ”‚    608 โ”‚   โ”‚   with augment_usage_errors(self):                              โ”‚
โ”‚    609 โ”‚   โ”‚   โ”‚   with ctx:                                                 โ”‚
โ”‚ โฑ  610 โ”‚   โ”‚   โ”‚   โ”‚   return callback(*args, **kwargs)                      โ”‚
โ”‚    611 โ”‚                                                                     โ”‚
โ”‚    612 โ”‚   def forward(*args, **kwargs):  # noqa: B902                       โ”‚
โ”‚    613 โ”‚   โ”‚   """Similar to :meth:`invoke` but fills in default keyword     โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/aicrowd/cmd/notebook.py:92 in         โ”‚
โ”‚ submit_subcommand                                                            โ”‚
โ”‚                                                                              โ”‚
โ”‚    89 โ”‚   โ”‚   output,                                                        โ”‚
โ”‚    90 โ”‚   โ”‚   notebook_name,                                                 โ”‚
โ”‚    91 โ”‚   โ”‚   no_verify,                                                     โ”‚
โ”‚ โฑ  92 โ”‚   โ”‚   dry_run,                                                       โ”‚
โ”‚    93 โ”‚   )                                                                  โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/aicrowd/notebook/submit.py:88 in      โ”‚
โ”‚ create_submission                                                            โ”‚
โ”‚                                                                              โ”‚
โ”‚   85 ):                                                                      โ”‚
โ”‚   86 โ”‚   bundle_submission(assets_dir, submission_zip_path, notebook_name)   โ”‚
โ”‚   87 โ”‚   if not no_verify:                                                   โ”‚
โ”‚ โฑ 88 โ”‚   โ”‚   verify_submission()                                             โ”‚
โ”‚   89 โ”‚   if not dry_run:                                                     โ”‚
โ”‚   90 โ”‚   โ”‚   submit_to_aicrowd(                                              โ”‚
โ”‚   91 โ”‚   โ”‚   โ”‚   challenge=challenge,                                        โ”‚
โ”‚                                                                              โ”‚
โ”‚ /usr/local/lib/python3.7/dist-packages/aicrowd/notebook/submit.py:32 in      โ”‚
โ”‚ verify_submission                                                            โ”‚
โ”‚                                                                              โ”‚
โ”‚   29 โ”‚   for notebook in ["install.ipynb", "predict.ipynb"]:                 โ”‚
โ”‚   30 โ”‚   โ”‚   print(f"Executing {notebook}...")                               โ”‚
โ”‚   31 โ”‚   โ”‚   if execute_command(nbconvert_cmd.format(kernel, SUBMISSION_DIR, โ”‚
โ”‚ โฑ 32 โ”‚   โ”‚   โ”‚   raise RuntimeError(f"{notebook} failed to execute")         โ”‚
โ”‚   33                                                                         โ”‚
โ”‚   34                                                                         โ”‚
โ”‚   35 def bundle_submission(                                                  โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
RuntimeError: predict.ipynb failed to execute
227

Comments

You must login before you can post a comment.

Execute