引用来自ShangtongZhang的代码chapter06/windy_grid_world.py、chapter06/cliff_walking.py
本篇包含了两份代码,第一个主要测试了on-policy Sarsa的性能,第二个对标题的三种算法性能进行了比较
一、问题描述
和普通的grid-world不同之处是,在格子的中间区域,存在上升的wind,所以在该处的action会附加一个up的action。
引入模块并定义常量
1 | #Sarsa |
使用on-policy策略的Sarsa来更新state-action-vlaue
1 | # 根据current-state和action对返回next state |
1 | def figure_6_3(): |
可以看到随着多个episode的迭代,使用的step数目逐渐收敛。
Optimal policy is:
['R', 'D', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'D']
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'L', 'R', 'D']
['R', 'R', 'R', 'R', 'R', 'U', 'R', 'R', 'R', 'D']
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'G', 'R', 'D']
['R', 'U', 'U', 'R', 'R', 'R', 'U', 'D', 'L', 'L']
['R', 'D', 'R', 'U', 'R', 'U', 'U', 'D', 'R', 'L']
['R', 'R', 'R', 'R', 'U', 'U', 'U', 'U', 'U', 'L']
Wind strength for each column:
['0', '0', '0', '1', '1', '1', '2', '2', '1', '0']
二、问题描述
这个问题在grid-world基础上做了一些改动,主要测试了3种算法的性能:Sarsa、Q-Learning、Expect Sarsa。
在一般区域(非阴影部分)action的reward=-1,如果action导致next state落到cliff区域,则reward=-100,而且agent会回到start state。到达goal state的return=0。
引入模块并定义常量
1 | import numpy as np |
function for taking action and choosing action
1 | # 根据所给state-action对给出next-state和对应的reward |
使用on-policy Sarsa方法训练
1 | # an episode with Sarsa |
使用off-policy Q-Learning方法训练
1 | # an episode with Q-Learning |
输出优化的action
1 | # print optimal policy |
比较Sarsa和Q-Learning的rewards并给出两者的优化action
1 | # Use multiple runs instead of a single run and a sliding window |
100%|██████████| 50/50 [00:56<00:00, 1.15s/it]
最终训练结果Sarsa收敛到较安全的位于上部区域的路径(问题描述图片中的 safe path),Q-Learning收敛到靠近cliff的路径(optimal path),但是因为epsilon-greedy的behavior policy,所以会导致Q-Learning偶尔会落入cliff,所以最终的总的reward低于Sarsa。
Sarsa Optimal Policy:
['R', 'R', 'R', 'R', 'D', 'R', 'R', 'R', 'R', 'R', 'R', 'D']
['R', 'U', 'U', 'U', 'R', 'R', 'U', 'U', 'U', 'U', 'R', 'D']
['U', 'R', 'R', 'L', 'U', 'U', 'U', 'L', 'U', 'U', 'R', 'D']
['U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'G']
Q-Learning Optimal Policy:
['U', 'U', 'U', 'R', 'R', 'U', 'D', 'R', 'R', 'D', 'D', 'D']
['R', 'R', 'R', 'R', 'R', 'R', 'D', 'R', 'R', 'R', 'R', 'D']
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'D']
['U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'G']
Interim and asymptotic performance of TD control methods as a function of α
1 | # Due to limited capacity of calculation of my machine, I can't complete this experiment |
100%|██████████| 10/10 [00:41<00:00, 4.57s/it]
100%|██████████| 10/10 [00:41<00:00, 4.53s/it]
100%|██████████| 10/10 [00:41<00:00, 4.55s/it]
100%|██████████| 10/10 [00:40<00:00, 4.35s/it]
100%|██████████| 10/10 [00:40<00:00, 4.36s/it]
100%|██████████| 10/10 [00:41<00:00, 4.40s/it]
100%|██████████| 10/10 [00:40<00:00, 4.33s/it]
100%|██████████| 10/10 [00:40<00:00, 4.27s/it]
100%|██████████| 10/10 [00:40<00:00, 4.37s/it]
100%|██████████| 10/10 [00:40<00:00, 4.28s/it]