The Wayback Machine - https://web.archive.org/web/20240927175102/https://www.geeksforgeeks.org/sarsa-reinforcement-learning/
Open In App

SARSA Reinforcement Learning

Last Updated : 21 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: Q-Learning technique
SARSA 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:- 
 

  1. On Policy: In this, the learning agent learns the value function according to the current action derived from the policy currently being used.
  2. Off Policy: In this, the learning agent learns the value function according to the action derived from another policy.


Q-Learning technique is an Off Policy technique and uses the greedy approach to learn the Q-value. SARSA technique, on the other hand, is an On Policy and uses the action performed by the current policy to learn the Q-value.
This difference is visible in the difference of the update statements for each technique:- 
 

  1. Q-Learning: Q(s_{t},a_{t}) = Q(s_{t},a_{t}) + \alpha (r_{t+1}+\gamma max_{a}Q(s_{t+1},a)-Q(s_{t},a_{t}))
  2. SARSA: Q(s_{t},a_{t}) = Q(s_{t},a_{t}) + \alpha (r_{t+1}+\gamma Q(s_{t+1},a_{t+1})-Q(s_{t},a_{t}))


Here, the update equation for SARSA depends on the current state, current action, reward obtained, next state and next action. This observation lead to the naming of the learning technique as SARSA stands for State Action Reward State Action which symbolizes the tuple (s, a, r, s’, a’).
The following Python code demonstrates how to implement the SARSA algorithm using the OpenAI’s gym module to load the environment.
Step 1: Importing the required libraries
 

Python3

import numpy as np
import gym

                    

Step 2: Building the environment
Here, we will be using the ‘FrozenLake-v0’ environment which is preloaded into gym. You can read about the environment description here.
 

Python3

#Building the environment
env = gym.make('FrozenLake-v0')

                    

Step 3: Initializing different parameters
 

Python3

#Defining the different parameters
epsilon = 0.9
total_episodes = 10000
max_steps = 100
alpha = 0.85
gamma = 0.95
 
#Initializing the Q-matrix
Q = np.zeros((env.observation_space.n, env.action_space.n))

                    

Step 4: Defining utility functions to be used in the learning process
 

Python3

#Function to choose the next action
def choose_action(state):
    action=0
    if np.random.uniform(0, 1) < epsilon:
        action = env.action_space.sample()
    else:
        action = np.argmax(Q[state, :])
    return action
 
#Function to learn the Q-value
def update(state, state2, reward, action, action2):
    predict = Q[state, action]
    target = reward + gamma * Q[state2, action2]
    Q[state, action] = Q[state, action] + alpha * (target - predict)

                    

Step 5: Training the learning agent
 

Python3

#Initializing the reward
reward=0
 
# Starting the SARSA learning
for episode in range(total_episodes):
    t = 0
    state1 = env.reset()
    action1 = choose_action(state1)
 
    while t < max_steps:
        #Visualizing the training
        env.render()
         
        #Getting the next state
        state2, reward, done, info = env.step(action1)
 
        #Choosing the next action
        action2 = choose_action(state2)
         
        #Learning the Q-value
        update(state1, state2, reward, action1, action2)
 
        state1 = state2
        action1 = action2
         
        #Updating the respective vaLues
        t += 1
        reward += 1
         
        #If at the end of learning process
        if done:
            break

                    

In the above output, the red mark determines the current position of the agent in the environment while the direction given in brackets gives the direction of movement that the agent will make next. Note that the agent stays at it’s position if goes out of bounds.
Step 6: Evaluating the performance
 

Python3

#Evaluating the performance
print ("Performance : ", reward/total_episodes)
 
#Visualizing the Q-matrix
print(Q)

                    

SARSA (State-Action-Reward-State-Action) is a reinforcement learning algorithm that is used to learn a policy for an agent interacting with an environment. It is a type of on-policy algorithm, which means that it learns the value function and the policy based on the actions that are actually taken by the agent.

The SARSA algorithm works by maintaining a table of action-value estimates Q(s, a), where s is the state and a is the action taken by the agent in that state. The table is initialized to some arbitrary values, and the agent uses an epsilon-greedy policy to select actions.

Here are the steps involved in the SARSA algorithm:

Initialize the action-value estimates Q(s, a) to some arbitrary values.

  1. Set the initial state s.
  2. Choose the initial action a using an epsilon-greedy policy based on the current Q values.
  3. Take the action a and observe the reward r and the next state s’.
  4. Choose the next action a’ using an epsilon-greedy policy based on the updated Q values.
  5. Update the action-value estimate for the current state-action pair using the SARSA update rule:
  6. Q(s, a) = Q(s, a) + alpha * (r + gamma * Q(s’, a’) – Q(s, a))

where alpha is the learning rate, gamma is the discount factor, and r + gamma * Q(s’, a’) is the estimated return for the next state-action pair.

Set the current state s to the next state s’, and the current action a to the next action a’.

Repeat steps 4-7 until the episode ends.

The SARSA algorithm learns a policy that balances exploration and exploitation, and can be used in a variety of applications, including robotics, game playing, and decision making. However, it is important to note that the convergence of the SARSA algorithm can be slow, especially in large state spaces, and there are other reinforcement learning algorithms that may be more effective in certain situations.



Previous Article
Next Article

Similar Reads

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
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
ML | Reinforcement Learning Algorithm : Python Implementation using Q-learning
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
6 min read
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
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
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
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
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
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
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
Introduction to Multi-Task Learning(MTL) for Deep Learning
Multi-Task Learning (MTL) is a type of machine learning technique where a model is trained to perform multiple tasks simultaneously. In deep learning, MTL refers to training a neural network to perform multiple tasks by sharing some of the network's layers and parameters across tasks. In MTL, the goal is to improve the generalization performance of
6 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works & what is happening under
6 min read
Fusion Learning - The One Shot Federated Learning
Introduction Machine Learning has improved our lives significantly. Right from the intelligent chatbots to autonomous cars. The main ingredient which improves these models to perform beyond expectation is data. With the digitization and increased popularity of IoT, more and more people have devices that are generating immense amounts of quality dat
5 min read
Article Tags :
Practice Tags :