Loading

IIT-M RL-ASSIGNMENT-2-TAXI

Solution for submission 132341

A detailed solution for submission 132341 submitted for challenge IIT-M RL-ASSIGNMENT-2-TAXI

nachiket_dev_me18b017

What is the notebook about?

Problem - Taxi Environment Algorithms

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

  • Implement Policy Iteration
  • Implement Modified Policy Iteration
  • Implement Value Iteration
  • Implement Gauss Seidel Value Iteration
  • 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 [2]:
!pip install aicrowd-cli > /dev/null

AIcrowd Runtime Configuration 🧷

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

In [3]:
import os

AICROWD_DATASET_PATH = os.getenv("DATASET_PATH", os.getcwd()+"/13d77bb0-b325-4e95-a03b-833eb6694acd_a2_taxi_inputs.zip")
AICROWD_RESULTS_DIR = os.getenv("OUTPUTS_DIR", "results")
In [4]:

API Key valid
Saved API Key successfully!
13d77bb0-b325-4e95-a03b-833eb6694acd_a2_taxi_inputs.zip: 100% 31.2k/31.2k [00:00<00:00, 376kB/s]
In [5]:
!unzip $AICROWD_DATASET_PATH
Archive:  /content/13d77bb0-b325-4e95-a03b-833eb6694acd_a2_taxi_inputs.zip
   creating: inputs/
  inflating: inputs/inputs_base.npy  
  inflating: inputs/inputs_1.npy     
  inflating: inputs/inputs_0.npy     
  inflating: inputs/inputs_2.npy     
   creating: targets/
  inflating: targets/targets_2.npy   
  inflating: targets/targets_0.npy   
  inflating: targets/targets_1.npy   
  inflating: targets/targets_base.npy  
In [6]:
DATASET_DIR = 'inputs/'

Taxi Environment

Read the environment to understand the functions, but do not edit anything

In [7]:
import numpy as np

class TaxiEnv_HW2:
    def __init__(self, states, actions, probabilities, rewards, initial_policy):
        self.possible_states = states
        self._possible_actions = {st: ac for st, ac in zip(states, actions)}
        self._ride_probabilities = {st: pr for st, pr in zip(states, probabilities)}
        self._ride_rewards = {st: rw for st, rw in zip(states, rewards)}
        self.initial_policy = initial_policy
        self._verify()

    def _check_state(self, state):
        assert state in self.possible_states, "State %s is not a valid state" % state

    def _verify(self):
        """ 
        Verify that data conditions are met:
        Number of actions matches shape of next state and actions
        Every probability distribution adds up to 1 
        """
        ns = len(self.possible_states)
        for state in self.possible_states:
            ac = self._possible_actions[state]
            na = len(ac)

            rp = self._ride_probabilities[state]
            assert np.all(rp.shape == (na, ns)), "Probabilities shape mismatch"
        
            rr = self._ride_rewards[state]
            assert np.all(rr.shape == (na, ns)), "Rewards shape mismatch"

            assert np.allclose(rp.sum(axis=1), 1), "Probabilities don't add up to 1"

    def possible_actions(self, state):
        """ Return all possible actions from a given state """
        self._check_state(state)
        return self._possible_actions[state]

    def ride_probabilities(self, state, action):
        """ 
        Returns all possible ride probabilities from a state for a given action
        For every action a list with the returned with values in the same order as self.possible_states
        """
        actions = self.possible_actions(state)
        ac_idx = actions.index(action)
        return self._ride_probabilities[state][ac_idx]

    def ride_rewards(self, state, action):
        actions = self.possible_actions(state)
        ac_idx = actions.index(action)
        return self._ride_rewards[state][ac_idx]

Example of Environment usage

In [8]:
def check_taxienv():
    # These are the values as used in the pdf, but they may be changed during submission, so do not hardcode anything

    states = ['A', 'B', 'C']

    actions = [['1','2','3'], ['1','2'], ['1','2','3']]

    probs = [np.array([[1/2,  1/4,  1/4],
                    [1/16, 3/4,  3/16],
                    [1/4,  1/8,  5/8]]),

            np.array([[1/2,   0,     1/2],
                    [1/16,  7/8,  1/16]]),

            np.array([[1/4,  1/4,  1/2],
                    [1/8,  3/4,  1/8],
                    [3/4,  1/16, 3/16]]),]

    rewards = [np.array([[10,  4,  8],
                        [ 8,  2,  4],
                        [ 4,  6,  4]]),

            np.array([[14,  0, 18],
                        [ 8, 16,  8]]),

            np.array([[10,  2,  8],
                        [6,   4,  2],
                        [4,   0,  8]]),]
    initial_policy = {'A': '1', 'B': '1', 'C': '1'}

    env = TaxiEnv_HW2(states, actions, probs, rewards, initial_policy)
    print("All possible states", env.possible_states)
    print("All possible actions from state B", env.possible_actions('B'))
    print("Ride probabilities from state A with action 2", env.ride_probabilities('A', '2'))
    print("Ride rewards from state C with action 3", env.ride_rewards('C', '3'))

    base_kwargs = {"states": states, "actions": actions, 
                "probabilities": probs, "rewards": rewards,
                "initial_policy": initial_policy}
    return base_kwargs

base_kwargs = check_taxienv()
env = TaxiEnv_HW2(**base_kwargs)
All possible states ['A', 'B', 'C']
All possible actions from state B ['1', '2']
Ride probabilities from state A with action 2 [0.0625 0.75   0.1875]
Ride rewards from state C with action 3 [4 0 8]

Task 1 - Policy Iteration

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

In [9]:
# 1.1 Policy Iteration
def policy_iteration(taxienv, gamma):
    # A list of all the states
    states = taxienv.possible_states
    # Initial values
    values = {s: 0 for s in states}

    # This is a dictionary of states to policies -> e.g {'A': '1', 'B': '2', 'C': '1'}
    policy = taxienv.initial_policy.copy()

    ## Begin code here
    flag = False
    while not flag:
    #policy evaluation step
      while True:
        delta =0
        values_old =values.copy()
        for s in states:
          a=policy[s]
          J= [ i*gamma for i in list(values_old.values())]
          values[s] = sum(taxienv.ride_probabilities(s,a)* ( taxienv.ride_rewards(s,a) + J ))    
          delta = max(delta, abs(values[s] - values_old[s]))
        if delta < 1e-8:
          break 
    #policy improvement step
      flag =True
      for s in states:
        actions = taxienv.possible_actions(s)
        rewards = {a:0 for a in actions}
        for a in actions:
          J= [ i*gamma for i in list(values.values()) ]
          rewards[a] = sum(taxienv.ride_probabilities(s, a)* ( taxienv.ride_rewards(s, a) + J ))

        action=max(rewards, key=rewards.get)
        
        if policy[s] != action:
          policy[s]=action
          flag= False
          



    # Hints - 
    # Do not hardcode anything
    # Only the final result is required for the results
    # Put any extra data in "extra_info" dictonary for any plots etc
    # Use the helper functions taxienv.ride_rewards, taxienv.ride_probabilities,  taxienv.possible_actions
    # For terminating condition use the condition exactly mentioned in the pdf

    
    # Put your extra information needed for plots etc in this dictionary
    extra_info = {}

    ## Do not edit below this line

    # Final results
    return {"Expected Reward": values, "Policy": policy}, extra_info

Task 2 - Policy Iteration for multiple values of gamma

Ideally this code should run as is

In [10]:
# 1.2 Policy Iteration with different values of gamma
def run_policy_iteration(env):
    gamma_values = np.arange(5, 100, 5)/100
    results, extra_info = {}, {}
    for gamma in gamma_values:
        results[gamma], extra_info[gamma] = policy_iteration(env, gamma)
    return results, extra_info

results, extra_info = run_policy_iteration(env)

Task 3 - Modifed Policy Iteration

Implement modified policy iteration (where Value iteration is done for fixed m number of steps)

In [11]:
# 1.3 Modified Policy Iteration
def modified_policy_iteration(taxienv, gamma, m):
    # A list of all the states
    states = taxienv.possible_states
    # Initial values
    values = {s: 0 for s in states}

    # This is a dictionary of states to policies -> e.g {'A': '1', 'B': '2', 'C': '1'}
    policy = taxienv.initial_policy.copy()

    ## Begin code here
    flag = False
    while not flag:

    #policy evaluation step
      for i in range(m):
        values_old =values.copy()
        for s in states:
          a=policy[s]
          J= [ i*gamma for i in list(values_old.values())]
          values[s] = sum(taxienv.ride_probabilities(s,a)* ( taxienv.ride_rewards(s,a) + J ))    


    #policy improvement step
      flag =True
      for s in states:
        actions = taxienv.possible_actions(s)
        rewards = {a:0 for a in actions}
        for a in actions:
          J= [ i*gamma for i in list(values.values()) ]
          reward = sum(taxienv.ride_probabilities(s, a)* ( taxienv.ride_rewards(s, a) + J ))
          rewards[a]=reward
 

        action=max(rewards, key=rewards.get)
        if policy[s] != action:
          policy[s]=action
          flag= False
          

    # Hints - 
    # Do not hardcode anything
    # Only the final result is required for the results
    # Put any extra data in "extra_info" dictonary for any plots etc
    # Use the helper functions taxienv.ride_rewards, taxienv.ride_probabilities,  taxienv.possible_actions
    # For terminating condition use the condition exactly mentioned in the pdf

    
    # Put your extra information needed for plots etc in this dictionary
    extra_info = {}

    ## Do not edit below this line


    # Final results
    return {"Expected Reward": values, "Policy": policy}, extra_info

Task 4 Modified policy iteration for multiple values of m

Ideally this code should run as is

In [12]:
def run_modified_policy_iteration(env):
    m_values = np.arange(1, 15)
    gamma = 0.9
    results, extra_info = {}, {}
    for m in m_values:
        results[m], extra_info[m] = modified_policy_iteration(env, gamma, m)
    return results, extra_info

results, extra_info = run_modified_policy_iteration(env)

Task 5 Value Iteration

Implement value iteration and find the policy and expected rewards

In [13]:
# 1.4 Value Iteration
def value_iteration(taxienv, gamma):
    # A list of all the states
    states = taxienv.possible_states
    # Initial values
    values = {s: 0 for s in states}

    # This is a dictionary of states to policies -> e.g {'A': '1', 'B': '2', 'C': '1'}
    policy = taxienv.initial_policy.copy()

    ## Begin code here
    iter=0
    delta_values=[]
    while True:
      iter=iter+1
      delta=0
      values_old=values.copy()

      for s in states:
        actions=taxienv.possible_actions(s)
        rewards= {a:0 for a in actions}

        for a in actions:
                    J= [ i*gamma for i in list(values_old.values()) ]
                    rewards[a] = sum(taxienv.ride_probabilities(s, a)* ( taxienv.ride_rewards(s, a) + J ))
        action=max(rewards,key=rewards.get)
        values[s]=rewards[action]
        policy[s]=action

        delta=max(delta,abs(values[s]-values_old[s]))
      delta_values.append(delta)
      if delta < 1e-8:
        break



    # Hints - 
    # Do not hardcode anything
    # Only the final result is required for the results
    # Put any extra data in "extra_info" dictonary for any plots etc
    # Use the helper functions taxienv.ride_rewards, taxienv.ride_probabilities,  taxienv.possible_actions
    # For terminating condition use the condition exactly mentioned in the pdf


    # Put your extra information needed for plots etc in this dictionary
    extra_info = {"iter":iter}

    ## Do not edit below this line

    # Final results
    return {"Expected Reward": values, "Policy": policy}, extra_info

Task 6 Value Iteration with multiple values of gamma

Ideally this code should run as is

In [14]:
def run_value_iteration(env):
    gamma_values = np.arange(5, 100, 5)/100
    results = {}
    results, extra_info = {}, {}
    for gamma in gamma_values:
        results[gamma], extra_info[gamma] = value_iteration(env, gamma)
    return results, extra_info
  
results, extra_info = run_value_iteration(env)

Task 7 Gauss Seidel Value Iteration

Implement Gauss Seidel Value Iteration

In [15]:
# 1.4 Gauss Seidel Value Iteration
def gauss_seidel_value_iteration(taxienv, gamma):
    # A list of all the states
    # For Gauss Seidel Value Iteration - iterate through the values in the same order
    states = taxienv.possible_states

    # Initial values
    values = {s: 0 for s in states}

    # This is a dictionary of states to policies -> e.g {'A': '1', 'B': '2', 'C': '1'}
    policy = taxienv.initial_policy.copy()

    # Hints - 
    # Do not hardcode anything
    # For Gauss Seidel Value Iteration - iterate through the values in the same order as taxienv.possible_states
    # Only the final result is required for the results
    # Put any extra data in "extra_info" dictonary for any plots etc
    # Use the helper functions taxienv.ride_rewards, taxienv.ride_probabilities,  taxienv.possible_actions
    # For terminating condition use the condition exactly mentioned in the pdf

    ## Begin code here

    iter=0
    delta_values=[]
    while True:
      iter=iter+1
      delta=0
      values_old=values.copy()
      for s in states:
        actions=taxienv.possible_actions(s)
        rewards= {a:0 for a in actions}
        for a in actions:
          J= [ i*gamma for i in list(values.values()) ]
          rewards[a] = sum(taxienv.ride_probabilities(s, a)* ( taxienv.ride_rewards(s, a) + J ))

        action=max(rewards,key=rewards.get)
        values[s]=rewards[action]
        policy[s]=action

        delta=max(delta,abs(values[s]-values_old[s]))
        delta_values.append(delta)

      if delta <1e-8:
        break
    
    
    # Put your extra information needed for plots etc in this dictionary
    extra_info = {"iter":iter}

    ## Do not edit below this line

    # Final results
    return {"Expected Reward": values, "Policy": policy}, extra_info

Task 8 Gauss Seidel Value Iteration with multiple values of gamma

Ideally this code should run as is

In [16]:
def run_gauss_seidel_value_iteration(env):
    gamma_values = np.arange(5, 100, 5)/100
    results = {}
    results, extra_info = {}, {}
    for gamma in gamma_values:
        results[gamma], extra_info[gamma] = gauss_seidel_value_iteration(env, gamma)
    return results, extra_info

results, extra_info = run_gauss_seidel_value_iteration(env)

Generate Results ✅

In [17]:
# Do not edit this cell
def get_results(kwargs):

    taxienv = TaxiEnv_HW2(**kwargs)

    policy_iteration_results = run_policy_iteration(taxienv)[0]
    modified_policy_iteration_results = run_modified_policy_iteration(taxienv)[0]
    value_iteration_results = run_value_iteration(taxienv)[0]
    gs_vi_results = run_gauss_seidel_value_iteration(taxienv)[0]

    final_results = {}
    final_results["policy_iteration"] = policy_iteration_results
    final_results["modifed_policy_iteration"] = modified_policy_iteration_results
    final_results["value_iteration"] = value_iteration_results
    final_results["gauss_seidel_iteration"] = gs_vi_results

    return final_results
In [18]:
# 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 local score

This score 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 [19]:
# 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):
    param_matches = []
    for k in results:
        param_results = results[k]
        param_targets = targets[k]
        policy_match = param_results['Policy'] == param_targets['Policy']
        rv = [v for k, v in param_results['Expected Reward'].items()]
        tv = [v for k, v in param_targets['Expected Reward'].items()]
        rewards_match = np.allclose(rv, tv, rtol=3)
        equal = rewards_match and policy_match
        param_matches.append(equal)
    return np.mean(param_matches)

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

Implement The following

1.1: Find an optimal policy using policy iteration(Algorithm 3) starting with a policy that will always cruise independent of the town, and a zero value vector. Let γ = 0.9.

In [20]:
gamma = 0.9
results, extra_info = policy_iteration(env, gamma)
reward = results["Expected Reward"]
policy = results["Policy"]
print("Optimal Policy",policy)
print("Expected Rewards",reward)
Optimal Policy {'A': '2', 'B': '2', 'C': '2'}
Expected Rewards {'A': 121.65347103938102, 'B': 135.3062754397477, 'C': 122.83690299204375}

Optimal Policy is to Always take action 2 i.e Go to the nearest taxi stand and wait in line.

1.2: Run policy iteration for discount factors γ ranging from 0 to 0.95 with intervals of 0.05 and display the results.

In [21]:
results, extra_info = run_policy_iteration(env)
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 5), dpi=100)
plt.title("Expected Reward Vs Gamma Values Plot")
plt.xlabel('Gamma values')
plt.ylabel('Expected rewards')
plt.xticks(list(results.keys()))

cities = ['A','B','C']
for city in cities:
  plt.plot(list(results.keys()),[i['Expected Reward'][city] for i in results.values()],marker='o',linewidth=0.5, markersize=3)

plt.legend(["City_A","City_B","City_C"])
plt.show()
In [22]:
##printing all rewards and policy wrt to gamma
print("Expected Reward")
for gamma in results.keys():
  rewards = results[gamma]['Expected Reward']
  print("Gamma",gamma,rewards)

print("\nPolicy")
for gamma in results.keys():
  policy = results[gamma]['Policy']
  print("Gamma",gamma,policy)
Expected Reward
Gamma 0.05 {'A': 8.511527294182539, 'B': 16.400259908653545, 'C': 7.498869066334438}
Gamma 0.1 {'A': 9.076506148654659, 'B': 16.856368562663413, 'C': 8.050865123013633}
Gamma 0.15 {'A': 9.708121492773689, 'B': 17.46450304225433, 'C': 8.66916045381265}
Gamma 0.2 {'A': 10.437030073770368, 'B': 18.482142855718322, 'C': 9.384398494823}
Gamma 0.25 {'A': 11.274074071593612, 'B': 19.62962962714457, 'C': 10.207407404926943}
Gamma 0.3 {'A': 12.243837242514767, 'B': 20.93406593274288, 'C': 11.162756161433684}
Gamma 0.35 {'A': 13.37871443314124, 'B': 22.430769227661276, 'C': 12.282824022182337}
Gamma 0.4 {'A': 14.722222218890456, 'B': 24.16666666333477, 'C': 13.611111107779344}
Gamma 0.45 {'A': 16.334131264623938, 'B': 26.2055335916294, 'C': 15.207370701243658}
Gamma 0.5 {'A': 18.298701292975394, 'B': 28.636363630637724, 'C': 17.155844150118252}
Gamma 0.55 {'A': 20.789988631690285, 'B': 31.607396693357217, 'C': 19.830725208961304}
Gamma 0.6 {'A': 24.025686435735523, 'B': 35.32772363679841, 'C': 23.458813096497263}
Gamma 0.65 {'A': 28.276692058262245, 'B': 40.0962805733634, 'C': 28.12997877956433}
Gamma 0.7 {'A': 34.06193076352557, 'B': 46.435416151978885, 'C': 34.36604100348755}
Gamma 0.75 {'A': 42.31741137421433, 'B': 55.285053901178884, 'C': 43.10631738345932}
Gamma 0.8 {'A': 55.0793650415215, 'B': 68.55820102035747, 'C': 56.269841231997695}
Gamma 0.85 {'A': 77.24651208813728, 'B': 90.81170060881541, 'C': 78.43345570831532}
Gamma 0.9 {'A': 121.65347103938102, 'B': 135.3062754397477, 'C': 122.83690299204375}
Gamma 0.95 {'A': 255.0229082403122, 'B': 268.76461831792886, 'C': 256.20284924326205}

Policy
Gamma 0.05 {'A': '1', 'B': '1', 'C': '1'}
Gamma 0.1 {'A': '1', 'B': '1', 'C': '1'}
Gamma 0.15 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.2 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.25 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.3 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.35 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.4 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.45 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.5 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.55 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.6 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.65 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.7 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.75 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.8 {'A': '2', 'B': '2', 'C': '2'}
Gamma 0.85 {'A': '2', 'B': '2', 'C': '2'}
Gamma 0.9 {'A': '2', 'B': '2', 'C': '2'}
Gamma 0.95 {'A': '2', 'B': '2', 'C': '2'}

1.3: Find an optimal policy using modified policy iteration(Algorithm 4) starting with a policy that will always cruise independent of the town, and a zero value vector. Let γ = 0.9 and m = 5

In [23]:
##simply just running modified PI with given values
gamma = 0.9
m = 5
results, extra_info = modified_policy_iteration(env, gamma, m)
rewards = results["Expected Reward"]
policy = results["Policy"]
print("Optimal Policy  ",policy)
print("Expected Rewards",rewards)
Optimal Policy   {'A': '2', 'B': '2', 'C': '2'}
Expected Rewards {'A': 89.81178760453517, 'B': 103.46459982778873, 'C': 90.99521888644551}

For Modified PI , Optimal Policy is to Always take action 2 i.e Go to the nearest taxi stand and wait in line

1.4: Find optimal values using value iteration(Algorithm 1) starting with a zero vector. Let γ = 0.9.

In [24]:
gamma = 0.9
results, extra_info = value_iteration(env, gamma)
rewards = results["Expected Reward"]
policy = results["Policy"]
print("Optimal Policy",policy)
print("Expected Rewards",rewards)
Optimal Policy {'A': '2', 'B': '2', 'C': '2'}
Expected Rewards {'A': 121.65347103895924, 'B': 135.30627543932593, 'C': 122.83690299162194}

For VI , Optimal Policy is to Always take action 2 i.e Go to the nearest taxi stand and wait in line. Expected Rewards are

{'A': 121.65347103895924, 'B': 135.30627543932593, 'C': 122.83690299162194}

1.5: Find optimal values using Gauss-Seidel value iteration(Algorithm 2) starting with a zero vector. Let γ = 0.9.

In [25]:
gamma = 0.9
results, extra_info = gauss_seidel_value_iteration(env, gamma)
rewards = results["Expected Reward"]
policy = results["Policy"]
print("Optimal Policy",policy)
print("Expected Rewards",rewards)
Optimal Policy {'A': '2', 'B': '2', 'C': '2'}
Expected Rewards {'A': 121.65347104963263, 'B': 135.30627544959796, 'C': 122.83690300915262}

For Gauss-Seidel VI , Optimal Policy is to Always take action 2 i.e Go to the nearest taxi stand and wait in line. Expected Rewards are

{'A': 121.65347104963263, 'B': 135.30627544959796, 'C': 122.83690300915262}

Subjective questions

1.a How are values of $\gamma$ affecting results of policy iteration

We can see from the graph that higher $\gamma$ gives more Expected reward. This can be reasond as follows

since 1-$\gamma$ is the probabilty our taxi drivers car will break down, the longer the care can run , the more money he can make.

If $\gamma$ was 0 , his car would immediatly break and he cannot make money

If $\gamma$ was 1 , his car will never break and he'll make a treamendous (tending to infinity) amount of money

In [26]:
results, extra_info = run_policy_iteration(env)
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 5), dpi=100)
plt.title("Expected Reward Vs Gamma Values Plot")
plt.xlabel('Gamma values')
plt.ylabel('Expected rewards')
plt.xticks(list(results.keys()))

cities = ['A','B','C']
for city in cities:
  plt.plot(list(results.keys()),[i['Expected Reward'][city] for i in results.values()],marker='o',linewidth=0.5, markersize=3)

plt.legend(["City_A","City_B","City_C"])
plt.show()
In [27]:
""" our policy changes as follows

Gamma 0.05 {'A': '1', 'B': '1', 'C': '1'}
Gamma 0.1 {'A': '1', 'B': '1', 'C': '1'}
Gamma 0.15 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.2 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.25 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.3 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.35 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.4 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.45 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.5 {'A': '1', 'B': '2', 'C': '1'}
Gamma 0.55 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.6 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.65 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.7 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.75 {'A': '1', 'B': '2', 'C': '2'}
Gamma 0.8 {'A': '2', 'B': '2', 'C': '2'}
Gamma 0.85 {'A': '2', 'B': '2', 'C': '2'}
Gamma 0.9 {'A': '2', 'B': '2', 'C': '2'}
Gamma 0.95 {'A': '2', 'B': '2', 'C': '2'}

we can easily see how it changes from "1" ie cruise the streets to look for a passenger to "2" ie  go to nearest taxi line and wait

this can be reasoned as with low gamma driver doesn't have alot of trips he can make and therefore chooses "1" which is the short term 
maximizer , while "2" is the long term maximizer which he can choose when the car has low change of breaking down"""
Out[27]:
' our policy changes as follows\n\nGamma 0.05 {\'A\': \'1\', \'B\': \'1\', \'C\': \'1\'}\nGamma 0.1 {\'A\': \'1\', \'B\': \'1\', \'C\': \'1\'}\nGamma 0.15 {\'A\': \'1\', \'B\': \'2\', \'C\': \'1\'}\nGamma 0.2 {\'A\': \'1\', \'B\': \'2\', \'C\': \'1\'}\nGamma 0.25 {\'A\': \'1\', \'B\': \'2\', \'C\': \'1\'}\nGamma 0.3 {\'A\': \'1\', \'B\': \'2\', \'C\': \'1\'}\nGamma 0.35 {\'A\': \'1\', \'B\': \'2\', \'C\': \'1\'}\nGamma 0.4 {\'A\': \'1\', \'B\': \'2\', \'C\': \'1\'}\nGamma 0.45 {\'A\': \'1\', \'B\': \'2\', \'C\': \'1\'}\nGamma 0.5 {\'A\': \'1\', \'B\': \'2\', \'C\': \'1\'}\nGamma 0.55 {\'A\': \'1\', \'B\': \'2\', \'C\': \'2\'}\nGamma 0.6 {\'A\': \'1\', \'B\': \'2\', \'C\': \'2\'}\nGamma 0.65 {\'A\': \'1\', \'B\': \'2\', \'C\': \'2\'}\nGamma 0.7 {\'A\': \'1\', \'B\': \'2\', \'C\': \'2\'}\nGamma 0.75 {\'A\': \'1\', \'B\': \'2\', \'C\': \'2\'}\nGamma 0.8 {\'A\': \'2\', \'B\': \'2\', \'C\': \'2\'}\nGamma 0.85 {\'A\': \'2\', \'B\': \'2\', \'C\': \'2\'}\nGamma 0.9 {\'A\': \'2\', \'B\': \'2\', \'C\': \'2\'}\nGamma 0.95 {\'A\': \'2\', \'B\': \'2\', \'C\': \'2\'}\n\nwe can easily see how it changes from "1" ie cruise the streets to look for a passenger to "2" ie  go to nearest taxi line and wait\n\nthis can be reasoned as with low gamma driver doesn\'t have alot of trips he can make and therefore chooses "1" which is the short term \nmaximizer , while "2" is the long term maximizer which he can choose when the car has low change of breaking down'

1.b For modified policy itetaration, do you find any improvement if you choose m=10.

Here Optimal Policy remains same , yet there is a difference in Expected reward , for m=10 , we see a larger expected reward for all 3 cities hence we can conclude there is improvment in choosing m=10

In [28]:
gamma = 0.9
m = 5
results5, extra_info = modified_policy_iteration(env, gamma, m)
rewards5 = results5["Expected Reward"]
policy5 = results5["Policy"]
print("Optimal Policy" ,policy5)
print("Expected Rewards",rewards5)

gamma = 0.9
m = 10
results10, extra_info = modified_policy_iteration(env, gamma, m)
rewards10 = results10["Expected Reward"]
policy10 = results10["Policy"]

print("\nOptimal Policy",policy10)
print("Expected Rewards ",rewards10)
Optimal Policy {'A': '2', 'B': '2', 'C': '2'}
Expected Rewards {'A': 89.81178760453517, 'B': 103.46459982778873, 'C': 90.99521888644551}

Optimal Policy {'A': '2', 'B': '2', 'C': '2'}
Expected Rewards  {'A': 113.12458909097927, 'B': 126.77739349151406, 'C': 114.3080210436424}

Another thing to consider is how our Expected reward from modified PI is now closer to the expected reward from normal PI. This would indicate that we are getting more accurate values of expected reward with m=10 when compared with m=5 , and the difference here is significant. at higher values of m , say m=15 or 20 it could converge and therefore not show significant improvment , but between 5 and 10 it is showing

1.c Compare and contrast the behavior of Value Iteration and Gauss Seidel Value Iteraton

Here we see that VI reaches completion in more number of iterations than GS for all values of Gamma. Hence we can say that GS is a better algorithm as it gives us the answer in lower number of iterations.

In [29]:
import matplotlib.pyplot as plt

resultsvi, extra_infovi = run_value_iteration(env)
resultsgs, extra_infogs = run_gauss_seidel_value_iteration(env)
plt.figure(figsize=(10, 5), dpi=100)
plt.xlabel('Gamma')
plt.ylabel('Iterations')
plt.xticks(list(extra_infovi.keys()))
VI_iter= [extra_infovi[gamma]['iter'] for gamma in extra_infovi.keys()]
GS_iter=[extra_infogs[gamma]['iter'] for gamma in extra_infogs.keys()]
plt.plot(list(extra_infovi.keys()), VI_iter, color='cyan', marker='o', linewidth=0.5, markersize=5, label = "VI")
plt.plot(list(extra_infogs.keys()), GS_iter, color='red', marker='o', linewidth=0.5, markersize=5, label = "GS")

plt.legend()
plt.show()

Submit to AIcrowd 🚀

In [ ]:
!DATASET_PATH=$AICROWD_DATASET_PATH aicrowd notebook submit -c iit-m-rl-assignment-2-taxi -a assets
WARNING: No assets directory at assets... Creating one...
No jupyter lab module found. Using jupyter notebook.
Using notebook: /content/Copy%20of%20IITM_Assignment_2_Taxi_Release.ipynb for submission...
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:
In [ ]:

1228

Comments

You must login before you can post a comment.

Execute