Certainly! Let's go through a simple example of reinforcement learning using the Q-learning algorithm. We'll use a basic environment, the Frozen Lake, which is available in the gym library.
Here's a step-by-step guide:
Install the Gym library:
If you haven't already, you need to install the gym library. You can do this using pip:
bash
pip install gym
Import the necessary libraries:
python
import gym
import numpy as np
Create the environment:
We'll use the Frozen Lake environment.
python
env = gym.make('FrozenLake-v1')
Initialize the Q-table:
The Q-table will store the Q-values for each state-action pair.
rewards_all_episodes = []
for episode in range(num_episodes):
# Initialize new episode params
state = env.reset()
done = False
rewards_current_episode = 0
for step in range(max_steps_per_episode):
# Exploration-exploitation trade-off
exploration_rate_threshold = np.random.uniform(0, 1)
if exploration_rate_threshold > exploration_rate:
action = np.argmax(q_table[state, :])
else:
action = env.action_space.sample()
# Take the action
new_state, reward, done, info = env.step(action)
# Update Q-table
q_table[state, action] = q_table[state, action] * (1 - learning_rate) + \
learning_rate * (reward + discount_rate * np.max(q_table[new_state, :]))
# Set state as new state
state = new_state
# Add reward
rewards_current_episode += reward
if done:
break
# Exploration rate decay
exploration_rate = min_exploration_rate + \
(max_exploration_rate - min_exploration_rate) * np.exp(-exploration_decay_rate * episode)
rewards_all_episodes.append(rewards_current_episode)
# Calculate and print the average reward per thousand episodes
rewards_per_thousand_episodes = np.split(np.array(rewards_all_episodes), num_episodes/1000)
count = 1000
print("********Average reward per thousand episodes********\n")
for r in rewards_per_thousand_episodes:
print(count, ": ", str(sum(r/1000)))
count += 1000
# Print the final Q-table
print("\n\n********Q-table********\n")
print(q_table)
Use the trained Q-table to play the game:
python
for episode in range(3):
state = env.reset()
done = False
print("\nEpisode ", episode + 1)
for step in range(max_steps_per_episode):
env.render()
action = np.argmax(q_table[state, :])
new_state, reward, done, info = env.step(action)
if done:
env.render()
print("Score: ", reward)
break
state = new_state
env.close()
This code will train an agent using the Q-learning algorithm on the Frozen Lake environment and then use the learned Q-table to play the game. The agent will learn to navigate the frozen lake to reach the goal without falling into holes.