Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Reinforcement Learning Q-learning and SARSA

Reinforcement Learning Q-learning and SARSA

In the field of artificial intelligence, reinforcement learning is a method that enables an agent to learn how to achieve goals through interaction with its environment.

Imagine teaching a puppy a new command: it performs an action (such as sitting), you give it a reward (a treat), and it gradually learns to respond correctly when hearing the command. Q-learning and SARSA are two classic and crucial algorithms in reinforcement learning, and they are what the agent relies on to learn,what action is best in what stateThese are the core tools. This article will clearly explain the principles, differences, and implementations of these two algorithms.


Foundations of Reinforcement Learning and Markov Decision Processes

Before diving into Q-learning and SARSA, we need to understand the theoretical framework they share.

Core Concepts

Reinforcement learning problems are usually modeled as a Markov Decision Process. It contains the following key elements:

Goals and Value Functions

The agent's ultimate goal is to maximize long-term cumulative reward, not just immediate reward. To this end, we introduce,Value Function。

To balance immediate and future rewards, we usethe discount factor γ (typically in the range [0, 1]). The reward at future step k is multiplied by γ^k, which means the agent values near-term rewards more.


Q-learning: Off-Policy Temporal Difference Learning

Q-learning is anoff-policyalgorithm, proposed by Watkins in 1989. Its core idea is that the agent indirectly finds the optimal policy by learning an optimal Q-value table.

Core of the Algorithm: Q-Value Update Formula

The learning process of Q-learning is driven by the following formula: Q(s_t, a_t) ← Q(s_t, a_t) + α * [ r_{t+1} + γ * max_{a} Q(s_{t+1}, a) - Q(s_t, a_t) ]

Let's break down this formula:

Meaning of Off-Policy

Q-learning is calledoff-policy, because when updating Q values, the action used to evaluate future value (max_{a} Q(s_{t+1}, a)) and the agent's actual exploratory actionsare separated.。

This separation allows Q-learning to boldly learn from its estimate of the optimal path, even while taking random exploratory actions.

Algorithm Flow


SARSA: On-Policy Temporal Difference Learning

The name SARSA comes from the state-action sequence involved in its update process:(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}). It is anon-policyalgorithm.

Core of the Algorithm: Q-Value Update Formula

SARSA's update formula is very similar to that of Q-learning, but with one key difference: Q(s_t, a_t) ← Q(s_t, a_t) + α * [ r_{t+1} + γ * Q(s_{t+1}, a_{t+1}) - Q(s_t, a_t) ]

Note the second part:

In SARSA, future value is estimated from the action the agent will actually take inthe next state s_{t+1} the next state, that is, the a_{t+1} Q value of that action.

Meaning of On-Policy

SARSA is calledon-policy, because the policy it uses to update Q values (target policy) and the policy used to select actions (behavior policy)are the same, typically both ε-greedy policies.


Comparison of Q-learning and SARSA

Understanding the difference between the two is key to mastering them. The table below clearly summarizes the core differences:

Feature Q-learning SARSA
Strategy type off-policy on-policy
Update target Based on the optimal action:r + γ * max Q(s', a') Based on the actual action:r + γ * Q(s', a_{t+1})
Learning goals Studyoptimal policythe Q function of the optimal action Studyexecution policythe Q function of (e.g., ε-greedy)
Risk tendency More "bold," assuming optimal actions will be taken in the future More "conservative," considering the risks that future exploration may bring
Update timing in (s, a, r, s') can be updated after Needed (s, a, r, s', a') can only be updated with the five-tuple
Typical application Discrete environments, seeking the global optimum Environments with high safety requirements that need to avoid dangerous states

Classic Cliff Walking Problem Example

This example vividly illustrates the difference between the two. Imagine a grid world where the agent walks from the start S to the goal G, with a cliff below; falling off results in a large negative reward and a return to the start.

Conclusion: In environments that require balancing exploration and exploitation and where mistaken actions are costly, SARSA usually learns safer and more robust policies.


Code Practice: Implementing Q-learning and SARSA in Python

We will use a simple 4x4 grid world to demonstrate both algorithms. The goal is to have the agent move from the upper-left corner (0,0) to the lower-right corner (3,3)。

Environment setup

Example

import

numpy

as

np

import

random

class

GridWorld:

   

def

init

(

self

,

size

=

4

)

:

       

self

.

size

=

size

       

self

.

state

=

(

0

,

0

)

Start point

       

self

.

goal

=

(

size-

1

,

size-

1

)

Endpoint

       

self

.

actions

=

[

'up'

,

'down'

,

'left'

,

'right'

]

       

self

.

action_map

=

{

'up'

:

(

1

,

0

)

,

'down'

:

(

1

,

0

)

,

'left'

:

(

0

,

1

)

,

'right'

:

(

0

,

1

)

}

   

def

reset

(

self

)

:

       

"""Reset the environment to the starting point"""

       

self

.

state

=

(

0

,

0

)

       

return

self

.

state

   

def

step

(

self

,

action

)

:

       

"""Take an action and return (next state, reward, done)"""

        move

=

self

.

action_map

[

action

]

        next_state

=

(

self

.

state

[

0

]

[

0

]

,

self

.

state

[

1

]

[

1

]

)

       

Boundary check: if out of bounds, stay in place

       

if

not

(

0

<=

next_state

[

0

]

<

self

.

size

and

0

<=

next_state

[

1

]

<

self

.

size

)

:

            next_state

=

self

.

state

       

self

.

state

=

next_state

       

Reward setting: reaching the goal gives a reward of 10; other moves give -1 (to encourage reaching the goal quickly)

       

if

next_state

==

self

.

goal

:

            reward

=

10

            done

=

True

       

else

:

            reward

=

1

            done

=

False

       

return

next_state

,

reward

,

done

   

def

get_actions

(

self

)

:

       

return

self

.

actions

Q-learning Algorithm Implementation

Example

def

q_learning

(

env

,

episodes

=

500

,

alpha

=

0.1

,

gamma

=

0.9

,

epsilon

=

0.1

)

:

   

"""
    Implement the Q-learning algorithm
    env: environment object
    episodes: number of training episodes
    alpha: learning rate
    gamma: discount factor
    epsilon: exploration probability in the ε-greedy policy
    """

   

Initialize the Q-table with dimensions [grid rows, grid columns, number of actions]

    q_table

=

np.

zeros

(

(

env.

size

,

env.

size

,

len

(

env.

actions

)

)

)

   

for

episode

in

range

(

episodes

)

:

        state

=

env.

reset

(

)

        done

=

False

       

while

not

done:

           

1. Select an action using the ε-greedy policy

           

if

random

.

uniform

(

0

,

1

)

<

epsilon:

                action_idx

=

random

.

randint

(

0

,

len

(

env.

actions

)

1

)

Exploration: choose randomly

           

else

:

                action_idx

=

np.

argmax

(

q_table

[

state

[

0

]

,

state

[

1

]

,

:

]

)

Exploitation: choose the one with the largest Q-value

            action

=

env.

actions

[

action_idx

]

           

2. Execute the action and get feedback

            next_state

,

reward

,

done

=

env.

step

(

action

)

           

3. Core Q-learning update

           

Q-value of the current state-action pair

            current_q

=

q_table

[

state

[

0

]

,

state

[

1

]

,

action_idx

]

           

Maximum Q-value of the next state (the key to off-policy)

            next_max_q

=

np.

max

(

q_table

[

next_state

[

0

]

,

next_state

[

1

]

,

:

]

)

           

Compute the target Q-value

            target_q

=

reward + gamma * next_max_q

           

Update the Q-table

            q_table

[

state

[

0

]

,

state

[

1

]

,

action_idx

]

=

current_q + alpha *

(

target_q - current_q

)

           

Transition to the next state

            state

=

next_state

   

return

q_table

SARSA algorithm implementation

Example

def

sarsa

(

env

,

episodes

=

500

,

alpha

=

0.1

,

gamma

=

0.9

,

epsilon

=

0.1

)

:

   

"""
    Implement the SARSA algorithm
    Parameters have the same meaning as in Q-learning
    """

    q_table

=

np.

zeros

(

(

env.

size

,

env.

size

,

len

(

env.

actions

)

)

)

   

for

episode

in

range

(

episodes

)

:

        state

=

env.

reset

(

)

        done

=

False

       

SARSA needs to select an action for the initial state first

       

if

random

.

uniform

(

0

,

1

)

<

epsilon:

            action_idx

=

random

.

randint

(

0

,

len

(

env.

actions

)

1

)

       

else

:

            action_idx

=

np.

argmax

(

q_table

[

state

[

0

]

,

state

[

1

]

,

:

]

)

        action

=

env.

actions

[

action_idx

]

       

while

not

done:

           

1. Execute the action selected in the previous step

            next_state

,

reward

,

done

=

env.

step

(

action

)

           

2. Select an action for the next state (on-policy, still using ε-greedy)

           

if

random

.

uniform

(

0

,

1

)

<

epsilon:

                next_action_idx

=

random

.

randint

(

0

,

len

(

env.

actions

)

1

)

           

else

:

                next_action_idx

=

np.

argmax

(

q_table

[

next_state

[

0

]

,

next_state

[

1

]

,

:

]

)

            next_action

=

env.

actions

[

next_action_idx

]

           

3. Core SARSA update

            current_q

=

q_table

[

state

[

0

]

,

state

[

1

]

,

action_idx

]

           

Key difference: use the next state'saction that will actually be executedQ-value

            next_q

=

q_table

[

next_state

[

0

]

,

next_state

[

1

]

,

next_action_idx

]

            target_q

=

reward + gamma * next_q

            q_table

[

state

[

0

]

,

state

[

1

]

,

action_idx

]

=

current_q + alpha *

(

target_q - current_q

)

           

4. Update the state and action for the next iteration

            state

=

next_state

            action_idx

=

next_action_idx

            action

=

next_action

   

return

q_table

Testing and policy visualization

Example

def

test_policy

(

env

,

q_table

,

episodes

=

10

)

:

   

"""Test the learned policy"""

    total_rewards

=

[

]

   

for

_

in

range

(

episodes

)

:

        state

=

env.

reset

(

)

        done

=

False

        total_reward

=

0

        steps

=

[

]

       

while

not

done:

           

Use a greedy policy during testing (no exploration)

            action_idx

=

np.

argmax

(

q_table

[

state

[

0

]

,

state

[

1

]

,

:

]

)

            action

=

env.

actions

[

action_idx

]

            next_state

,

reward

,

done

=

env.

step

(

action

)

            steps.

append

(

action

[

0

]

.

upper

(

)

)

Record the first letter of each action

            total_reward +

=

reward

            state

=

next_state

        total_rewards.

append

(

total_reward

)

       

print

(

f

"Episode steps: {steps}, Total reward: {total_reward}"

)

   

print

(

f

"Average reward: {np.mean(total_rewards):.2f}"

)

Create environment

env

=

GridWorld

(

size

=

4

)

print

(

"=== Train and test Q-learning ==="

)

q_table_ql

=

q_learning

(

env

,

episodes

=

1000

)

test_policy

(

env

,

q_table_ql

)

print

(

"\n=== Train and test SARSA ==="

)

env.

reset

(

)

Reset the environment state

q_table_sarsa

=

sarsa

(

env

,

episodes

=

1000

)

test_policy

(

env

,

q_table_sarsa

)

Simple comparison of the final policies

print

(

"\n=== Policy comparison (actions from the start point (0,0)) ==="

)

start_q_values

=

q_table_ql

[

0

,

0

,

:

]

start_sarsa_values

=

q_table_sarsa

[

0

,

0

,

:

]

print

(

f

"Q-learning Q-values: {dict(zip(env.actions, start_q_values))}"

)

print

(

f

"Recommended action: {env.actions[np.argmax(start_q_values)]}"

)

print

(

f

"SARSA Q-values: {dict(zip(env.actions, start_sarsa_values))}"

)

print

(

f

"Recommended action: {env.actions[np.argmax(start_sarsa_values)]}"

)