【强化学习】SARSA

本文通过实现Taxi-v1环境中的SARSA算法,对比了SARSA与Q-Learning两种强化学习方法。两者都采用ϵ-greedy策略选取动作,但SARSA在更新Q值时继续采用该策略,而Q-Learning则采用贪婪策略。

在这里插入图片描述

import matplotlib.pylab as plt
#%matplotlib inline
import random
import gym
env = gym.make('Taxi-v1')
env.render()

Q = {}
for s in range(env.observation_space.n):
    for a in range(env.action_space.n):
        Q[(s,a)] = 0.0
        
def epsilon_greedy(state, epsilon):
    if random.uniform(0,1) < epsilon:
        return env.action_space.sample()
    else:
        return max(list(range(env.action_space.n)), key = lambda x: Q[(state,x)])

alpha = 0.85
gamma = 0.90
epsilon = 1

R = []
for i in range(800):
    
    # we store cumulative reward of each episodes in r
    r = 0
    
    # initialize the state,
    state = env.reset()
    
    # select the action using epsilon-greedy policy
    action = epsilon_greedy(state,epsilon)
    
    while True:
       
        # env.render()
        
        # then we perform the action and move to the next state, and receive the reward
        nextstate, reward, done, _ = env.step(action)
        
        # again, we select the next action using epsilon greedy policy
        nextaction = epsilon_greedy(nextstate,max(0.01,epsilon/(i+1))) 
    
        # we calculate the Q value of previous state using our update rule
        Q[(state,action)] += alpha * (reward + gamma * Q[(nextstate,nextaction)]-Q[(state,action)])

        # finally we update our state and action with next action and next state
        action = nextaction
        state = nextstate
        
        # store the rewards
        r += reward
        
        # we will break the loop, if we are at the terminal state of the episode
        if done:
            break
            
    print("total reward: ", r)
    R.append(r)

env.close()
plt.plot(R)
plt.show()

在这里插入图片描述

sarsa 和 Q-learning 的区别就在一个 max 上:

  • 它们在采取实际动作时,都是用 ϵ−greedy\epsilon-greedyϵgreedy 策略
  • 在更新 Q 函数时,sarsa 仍采用 ϵ−greedy\epsilon-greedyϵgreedy 策略得到下一个动作,而 Q-learning 使用的是 greedygreedygreedy 策略。基于这一点,称 sarsa 是 on-policy 的,而 Q-learning 是 off-policy 的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值