Loading

IIT-M RL-ASSIGNMENT-2-GRIDWORLD

Solution for submission 132240

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

narra_jeevan_reddy_ee17b057

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 [35]:
!pip install aicrowd-cli > /dev/null

AIcrowd Runtime Configuration 🧷

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

In [36]:
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 [37]:

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, 632kB/s]
In [38]:
!unzip -q $AICROWD_DATASET_PATH
replace inputs/inputs_base.npy? [y]es, [n]o, [A]ll, [N]one, [r]ename: A
In [39]:
DATASET_DIR = 'inputs/'

GridWorld Environment

Read the code for the environment thoroughly

Do not edit the code for the environment

In [40]:
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
        self.brown_in=brown_in[0]
        self.grey_in=grey_in[0]
    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 [41]:
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 [42]:
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
    H =  np.zeros((10, 10))
    delta=1
    BI=[]
    BO=[]
    GI=[]
    while delta>1e-8:
      delta = 0
      #for i in range(10):
       # for j in range(10):
      for s in [(i,j) for i in range(10) for j in range(10)]:
        opt_value = float('-inf')
        opt_action = 'N'

        for action in env.actions:
          value = 0
          for (next_state,prob,rew) in env.get_transition_probabilites_and_reward(s,action):
            value += prob*(rew + gamma*values[next_state])
          
          if value > opt_value:
            opt_value = value
            opt_action = action

        H[s] = opt_value
        policy[s] = opt_action

        delta = max(delta,abs(H[s]-values[s]))
      
      #for i in range(10):
       # for j in range(10):
        #  values[i][j] = H[i][j]
      values=H.copy()
      BI.append(values[env.brown_in])
      BO.append(values[env.brown_outs[0]])
      GI.append(values[env.grey_in])

    # Put your extra information needed for plots etc in this dictionary
    extra_info = {'Brown in':BI,'Brown out':BO,'Grey in':GI}

    # End code

    # Do not change the number of output values
    return {"Values": values, "Policy": policy}, extra_info
In [43]:
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 [44]:
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  
    
    done=0
    BI=[]
    BO=[]
    GI=[]
    J=[]
    while done==0:
      delta=1
      while delta > 1e-8:
        delta=0
        for s in [(i,j) for i in range(10) for j in range(10)]:
          previous_value=values[s]
          npr=env.get_transition_probabilites_and_reward(s,policy[s])
          present_state_value=0
          for ns,p,R in npr:
            present_state_value+=p*(R+gamma*values[ns])
          delta=max(delta,abs(previous_value-present_state_value))
          values[s]=present_state_value
      BI.append(values[env.brown_in])
      BO.append(values[env.brown_outs[0]])
      GI.append(values[env.grey_in])
      done=1
      for s in [(i,j) for i in range(10) for j in range(10)]:
        
        b=policy[s]
        opt_value=float('-inf')
        for a in env.actions:
          npr=env.get_transition_probabilites_and_reward(s,a)
          present_state_value=0
          for ns,p,R in npr:
            present_state_value+=p*(R+gamma*values[ns])
          if present_state_value>opt_value:
            opt_value=present_state_value
            policy[s]=a
        
        if b!=policy[s]:
          done=0
      J.append(values.copy())
    # Put your extra information needed for plots etc in this dictionary
    extra_info = {'Brown in':BI,'Brown out':BO,'Grey in':GI,'J':J}
    
    # End code

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

 # The rounding off is just for making print statement cleaner
print(np.flipud(np.round(res_PI['Values'], decimals=2)))

print(np.flipud(res_PI['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 [46]:
from matplotlib import  pyplot as plt
plt.figure(1)

plt.plot(range(len(extra_info['Brown in'])),extra_info['Brown in'])
plt.plot(range(len(extra_info_PI['Brown in'])),extra_info_PI['Brown in'])
plt.title('Brown IN')
plt.legend(['VI','PI'])
plt.figure(2)
plt.plot(range(len(extra_info['Brown out'])),extra_info['Brown out'])
plt.plot(range(len(extra_info_PI['Brown out'])),extra_info_PI['Brown out'])
plt.title('Brown OUT')
plt.legend(['VI','PI'])
plt.figure(3)
plt.plot(range(len(extra_info['Grey in'])),extra_info['Grey in'])
plt.plot(range(len(extra_info_PI['Grey in'])),extra_info_PI['Grey in'])
plt.title('Grey IN')
plt.legend(['VI','PI'])
Out[46]:
<matplotlib.legend.Legend at 0x7faa5a4deb90>

Task 2.3 - TD Lambda

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

In [47]:
# 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 [65]:
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))
    J=[]
    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
            if is_terminal:
              done=True
            delta=rew+gamma*values[ns]-values[state]
            es[state]+=1
            for s in [(i,j)for i in range(10) for j in range(10)]:
              values[s]+=alpha*delta*es[s]
              es[s]*=gamma*lamda
            state=ns
        J.append(values.copy())
    # Put your extra information needed for plots etc in this dictionary
    extra_info = {'J':J}

    # End code

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

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

Ideally this code should run as is

In [67]:
# 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 = {}
for lamda in lamda_values:
    env = GridEnv_HW2(**base_kwargs)
    td_lamda_results[lamda], extra_info[lamda] = td_lambda(env, lamda,
                                                           seeds=np.arange(1000))
In [51]:
import pandas as pd
for lamda in lamda_values:
  df=pd.DataFrame(td_lamda_results[lamda]['Values'])
  print("lambda = ",lamda)
  print(df)
lambda =  0.0
          0         1         2  ...         7         8         9
0  0.112206  0.000000  0.000000  ...  0.065779  0.068347  0.000000
1  0.000000  0.000000  0.005550  ...  0.153915  0.142262  0.000000
2  0.000000  0.009004  0.024202  ...  0.219198  0.186042  0.071450
3  0.001865  0.017169  0.037010  ...  0.329617  0.554287  0.000000
4  0.005547  0.029974  0.053455  ...  0.566782  0.987899  0.347095
5  0.013081  0.050791  0.099114  ...  0.962428  1.549146  1.084454
6  0.004858  0.047445  0.176900  ...  1.501906  2.286707  3.518086
7  0.000000  0.046376  0.194074  ...  3.134084  3.418145  5.585501
8  0.000000  0.000000  0.034499  ...  4.787558  6.945194  9.910450
9  0.000000  0.000000  0.001787  ...  0.102590  9.992897  0.000000

[10 rows x 10 columns]
lambda =  0.05
          0         1         2  ...         7         8         9
0  0.111166  0.000000  0.000000  ...  0.070193  0.075703  0.000000
1  0.000000  0.000000  0.006263  ...  0.155508  0.146924  0.000000
2  0.000012  0.009754  0.024875  ...  0.223106  0.188853  0.073801
3  0.002214  0.018243  0.036623  ...  0.338365  0.562541  0.004144
4  0.006483  0.031226  0.053854  ...  0.579032  1.003927  0.401682
5  0.014060  0.053458  0.096825  ...  0.968733  1.566175  1.130963
6  0.005811  0.050316  0.175818  ...  1.511975  2.279495  3.549401
7  0.000000  0.047535  0.200914  ...  3.148727  3.452754  5.613132
8  0.000000  0.000000  0.035845  ...  4.793819  6.948415  9.910119
9  0.000000  0.000000  0.002226  ...  0.104896  9.993986  0.000000

[10 rows x 10 columns]
lambda =  0.1
          0         1         2  ...         7         8         9
0  0.110055  0.000000  0.000000  ...  0.074745  0.083070  0.000000
1  0.000000  0.000000  0.006906  ...  0.157079  0.150931  0.000000
2  0.000049  0.010468  0.025441  ...  0.227003  0.191129  0.076901
3  0.002578  0.019332  0.036229  ...  0.345653  0.569933  0.013341
4  0.007501  0.032531  0.053998  ...  0.587985  1.016875  0.457981
5  0.015085  0.055838  0.094440  ...  0.973948  1.581948  1.174127
6  0.006940  0.053263  0.175418  ...  1.523217  2.271886  3.572816
7  0.000000  0.048377  0.206870  ...  3.163626  3.488413  5.642252
8  0.000000  0.000000  0.037013  ...  4.800136  6.951727  9.910005
9  0.000000  0.000000  0.002680  ...  0.106832  9.995085  0.000000

[10 rows x 10 columns]
lambda =  0.15
          0         1         2  ...         7         8         9
0  0.109080  0.000000  0.000000  ...  0.079361  0.090327  0.000000
1  0.000000  0.000000  0.007470  ...  0.158488  0.154339  0.000000
2  0.000113  0.011139  0.025913  ...  0.230497  0.192769  0.081107
3  0.002958  0.020448  0.035820  ...  0.351342  0.576116  0.027467
4  0.008631  0.033870  0.053961  ...  0.593616  1.027243  0.516184
5  0.016149  0.057926  0.092109  ...  0.977798  1.595764  1.214591
6  0.008234  0.056295  0.175871  ...  1.535534  2.263921  3.587942
7  0.000000  0.048943  0.212050  ...  3.178722  3.524968  5.672556
8  0.000000  0.000000  0.038022  ...  4.806478  6.955107  9.910136
9  0.000000  0.000000  0.003145  ...  0.108411  9.996189  0.000000

[10 rows x 10 columns]
lambda =  0.2
          0         1         2  ...         7         8         9
0  0.108401  0.000000  0.000000  ...  0.083978  0.097344  0.000000
1  0.000000  0.000000  0.007950  ...  0.159568  0.157150  0.000000
2  0.000209  0.011763  0.026305  ...  0.233288  0.193656  0.086781
3  0.003356  0.021592  0.035386  ...  0.355322  0.580838  0.046394
4  0.009903  0.035220  0.053798  ...  0.596014  1.035562  0.576402
5  0.017249  0.059757  0.089947  ...  0.980084  1.607117  1.252825
6  0.009681  0.059423  0.177304  ...  1.548896  2.255625  3.594214
7  0.000000  0.049295  0.216596  ...  3.193950  3.562281  5.703745
8  0.000000  0.000000  0.038891  ...  4.812815  6.958540  9.910555
9  0.000000  0.000000  0.003617  ...  0.109599  9.997298  0.000000

[10 rows x 10 columns]
lambda =  0.25
          0         1         2  ...         7         8         9
0  0.108150  0.000000  0.000000  ...  0.088530  0.103982  0.000000
1  0.000000  0.000000  0.008348  ...  0.160153  0.159327  0.000000
2  0.000340  0.012338  0.026632  ...  0.235168  0.193674  0.094294
3  0.003775  0.022757  0.034917  ...  0.357539  0.583948  0.070009
4  0.011339  0.036558  0.053553  ...  0.595393  1.042387  0.638658
5  0.018379  0.061394  0.088046  ...  0.980696  1.615682  1.289118
6  0.011270  0.062670  0.179814  ...  1.563341  2.247018  3.590889
7  0.000000  0.049513  0.220682  ...  3.209246  3.600232  5.735527
8  0.000000  0.000000  0.039630  ...  4.819124  6.962019  9.911316
9  0.000000  0.000000  0.004099  ...  0.110336  9.998419  0.000000

[10 rows x 10 columns]
lambda =  0.3
          0         1         2  ...         7         8         9
0  0.108439  0.000000  0.000000  ...  0.092956  0.110092  0.000000
1  0.000000  0.000000  0.008669  ...  0.160106  0.160813  0.000000
2  0.000515  0.012868  0.026906  ...  0.236018  0.192731  0.104044
3  0.004218  0.023930  0.034406  ...  0.358021  0.585411  0.098229
4  0.012946  0.037854  0.053263  ...  0.592109  1.048307  0.702880
5  0.019528  0.062915  0.086474  ...  0.979627  1.621301  1.323587
6  0.012992  0.066071  0.183478  ...  1.578977  2.238138  3.577039
7  0.000000  0.049693  0.224516  ...  3.224546  3.638726  5.767617
8  0.000000  0.000000  0.040247  ...  4.825386  6.965541  9.912480
9  0.000000  0.000000  0.004593  ...  0.110541  9.999559  0.000000

[10 rows x 10 columns]
lambda =  0.35
          0         1         2  ...         7          8         9
0  0.109370  0.000000  0.000000  ...  0.097200   0.115514  0.000000
1  0.000000  0.000000  0.008920  ...  0.159334   0.161537  0.000000
2  0.000739  0.013361  0.027131  ...  0.235819   0.190768  0.116472
3  0.004692  0.025088  0.033849  ...  0.356911   0.585328  0.131009
4  0.014714  0.039076  0.052957  ...  0.586681   1.053935  0.768888
5  0.020679  0.064411  0.085284  ...  0.976987   1.623975  1.356169
6  0.014835  0.069676  0.188358  ...  1.595977   2.229051  3.551545
7  0.000000  0.049938  0.228321  ...  3.239791   3.677698  5.799740
8  0.000000  0.000000  0.040745  ...  4.831586   6.969110  9.914117
9  0.000000  0.000000  0.005103  ...  0.110144  10.000731  0.000000

[10 rows x 10 columns]
lambda =  0.4
          0         1         2  ...         7          8         9
0  0.111045  0.000000  0.000000  ...  0.101214   0.120079  0.000000
1  0.000000  0.000000  0.009109  ...  0.157808   0.161420  0.000000
2  0.001020  0.013831  0.027306  ...  0.234664   0.187771  0.132087
3  0.005204  0.026205  0.033249  ...  0.354501   0.583973  0.168353
4  0.016603  0.040189  0.052664  ...  0.579812   1.059915  0.836392
5  0.021811  0.065982  0.084519  ...  0.973014   1.623848  1.386631
6  0.016790  0.073540  0.194503  ...  1.614584   2.219875  3.513095
7  0.000000  0.050362  0.232318  ...  3.254922   3.717122  5.831630
8  0.000000  0.000000  0.041117  ...  4.837717   6.972739  9.916296
9  0.000000  0.000000  0.005633  ...  0.109095  10.001952  0.000000

[10 rows x 10 columns]
lambda =  0.45
          0         1         2  ...         7          8         9
0  0.113571  0.000000  0.000000  ...  0.104969   0.123611  0.000000
1  0.000000  0.000000  0.009238  ...  0.155577   0.160384  0.000000
2  0.001362  0.014297  0.027425  ...  0.232783   0.183776  0.151494
3  0.005769  0.027253  0.032617  ...  0.351283   0.581833  0.210314
4  0.018549  0.041158  0.052417  ...  0.572413   1.066920  0.904987
5  0.022900  0.067738  0.084219  ...  0.968087   1.621205  1.414571
6  0.018847  0.077710  0.201952  ...  1.635107   2.210799  3.460177
7  0.000000  0.051085  0.236699  ...  3.269889   3.757020  5.863034
8  0.000000  0.000000  0.041353  ...  4.843775   6.976445  9.919089
9  0.000000  0.000000  0.006181  ...  0.107385  10.003246  0.000000

[10 rows x 10 columns]
lambda =  0.5
          0         1         2  ...         7          8         9
0  0.117065  0.000000  0.000000  ...  0.108455   0.125940  0.000000
1  0.000000  0.000000  0.009307  ...  0.152782   0.158366  0.000000
2  0.001774  0.014780  0.027485  ...  0.230582   0.178871  0.175415
3  0.006405  0.028202  0.031968  ...  0.347991   0.579664  0.256996
4  0.020454  0.041946  0.052252  ...  0.565630   1.075661  0.974160
5  0.023928  0.069811  0.084427  ...  0.962736   1.616460  1.439425
6  0.021000  0.082210  0.210722  ...  1.657924   2.202099  3.391071
7  0.000000  0.052231  0.241596  ...  3.284646   3.797465  5.893710
8  0.000000  0.000000  0.041429  ...  4.849766   6.980251  9.922563
9  0.000000  0.000000  0.006745  ...  0.105060  10.004645  0.000000

[10 rows x 10 columns]
lambda =  0.55
          0         1         2  ...         7          8         9
0  0.121653  0.000000  0.000000  ...  0.111678   0.126905  0.000000
1  0.000000  0.000000  0.009313  ...  0.149668   0.155343  0.000000
2  0.002262  0.015307  0.027492  ...  0.228684   0.173211  0.204709
3  0.007137  0.029027  0.031331  ...  0.345661   0.578565  0.308556
4  0.022195  0.042522  0.052218  ...  0.560859   1.086889  1.043292
5  0.024893  0.072354  0.085199  ...  0.957651   1.610147  1.460483
6  0.023250  0.087018  0.220809  ...  1.683479   2.194159  3.303849
7  0.000000  0.053937  0.247039  ...  3.299158   3.838590  5.923424
8  0.000000  0.000000  0.041312  ...  4.855698   6.984189  9.926779
9  0.000000  0.000000  0.007318  ...  0.102235  10.006194  0.000000

[10 rows x 10 columns]
lambda =  0.6
          0         1         2  ...         7          8         9
0  0.127467  0.000000  0.000000  ...  0.114646   0.126372  0.000000
1  0.000000  0.000000  0.009253  ...  0.146603   0.151374  0.000000
2  0.002837  0.015904  0.027466  ...  0.227989   0.167037  0.240387
3  0.007991  0.029713  0.030736  ...  0.345680   0.580062  0.365196
4  0.023629  0.042866  0.052375  ...  0.559765   1.101403  1.111686
5  0.025829  0.075556  0.086613  ...  0.953690   1.602912  1.476908
6  0.025623  0.092039  0.232180  ...  1.712291   2.187483  3.196363
7  0.000000  0.056354  0.252915  ...  3.313394   3.880589  5.951935
8  0.000000  0.000000  0.040957  ...  4.861587   6.988296  9.931782
9  0.000000  0.000000  0.007897  ...  0.099104  10.007955  0.000000

[10 rows x 10 columns]
lambda =  0.65
          0         1         2  ...         7          8         9
0  0.134630  0.000000  0.000000  ...  0.117327   0.124259  0.000000
1  0.000000  0.000000  0.009128  ...  0.144097   0.146676  0.000000
2  0.003512  0.016598  0.027443  ...  0.229726   0.160719  0.283609
3  0.008998  0.030264  0.030217  ...  0.349826   0.586219  0.427171
4  0.024603  0.042972  0.052804  ...  0.564284   1.120049  1.178591
5  0.026833  0.079635  0.088776  ...  0.951885   1.595493  1.487763
6  0.028176  0.097082  0.244758  ...  1.744951   2.182706  3.066240
7  0.000000  0.059672  0.258923  ...  3.327332   3.923720  5.978982
8  0.000000  0.000000  0.040309  ...  4.867451   6.992609  9.937602
9  0.000000  0.000000  0.008486  ...  0.095957  10.010007  0.000000

[10 rows x 10 columns]
lambda =  0.7
          0         1         2  ...         7          8         9
0  0.143245  0.000000  0.000000  ...  0.119582   0.120577  0.000000
1  0.000000  0.000000  0.008950  ...  0.142827   0.141720  0.000000
2  0.004298  0.017413  0.027469  ...  0.235503   0.154811  0.335652
3  0.010190  0.030719  0.029809  ...  0.360292   0.599757  0.494788
4  0.024979  0.042857  0.053613  ...  0.576623   1.143720  1.243247
5  0.028094  0.084837  0.091830  ...  0.953447   1.588705  1.492052
6  0.031030  0.101829  0.258413  ...  1.782131   2.180600  2.910881
7  0.000000  0.064143  0.264526  ...  3.340952   3.968300  6.004251
8  0.000000  0.000000  0.039307  ...  4.873302   6.997158  9.944235
9  0.000000  0.000000  0.009107  ...  0.093197  10.012448  0.000000

[10 rows x 10 columns]
lambda =  0.75
          0         1         2  ...         7          8         9
0  0.153366  0.000000  0.000000  ...  0.121032   0.115508  0.000000
1  0.000000  0.000000  0.008738  ...  0.143662   0.137380  0.000000
2  0.005202  0.018369  0.027580  ...  0.247326   0.150140  0.397857
3  0.011608  0.031178  0.029530  ...  0.379671   0.624186  0.568408
4  0.024657  0.042577  0.054951  ...  0.599235   1.173341  1.304944
5  0.029945  0.091404  0.095957  ...  0.959765   1.583412  1.488766
6  0.034388  0.105816  0.272949  ...  1.824581   2.182066  2.727456
7  0.000000  0.070137  0.268918  ...  3.354222   4.014696  6.027344
8  0.000000  0.000000  0.037899  ...  4.879138   7.001953  9.951637
9  0.000000  0.000000  0.009807  ...  0.091372  10.015393  0.000000

[10 rows x 10 columns]
lambda =  0.8
          0         1         2  ...         7          8         9
0  0.164967  0.000000  0.000000  ...  0.120872   0.109539  0.000000
1  0.000000  0.000000  0.008510  ...  0.147686   0.135110  0.000000
2  0.006221  0.019482  0.027738  ...  0.267585   0.147886  0.471511
3  0.013331  0.031841  0.029378  ...  0.410881   0.663945  0.648467
4  0.023599  0.042254  0.057041  ...  0.634793   1.209849  1.363094
5  0.032920  0.099532  0.101373  ...  0.972405   1.580493  1.476942
6  0.038579  0.108414  0.288078  ...  1.873132   2.188124  2.512924
7  0.000000  0.078217  0.270993  ...  3.367092   4.063313  6.047742
8  0.000000  0.000000  0.036043  ...  4.884930   7.006970  9.959713
9  0.000000  0.000000  0.010649  ...  0.091210  10.018970  0.000000

[10 rows x 10 columns]
lambda =  0.85
          0         1         2  ...         7          8         9
0  0.177904  0.000000  0.000000  ...  0.117588   0.103671  0.000000
1  0.000000  0.000000  0.008234  ...  0.156200   0.137149  0.000000
2  0.007343  0.020784  0.027721  ...  0.298962   0.149659  0.557684
3  0.015539  0.033046  0.029297  ...  0.457034   0.724540  0.735490
4  0.021844  0.042122  0.060226  ...  0.686129   1.254159  1.417328
5  0.037836  0.109287  0.108320  ...  0.993106   1.580806  1.455726
6  0.044081  0.108812  0.303403  ...  1.928701   2.199899  2.264098
7  0.000000  0.089277  0.269344  ...  3.379467   4.114560  6.064804
8  0.000000  0.000000  0.033700  ...  4.890601   7.012127  9.968314
9  0.000000  0.000000  0.011682  ...  0.093654  10.023302  0.000000

[10 rows x 10 columns]
lambda =  0.9
          0         1         2  ...         7          8         9
0  0.191881  0.000000  0.000000  ...  0.108561   0.099744  0.000000
1  0.000000  0.000000  0.007730  ...  0.170703   0.146707  0.000000
2  0.008576  0.022387  0.026881  ...  0.344263   0.157488  0.656963
3  0.018656  0.035326  0.029139  ...  0.521213   0.812693  0.830143
4  0.019476  0.042638  0.065080  ...  0.756191   1.307132  1.467624
5  0.045883  0.120487  0.117048  ...  1.023777   1.585153  1.424448
6  0.051534  0.106015  0.318383  ...  1.992321   2.218589  1.977805
7  0.000000  0.104718  0.262268  ...  3.391193   4.168791  6.077836
8  0.000000  0.000000  0.030794  ...  4.896008   7.017265  9.977249
9  0.000000  0.000000  0.012856  ...  0.099897  10.028491  0.000000

[10 rows x 10 columns]
lambda =  0.95
          0         1         2  ...         7          8         9
0  0.206427  0.000000  0.000000  ...  0.089536   0.100870  0.000000
1  0.000000  0.000000  0.006446  ...  0.192824   0.168042  0.000000
2  0.010051  0.024637  0.023700  ...  0.406181   0.173639  0.769085
3  0.023587  0.039457  0.028580  ...  0.606222   0.936531  0.933321
4  0.016489  0.044694  0.072593  ...  0.848010   1.369569  1.514512
5  0.058761  0.132522  0.127796  ...  1.066525   1.594264  1.382718
6  0.061718  0.098829  0.332308  ...  2.065258   2.245449  1.651278
7  0.000000  0.126718  0.247802  ...  3.402031   4.226211  6.086355
8  0.000000  0.000000  0.027115  ...  4.900924   7.022121  9.986324
9  0.000000  0.000000  0.013896  ...  0.111388  10.034592  0.000000

[10 rows x 10 columns]
lambda =  1.0
          0         1         2  ...         7          8         9
0  0.220945  0.000000  0.000000  ...  0.053918   0.111954  0.000000
1  0.000000  0.000000  0.003026  ...  0.224250   0.206234  0.000000
2  0.012284  0.028489  0.014980  ...  0.487058   0.200140  0.892396
3  0.032108  0.046509  0.026996  ...  0.714410   1.105973  1.046358
4  0.012447  0.050015  0.084510  ...  0.964820   1.442297  1.559426
5  0.078816  0.144104  0.140764  ...  1.123767   1.608839  1.330594
6  0.075471  0.085809  0.344294  ...  2.149333   2.281812  1.283010
7  0.000000  0.158558  0.223736  ...  3.411648   4.286745  6.090763
8  0.000000  0.000000  0.022167  ...  4.905015   7.026312  9.995401
9  0.000000  0.000000  0.014136  ...  0.129800  10.041592  0.000000

[10 rows x 10 columns]

Generate Results ✅

In [52]:
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 [53]:
# 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 [54]:
# 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 plots were shown after policy iteration cell
  2. Which one converges faster and why policy iteration converges faster. As we are going for better policy in each step and number of policies are limited it converges faster to a optimal policy.

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

As lambda increases variance increases and bias dereases.

2.c Policy iteration error curve

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

In [75]:
env = GridEnv_HW2(**base_kwargs)
res_PI, extra_info_PI = policy_iteration(env, 0.7)
J=[]
for j in extra_info_PI['J']:
  J.append(np.linalg.norm(res_PI['Values']-j)/10) 
print(J)
 # The rounding off is just for making print statement cleaner

plt.plot(range(len(J)),J)
[1.077909159600382, 0.14611038385429523, 0.0069067408774980635, 0.0001783122880595513, 1.0250354852444958e-05, 0.0]
Out[75]:
[<matplotlib.lines.Line2D at 0x7faa5a35c950>]

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 [76]:
## please run TD lamda evaluation before running this cell
for lamda in lamda_values:
  res_TD, extra_info_TD = td_lamda_results[lamda],extra_info[lamda]
  J=[]
  for j in extra_info_TD['J']:
    J.append(np.linalg.norm(res_TD['Values']-j)/10) 
  # The rounding off is just for making print statement cleaner
  plt.figure()
  plt.plot(range(len(J)),J)
  plt.title(lamda)
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:8: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  

Submit to AIcrowd 🚀

In [ ]:
!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%20IITM_Assignment_2_Gridworld_Release.ipynb for submission...
Removing existing files from submission directory...
Mounting Google Drive 💾
Your Google Drive will be mounted to access the colab notebook
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.activity.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fexperimentsandconfigs%20https%3a%2f%2fwww.googleapis.com%2fauth%2fphotos.native&response_type=code

Enter your authorization code:
1206

Comments

You must login before you can post a comment.

Execute