强化学习笔记:多臂老虎机问题(5)--Optimistic Initial Value

目录

0. 前言

1. Optimistic Initial Value

2. 仿真

2.1 sample-average method

2.2 Constant Step-size alpha=0.1

3. 仿真结果分析和讨论

4. Exercises


0. 前言


        前面几节我们已经就多臂老虎机问题进行了一些讨论。详细参见:

        强化学习笔记:多臂老虎机问题(1)

        强化学习笔记:多臂老虎机问题(2)--Python仿真

        强化学习笔记:多臂老虎机问题(3)--行动价值估计的增量实现

        强化学习笔记:多臂老虎机问题(4)--跟踪非平稳环境

        本节我们继续基于基于多臂老虎机问题探讨行动-价值估计的初始值对强化学习的影响。

        Ref: Sutton-RLBook2020-2.6: Optimistic Initial Value

1. Optimistic Initial Value

到目前为止所讨论的方法都某种程度上依赖于行动-价值估计的初始设定Q1(a)。用统计学的语言来说,这些方法称为有偏的(biased by their initial estimates)。对于sample-average methods,这种偏置在每个行动都被选择了至少一次之后就消失了。而对于采用 的指数加权平均方法,这种偏置会一直存在(虽然会随着时间推移而呈指数方式减小—因此从近似意义上来说时间足够长之后就消失了)。

实际上,这种偏置通常并不是一个问题,有时候甚至还会有所帮助。这种依赖于初始值的有偏方法的不利之处在于需要用户去设定这些初始值(哪怕仅仅是置为全0)。有利之处是有可能利用初始值设定将一些先验信息提供给模型。

行动价值初始值设定可以提供一种简单的鼓励exploration的方法。设想在前面讨论的10-armed testbed中,将所有行动价值初始值全部设定为5而不是0,考虑到q^*(a)是从标准正态分布(均值为0方差为1)中采样的,初始值设置为5是非常乐观的设定。在最初阶段,不管选择什么行动,都极大概率地会将对应行动的价值估计值拉低,因此agent会因为对所受到的奖励反馈“失望”而转而选择其它的行动(即表现出对exploration的偏好),直到每个行动都被选择了若干次导致行动价值估计基本上收敛后才会结束对exploration的偏好。注意,即便在0-greedy策略中agent也会在进行了充分的exploration后才会转向纯粹的exploitation。

2. 仿真

import numpy as np
import matplotlib.pyplot as plt
import utilities as util

%matplotlib inline

         针对k_armed_bandit_one_run()一点修改,将Q值初始化设定修改为通过Qinit参数传入。

def k_armed_bandit_one_run(qstar,epsilon,nStep,Qinit,QUpdtAlgo='sample_average',alpha=0, stationary=True):
    """
    One run of K-armed bandit simulation.
    Add Qinit to the interface.
    Input:
        qstar:     Mean reward for each candition actions
        epsilon:   Epsilon value for epsilon-greedy algorithm
        nStep:     The number of steps for simulation
        Qinit:     Initial setting for action-value estimate
        QUpdtAlgo: The algorithm for updating Q value--'sample_average','exp_decaying'
        alpha:     step-size in case of 'exp_decaying'
    Output:
        a[t]: action series for each step in one run
        r[t]: reward series for each step in one run
        Q[k]: reward sample average up to t-1 for action[k]
        aNum[k]: The number of being selected for action[k]
        optRatio[t]: Ration of optimal action being selected over tim
    """
    
    K     = len(qstar)
    #Q     = np.zeros(K)
    Q     = Qinit
    a     = np.zeros(nStep+1,dtype='int') # Item#0 for initialization
    aNum  = np.zeros(K,dtype='int')       # Record the number of action#k being selected
    
    r     = np.zeros(nStep+1)             # Item#0 for initialization

    if stationary == False:
        qstar = np.ones(K)/K                 # qstart initialized to 1/K for all K actions    
    
    optCnt   = 0
    optRatio = np.zeros(nStep+1,dtype='float') # Item#0 for initialization

    for t in range(1,nStep+1):

        #0. For non-stationary environment, optAct also changes over time.Hence, move to inside the loop.
        optAct   = np.argmax(qstar)
        #1. action selection
        tmp = np.random.uniform(0,1)
        #print(tmp)
        if tmp < epsilon: # random selection
            a[t] = np.random.choice(np.arange(K))
            #print('random selection: a[{0}] = {1}'.format(t,a[t]))
        else:             # greedy selection
            #选择Q值最大的那个,当多个Q值并列第一时,从中任选一个--但是如何判断有多个并列第一的呢?
            #对Q进行random permutation处理后再找最大值可以等价地解决这个问题
            p = np.random.permutation(K)
            a[t] = p[np.argmax(Q[p])]
            #print('greedy selection: a[{0}] = {1}'.format(t,a[t]))

        aNum[a[t]] = aNum[a[t]] + 1

        #2. reward: draw from the pre-defined probability distribution    
        r[t] = np.random.randn() + qstar[a[t]]        

        #3.Update Q of the selected action - #2.4 Incremental Implementation
        # Q[a[t]] = (Q[a[t]]*(aNum[a[t]]-1) + r[t])/aNum[a[t]]    
        if QUpdtAlgo == 'sample_average':
            Q[a[t]] = Q[a[t]] + (r[t]-Q[a[t]])/aNum[a[t]]    
        elif QUpdtAlgo == 'exp_decaying':
            Q[a[t]] = Q[a[t]] + (r[t]-Q[a[t]])*alpha
        
        #4. Optimal Action Ratio tracking
        #print(a[t], optAct)
        if a[t] == optAct:
            optCnt = optCnt + 1
        optRatio[t] = optCnt/t

        #5. Random walk of qstar simulating non-stationary environment
        # Take independent random walks (say by adding a normally distributed increment with mean 0
        # and standard deviation 0.01 to all the q⇤(a) on each step).   
        if stationary == False:        
            qstar = qstar + np.random.randn(K)*0.01 # Standard Deviation = 0.01
            #print('t={0}, qstar={1}, sum={2}'.format(t,qstar,np.sum(qstar)))
        
    return a,aNum,r,Q,optRatio

        以下我们分别针对'sample-average-method'和'contant step-size(exponential recency-decaying weighted average)'两种平均方法(或者说步长机制),通过仿真对比{epsilon=0, Q=5}和{epsilon=0.1, Q=0}的差异。

2.1 sample-average method

nStep = 1000
nRun  = 2000
K     = 10

r_0p0_Q5   = np.zeros((nRun,nStep+1))
r_0p1_Q0   = np.zeros((nRun,nStep+1))
optRatio_0p0_Q5 = np.zeros((nRun,nStep+1))
optRatio_0p1_Q0 = np.zeros((nRun,nStep+1))

for run in range(nRun):
    print('.',end='')
    if run%100==99:        
        print('run = ',run+1)
    
    qstar   = np.random.randn(10)     
    a,aNum,r_0p0_Q5[run,:],Q,optRatio_0p0_Q5[run,:] = k_armed_bandit_one_run(qstar,epsilon=0,nStep=nStep, Qinit=np.ones(K)*5)
    a,aNum,r_0p1_Q0[run,:],Q,optRatio_0p1_Q0[run,:] = k_armed_bandit_one_run(qstar,epsilon=0.1,nStep=nStep, Qinit=np.zeros(K))


# Plotting simulation results
rEnsembleMean_0p0_Q5 = np.mean(r_0p0_Q5,axis=0)
rEnsembleMean_0p1_Q0 = np.mean(r_0p1_Q0,axis=0)

optRatioEnsembleMean_0p0_Q5 = np.mean(optRatio_0p0_Q5,axis=0)
optRatioEnsembleMean_0p1_Q0 = np.mean(optRatio_0p1_Q0,axis=0)


fig,ax = plt.subplots(1,2,figsize=(15,4))

ax[0].plot(rEnsembleMean_0p0_Q5)  # Without time-domain smooth filtering
ax[0].plot(rEnsembleMean_0p1_Q0)
ax[0].legend(['epsilon = 0, Qinit = 5','epsilon = 0.1, Qinit = 0'])
ax[0].set_title('ensemble average reward')

ax[1].plot(optRatioEnsembleMean_0p0_Q5)
ax[1].plot(optRatioEnsembleMean_0p1_Q0)
ax[1].legend(['epsilon = 0, Qinit = 5','epsilon = 0.1, Qinit = 0'])
ax[1].set_title('Optional action selection ratio')

        运行结果:


 

2.2 Constant Step-size alpha=0.1

nStep = 1000
nRun  = 2000
K     = 10

r_0p0_Q5   = np.zeros((nRun,nStep+1))
r_0p1_Q0   = np.zeros((nRun,nStep+1))
optRatio_0p0_Q5 = np.zeros((nRun,nStep+1))
optRatio_0p1_Q0 = np.zeros((nRun,nStep+1))

for run in range(nRun):
    print('.',end='')
    if run%100==99:        
        print('run = ',run+1)
    
    qstar   = np.random.randn(10)     
    a,aNum,r_0p0_Q5[run,:],Q,optRatio_0p0_Q5[run,:] = k_armed_bandit_one_run(qstar,epsilon=0,nStep=nStep,QUpdtAlgo='exp_decaying',alpha=0.1, Qinit=np.ones(K)*5)
    a,aNum,r_0p1_Q0[run,:],Q,optRatio_0p1_Q0[run,:] = k_armed_bandit_one_run(qstar,epsilon=0.1,nStep=nStep,QUpdtAlgo='exp_decaying',alpha=0.1, Qinit=np.zeros(K))
rEnsembleMean_0p0_Q5 = np.mean(r_0p0_Q5,axis=0)
rEnsembleMean_0p1_Q0 = np.mean(r_0p1_Q0,axis=0)

optRatioEnsembleMean_0p0_Q5 = np.mean(optRatio_0p0_Q5,axis=0)
optRatioEnsembleMean_0p1_Q0 = np.mean(optRatio_0p1_Q0,axis=0)


fig,ax = plt.subplots(1,2,figsize=(15,4))

ax[0].plot(rEnsembleMean_0p0_Q5)  # Without time-domain smooth filtering
ax[0].plot(rEnsembleMean_0p1_Q0)
ax[0].legend(['epsilon = 0, Qinit = 5','epsilon = 0.1, Qinit = 0'])
ax[0].set_title('ensemble average reward')

ax[1].plot(optRatioEnsembleMean_0p0_Q5)
ax[1].plot(optRatioEnsembleMean_0p1_Q0)
ax[1].legend(['epsilon = 0, Qinit = 5','epsilon = 0.1, Qinit = 0'])
ax[1].set_title('Optional action selection ratio')

         运行结果:

  

3. 仿真结果分析和讨论

        以上2.2节的仿真结果再现了原书种的仿真结果(参见Sutton-RLBook2020-Figure2.3).

        在开始阶段,”Optimal”方法的效果更差,因为它更多地采取了exploring策略。但是经过一段时间后,它就反超了。这个“小伎俩”在平稳环境下很有效,但是这并不是一种通用的鼓励探索(exploring)的好方法。比如说,它在非平稳环境下的表型就不怎么的。因为它对探索的鼓励只是临时性的,仅限于一开始的一段时间。对于非平稳环境,开始一段时间的表现对于总体结果没有什么影响。毕竟,游戏开始期间只发生一次,当任务发生变化(如前所述,非平稳环境下任务在持续发生变化,体现在qstar在持续发生变化)初始阶段对于exploring的鼓励不再起作用了。

事实上,任何依赖于初始条件的策略都不太能在非平稳环境下有什么帮助。同样的批评对于sample-average method也同样有效,它也同样将游戏开始阶段当作特殊的事件来处理。但是这些方法由于其非常简单,所以它们(以及它们的组合)在实践中往往有不错的效果。

4. Exercises

        没想明白。。。^-^容我继续慢慢想

Solution:

       由以上题设条件可知:

 

 由于 ,所以:

        由此可知,当某个行动第一次被选择时,它就把初始值Q1“忘记”了,因而回避了bias问题。

        其次,由于当n趋向无穷大时\beta_n趋向于\alpha,因此它渐进等价于前面讨论过的exponential recency-weighted average方法。

        本强化学习笔记系列总目录参见:

        强化学习笔记总目录icon-default.png?t=LA92https://blog.csdn.net/chenxy_bwave/article/details/121715424

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

笨牛慢耕

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值