# Exercise TD q-learning with frozenlake from gym API

## Introduction

In this notebook you will use Temporal-Difference learning (TD learning), especially the Q-learning algorithm to train the agent for the Frozenlake environment provided by the gym API. The main difference between TD learning and Monte Carlo methods is that instead of learning from whole episodes one goes even one more step back and learns based on a step by step approach.

To get familiar with the Frozenlake environment it is suggested to read through the first part of the notebook exercise-monte-carlo-frozenlake-gym. Also the usage of tie-breaking argmax and policy performance testing is explaned their in more detail.

## Requirements

### Knowledge

To solve this notebook you should aquire knowledge about Temporal-Difference learning, especially Q-learning, agent-environment interaction, state-action values and policy improvement.

### Prerequisites

Read SUT18 chapter 6 to gain knowledge about the mentioned topics and terms. SUT18 is the standard literature for reinforcment learning and the basis for this and following notebooks.

## Python Modules

import gym
import numpy as np
import matplotlib.pyplot as plt

## Frozenlake environment

env = gym.make('FrozenLake-v0')
env.reset()
env.render()

### Tie-breaking argmax

def random_argmax_axis1(b):
""" a random tie-breaking argmax"""
return np.argmax(np.random.random(b.shape) * (b.T==b.max(axis=1)).T, axis=1)

##$\epsilon$-greedy policy

def epsilon_policy(s,Q_sa,env,epsilon=0.2):

if np.random.uniform(0,1) < epsilon:
action = env.action_space.sample() #exploration
else:
action = random_argmax_axis1(Q_sa)[s] #explotation
return action

# Exercise

Implement the Q-learning algorithm given in chapter 6.5 in SUT18.

def q_learning(env,nb_episode,alpha=0.5,gamma=0.95):

"""
Args:
env: given environment
nb_episode: number of episodes used for training
Kwargs:
alpha: learning rate for Q-learning
gamma: discount rate

Return:
Q_sa: learned Q-table
"""

Q_sa = np.zeros((env.observation_space.n,env.action_space.n))

#for e in range(nb_episode):

#done = False
#while not done:

#generate steps

#q_learning

return NotImplementedError

## Training the agent

Q_sa = q_learning(env,100000)
print(Q_sa)

## Test performance after training

Since each performance test might lead to a different value accordingly to the random nature of our frozenlake environment due to its slippery condition, it is usefull to find the mean over many tests. Reaching over 0.7 means your learning was succesful.

greedy_policy = random_argmax_axis1(Q_sa)
print(greedy_policy)
policy = lambda s: greedy_policy[s]
def test_performance(policy, nb_episodes=100):
sum_returns = 0
for i in range(nb_episodes):
state  = env.reset()
done = False
while not done:
action = policy(state)
state, reward, done, info = env.step(action)
if done:
sum_returns += reward
return sum_returns/nb_episodes
mean_performance_list = []
mean_performance = 0
n = 300
for i in range(n):
performance = test_performance(policy)
mean_performance_list.append(performance)
mean_performance += performance

print(mean_performance/n)
plt.hist(mean_performance_list,bins=30)
plt.grid()
plt.xlabel("Policy performance")
plt.show()

## Literature

The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).

exercise-TD-q-learning-frozenlake-gym

Oliver Fischer