The Wayback Machine - https://web.archive.org/web/20241005072351/https://www.geeksforgeeks.org/ml-reinforcement-learning-algorithm-python-implementation-using-q-learning/
Open In App

ML | Reinforcement Learning Algorithm : Python Implementation using Q-learning

Last Updated : 07 Jun, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: Q-Learning technique.

Reinforcement Learning is a type of Machine Learning paradigms in which a learning algorithm is trained not on preset data but rather based on a feedback system. These algorithms are touted as the future of Machine Learning as these eliminate the cost of collecting and cleaning the data.

In this article, we are going to demonstrate how to implement a basic Reinforcement Learning algorithm which is called the Q-Learning technique. In this demonstration, we attempt to teach a bot to reach its destination using the Q-Learning technique.

Step 1: Importing the required libraries




import numpy as np
import pylab as pl
import networkx as nx


Step 2: Defining and visualising the graph




edges = [(0, 1), (1, 5), (5, 6), (5, 4), (1, 2), 
         (1, 3), (9, 10), (2, 4), (0, 6), (6, 7),
         (8, 9), (7, 8), (1, 7), (3, 9)]
  
goal = 10
G = nx.Graph()
G.add_edges_from(edges)
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
pl.show()


Note: The above graph may not look the same on reproduction of the code because the networkx library in python produces a random graph from the given edges.

Step 3: Defining the reward the system for the bot




MATRIX_SIZE = 11
M = np.matrix(np.ones(shape =(MATRIX_SIZE, MATRIX_SIZE)))
M *= -1
  
for point in edges:
    print(point)
    if point[1] == goal:
        M[point] = 100
    else:
        M[point] = 0
  
    if point[0] == goal:
        M[point[::-1]] = 100
    else:
        M[point[::-1]]= 0
        # reverse of point
  
M[goal, goal]= 100
print(M)
# add goal point round trip


Step 4: Defining some utility functions to be used in the training




Q = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))
  
gamma = 0.75
# learning parameter
initial_state = 1
  
# Determines the available actions for a given state
def available_actions(state):
    current_state_row = M[state, ]
    available_action = np.where(current_state_row >= 0)[1]
    return available_action
  
available_action = available_actions(initial_state)
  
# Chooses one of the available actions at random
def sample_next_action(available_actions_range):
    next_action = int(np.random.choice(available_action, 1))
    return next_action
  
  
action = sample_next_action(available_action)
  
def update(current_state, action, gamma):
  
  max_index = np.where(Q[action, ] == np.max(Q[action, ]))[1]
  if max_index.shape[0] > 1:
      max_index = int(np.random.choice(max_index, size = 1))
  else:
      max_index = int(max_index)
  max_value = Q[action, max_index]
  Q[current_state, action] = M[current_state, action] + gamma * max_value
  if (np.max(Q) > 0):
    return(np.sum(Q / np.max(Q)*100))
  else:
    return (0)
# Updates the Q-Matrix according to the path chosen
  
update(initial_state, action, gamma)


Step 5: Training and evaluating the bot using the Q-Matrix




scores = []
for i in range(1000):
    current_state = np.random.randint(0, int(Q.shape[0]))
    available_action = available_actions(current_state)
    action = sample_next_action(available_action)
    score = update(current_state, action, gamma)
    scores.append(score)
  
# print("Trained Q matrix:")
# print(Q / np.max(Q)*100)
# You can uncomment the above two lines to view the trained Q matrix
  
# Testing
current_state = 0
steps = [current_state]
  
while current_state != 10:
  
    next_step_index = np.where(Q[current_state, ] == np.max(Q[current_state, ]))[1]
    if next_step_index.shape[0] > 1:
        next_step_index = int(np.random.choice(next_step_index, size = 1))
    else:
        next_step_index = int(next_step_index)
    steps.append(next_step_index)
    current_state = next_step_index
  
print("Most efficient path:")
print(steps)
  
pl.plot(scores)
pl.xlabel('No of iterations')
pl.ylabel('Reward gained')
pl.show()


Now, Let’s bring this bot to a more realistic setting. Let us imagine that the bot is a detective and is trying to find out the location of a large drug racket. He naturally concludes that the drug sellers will not sell their products in a location which is known to be frequented by the police and the selling locations are near the location of the drug racket. Also, the sellers leave a trace of their products where they sell it and this can help the detective in finding out the required location. We want to train our bot to find the location using these Environmental Clues.

Step 6: Defining and visualizing the new graph with the environmental clues




# Defining the locations of the police and the drug traces
police = [2, 4, 5]
drug_traces = [3, 8, 9]
  
G = nx.Graph()
G.add_edges_from(edges)
mapping = {0:'0 - Detective', 1:'1', 2:'2 - Police', 3:'3 - Drug traces',
           4:'4 - Police', 5:'5 - Police', 6:'6', 7:'7', 8:'Drug traces',
           9:'9 - Drug traces', 10:'10 - Drug racket location'}
  
H = nx.relabel_nodes(G, mapping)
pos = nx.spring_layout(H)
nx.draw_networkx_nodes(H, pos, node_size =[200, 200, 200, 200, 200, 200, 200, 200])
nx.draw_networkx_edges(H, pos)
nx.draw_networkx_labels(H, pos)
pl.show() 


Note: The above graph may look a bit different from the previous graph but they, in fact, are the same graphs. This is due to the random placement of nodes by the networkx library.

Step 7: Defining some utility functions for the training process




Q = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))
env_police = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))
env_drugs = np.matrix(np.zeros([MATRIX_SIZE, MATRIX_SIZE]))
initial_state = 1
  
# Same as above
def available_actions(state):
    current_state_row = M[state, ]
    av_action = np.where(current_state_row >= 0)[1]
    return av_action
  
# Same as above
def sample_next_action(available_actions_range):
    next_action = int(np.random.choice(available_action, 1))
    return next_action
  
# Exploring the environment
def collect_environmental_data(action):
    found = []
    if action in police:
        found.append('p')
    if action in drug_traces:
        found.append('d')
    return (found)
  
   
available_action = available_actions(initial_state)
action = sample_next_action(available_action)
  
def update(current_state, action, gamma):
  max_index = np.where(Q[action, ] == np.max(Q[action, ]))[1]
  if max_index.shape[0] > 1:
      max_index = int(np.random.choice(max_index, size = 1))
  else:
      max_index = int(max_index)
  max_value = Q[action, max_index]
  Q[current_state, action] = M[current_state, action] + gamma * max_value
  environment = collect_environmental_data(action)
  if 'p' in environment:
    env_police[current_state, action] += 1
  if 'd' in environment:
    env_drugs[current_state, action] += 1
  if (np.max(Q) > 0):
    return(np.sum(Q / np.max(Q)*100))
  else:
    return (0)
# Same as above
update(initial_state, action, gamma)
  
def available_actions_with_env_help(state):
    current_state_row = M[state, ]
    av_action = np.where(current_state_row >= 0)[1]
  
    # if there are multiple routes, dis-favor anything negative
    env_pos_row = env_matrix_snap[state, av_action]
  
    if (np.sum(env_pos_row < 0)):
        # can we remove the negative directions from av_act?
        temp_av_action = av_action[np.array(env_pos_row)[0]>= 0]
        if len(temp_av_action) > 0:
            av_action = temp_av_action
    return av_action
# Determines the available actions according to the environment


Step 8: Visualising the Environmental matrices




scores = []
for i in range(1000):
    current_state = np.random.randint(0, int(Q.shape[0]))
    available_action = available_actions(current_state)
    action = sample_next_action(available_action)
    score = update(current_state, action, gamma)
  
# print environmental matrices
print('Police Found')
print(env_police)
print('')
print('Drug traces Found')
print(env_drugs)


Step 9: Training and evaluating the model




scores = []
for i in range(1000):
    current_state = np.random.randint(0, int(Q.shape[0]))
    available_action = available_actions_with_env_help(current_state)
    action = sample_next_action(available_action)
    score = update(current_state, action, gamma)
    scores.append(score)
  
pl.plot(scores)
pl.xlabel('Number of iterations')
pl.ylabel('Reward gained')
pl.show()


The example taken above was a very basic one and many practical examples like Self Driving Cars involve the concept of Game Theory.



Previous Article
Next Article

Similar Reads

Genetic Algorithm for Reinforcement Learning : Python implementation
Most beginners in Machine Learning start with learning Supervised Learning techniques such as classification and regression. However, one of the most important paradigms in Machine Learning is Reinforcement Learning (RL) which is able to tackle many challenging tasks. It is an aspect of Machine learning where an agent learns to behave in an environ
5 min read
Epsilon-Greedy Algorithm in Reinforcement Learning
In Reinforcement Learning, the agent or decision-maker learns what to do—how to map situations to actions—so as to maximize a numerical reward signal. The agent is not explicitly told which actions to take, but instead must discover which action yields the most reward through trial and error. Multi-Armed Bandit Problem The multi-armed bandit proble
4 min read
Upper Confidence Bound Algorithm in Reinforcement Learning
In Reinforcement learning, the agent or decision-maker generates its training data by interacting with the world. The agent must learn the consequences of its actions through trial and error, rather than being explicitly told the correct action. Multi-Armed Bandit Problem In Reinforcement Learning, we use Multi-Armed Bandit Problem to formalize the
6 min read
Dyna Algorithm in Reinforcement Learning
The Dyna algorithm introduces a hybrid approach that leverages both real-world and simulated experiences, enhancing the agent's learning efficiency. This article delves into the key concepts, architecture, and benefits of the Dyna algorithm, along with its applications. Table of Content Understanding Dyna Algorithm in Reinforcement Learning Key Con
5 min read
Actor-Critic Algorithm in Reinforcement Learning
Reinforcement learning (RL) stands as a pivotal component in the realm of artificial intelligence, enabling agents to learn optimal decision-making strategies through interaction with their environments. Let's Dive into the actor-critic algorithm, a key concept in reinforcement learning, and learn how it can improve your machine learning models. Ta
12 min read
Reinforcement Learning in Python: Implementing SARSA Agent in Taxi Environment
SARSA (State-Action-Reward-State-Action) is an on-policy reinforcement learning algorithm that updates its policy based on the current state-action pair, the reward received, the next state, and the next action chosen by the current policy. In this article, we will implement SARSA in Gymnasium's Taxi-v3 environment, walking through the setup, agent
8 min read
SARSA Reinforcement Learning
Prerequisites: Q-Learning techniqueSARSA algorithm is a slight variation of the popular Q-Learning algorithm. For a learning agent in any Reinforcement Learning algorithm it's policy can be of two types:- On Policy: In this, the learning agent learns the value function according to the current action derived from the policy currently being used.Off
5 min read
Introduction to Thompson Sampling | Reinforcement Learning
Reinforcement Learning is a branch of Machine Learning, also called Online Learning. It is used to decide what action to take at t+1 based on data up to time t. This concept is used in Artificial Intelligence applications such as walking. A popular example of reinforcement learning is a chess engine. Here, the agent decides upon a series of moves d
4 min read
Neural Logic Reinforcement Learning - An Introduction
Neural Logic Reinforcement Learning is an algorithm that combines logic programming with deep reinforcement learning methods. Logic programming can be used to express knowledge in a way that does not depend on the implementation, making programs more flexible, compressed and understandable. It enables knowledge to be separated from use, ie the mach
3 min read
Expected SARSA in Reinforcement Learning
Prerequisites: SARSASARSA and Q-Learning technique in Reinforcement Learning are algorithms that uses Temporal Difference(TD) Update to improve the agent's behaviour. Expected SARSA technique is an alternative for improving the agent's policy. It is very similar to SARSA and Q-Learning, and differs in the action value function it follows. Expected
9 min read
Understanding Reinforcement Learning in-depth
The subject of reinforcement learning has absolutely grown in recent years ever since the astonishing results with old Atari games deep Minds victory with AlphaGo stunning breakthroughs in robotic arm manipulation which even beats professional players at 1v1 dota. Since the impressive breakthrough in the ImageNet classification challenge in 2012, s
13 min read
Sparse Rewards in Reinforcement Learning
Prerequisite: Understanding Reinforcement Learning in-depth In the previous articles, we learned about reinforcement learning, as well as the general paradigm and the issues with sparse reward settings. In this article, we'll dive a little further into some more technical work aimed at resolving the sparse reward setting problem. The fact that we'r
15+ min read
A Beginner's Guide to Deep Reinforcement Learning
Deep Reinforcement Learning (DRL) is the crucial fusion of two powerful artificial intelligence fields: deep neural networks and reinforcement learning. By combining the benefits of data-driven neural networks and intelligent decision-making, it has sparked an evolutionary change that crosses traditional boundaries. In this article, we take a detai
10 min read
On-policy vs off-policy methods Reinforcement Learning
In the world of Reinforcement Learning (RL), two primary approaches dictate how an agent (like a robot or a software program) learns from its environment: On-policy methods and Off-policy methods. Understanding the difference between these two is crucial for grasping the fundamentals of RL. This tutorial aims to demystify the concepts, providing a
13 min read
Model-Free Reinforcement Learning: An Overview
In Reinforcement learning, we have agents that use a particular 'algorithm' to interact with the environment. Now this algorithm can be model-based or model-free. The traditional algorithms are model-based in the sense they tend to develop a 'model' for the environment. This developed model captured the 'transition probability' and 'rewards' for ea
15+ min read
Function Approximation in Reinforcement Learning
Function approximation is a critical concept in reinforcement learning (RL), enabling algorithms to generalize from limited experience to a broader set of states and actions. This capability is essential when dealing with complex environments where the state and action spaces are vast or continuous. This article delves into the significance, method
5 min read
Multi-Agent Reinforcement Learning in AI
Reinforcement learning (RL) can solve complex problems through trial and error, learning from the environment to make optimal decisions. While single-agent reinforcement learning has made remarkable strides, many real-world problems involve multiple agents interacting within the same environment. This is where multi-agent reinforcement learning (MA
7 min read
Optimizing Production Scheduling with Reinforcement Learning
Production scheduling is a critical aspect of manufacturing operations, involving the allocation of resources to tasks over time to optimize various performance metrics such as throughput, lead time, and resource utilization. Traditional scheduling methods often struggle to cope with the dynamic and complex nature of modern manufacturing environmen
10 min read
Reinforcement Learning with TensorFlow Agents
Reinforcement learning (RL) represents a dynamic and powerful approach within machine learning, focusing on how agents should take actions in an environment to maximize cumulative rewards. TensorFlow Agents (TF-Agents) is a versatile and user-friendly library designed to streamline the process of developing RL algorithms and applications. This arti
6 min read
How does reward maximization work in reinforcement learning?
Reinforcement learning (RL) is a subset of machine learning that enables an agent to learn optimal behaviors through interactions with an environment to maximize cumulative rewards. In essence, RL revolves around the concept of reward maximization, where an agent takes actions that maximize the expected long-term reward. This article delves into th
7 min read
Differences between Model-free and Model-based Reinforcement Learning
Reinforcement learning (RL) is a type of machine learning where an agent learns to make decisions by performing actions in an environment to maximize some notion of cumulative reward. Two primary approaches in RL are model-free and model-based reinforcement learning. This article explores the distinctions between these two methodologies. Overview o
7 min read
What is Markov Decision Process (MDP) and Its relevance to Reinforcement Learning
In artificial intelligence and machine learning, Reinforcement Learning (RL) stands out as a powerful technique for training agents to make sequential decisions. At the heart of RL lies the concept of the Markov Decision Process (MDP). Understanding MDPs is crucial for comprehending how RL algorithms work and why they are effective. This article de
5 min read
Reinforcement Learning for Production Scheduling : The SOLO Method
Production scheduling is a critical aspect of manufacturing and operations management, involving the allocation of resources, planning of production activities, and optimization of workflows to meet demand while minimizing costs and maximizing efficiency. Traditional methods often rely on heuristic or rule-based approaches, which can be inflexible
7 min read
Multi-armed Bandit Problem in Reinforcement Learning
The Multi-Armed Bandit (MAB) problem is a classic problem in probability theory and decision-making that captures the essence of balancing exploration and exploitation. This problem is named after the scenario of a gambler facing multiple slot machines (bandits) and needing to determine which machine to play to maximize their rewards. The MAB probl
7 min read
Reinforcement learning
Reinforcement Learning: An OverviewReinforcement Learning (RL) is a branch of machine learning focused on making decisions to maximize cumulative rewards in a given situation. Unlike supervised learning, which relies on a training dataset with predefined answers, RL involves learning through experience. In RL, an agent learns to achieve a goal in a
8 min read
How to Visualize and Interact with Environments in Reinforcement Learning?
Reinforcement learning (RL) is a crucial area of machine learning where agents learn to make decisions by interacting with an environment. Visualization of these interactions is essential for understanding the behavior of agents and improving their learning algorithms. One of the popular tools for this purpose is the Python gym library, which provi
3 min read
How to Make a Reward Function in Reinforcement Learning?
One of the most critical components in RL is the reward function. It drives the agent's learning process by providing feedback on the actions it takes, guiding it toward achieving the desired outcomes. Crafting a proper reward function is essential to ensure that the agent learns the correct behavior. In this article, we’ll explore how to make a re
7 min read
Supervised vs Reinforcement vs Unsupervised
The Machine learning (ML) is a subfield of artificial intelligence (AI) that enables systems to learn from the data identify patterns and make decisions with the minimal human intervention. By leveraging large amounts of data and powerful algorithms machine learning has transformed industries such as the healthcare, finance and robotics. The three
7 min read
Box Blur Algorithm - With Python implementation
The pixels in an image are represented as integers. After blurring each pixel 'x' of the resulting image has a value equal to the average of the pixels surrounding 'x' including 'x'. For example, consider a 3 * 3 image as [Tex] image = \begin{bmatrix} 1 & 1 & 1\\ 1 & 7 & 1\\ 1 & 1 & 1 \end{bmatrix} [/Tex] Then, the resulting
4 min read
Implementation of Perceptron Algorithm for NOT Logic Gate
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: [Tex]\[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \\ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \\ \text { where } \Theta(v)=\left\{\begin{arra
2 min read
Article Tags :
Practice Tags :