引用来自ShangtongZhang的代码chapter06/random_walk.py
通过一个例子比较了TD(0)和constant-α MC方法的训练性能
问题描述
通过一个MRP来比较constant-α MC Method和TD(0)方法之间的训练性能。
MRP的状态转移示意图:
其中state C 是起始状态,向右达到终点return=1,向左return=0,其余每一步reward=0
所以每个state的true value就是该state到达最右端端点的概率。A-E:1/6,2/6,..5/6
计算也很容易,通过迭代计算列出5个式子,P(s)代表从改点到达右端点的概率:
P(E)=1/2 + 1/2 * P(D)
P(D)=1/2 P(C) + 1/2 P(E)
P(C)=1/2 P(B) + 1/2 P(D)
P(B)=1/2 P(A) + 1/2 P(C)
P(A)=1/2 * P(B)
计算即可得到上面提到的答案。当然这个方法就是我们在Chapter03讲到的Bellman equation:
引入模块并定义常量
1 | # 6.2 Advantages of TD Prediction Methods |
使用TD(0)方法update state-value
1 | # @values: current states value, will be updated if @batch is False |
使用Monte Carlo方法update state-value
1 | # @values: current states value, will be updated if @batch is False |
通过使用TD(0)方法建立state-value,并绘制收敛图像
1 | # Example 6.2 left |
计算并比较TD(0)和constant α-MC method的rms(均方差误差)
1 | # Example 6.2 right |
使用一般的方法进行state-value收敛并绘制图像
1 | def example_6_2(): |
100%|██████████| 101/101 [00:00<00:00, 7677.14it/s]
100%|██████████| 100/100 [00:00<00:00, 173.89it/s]
100%|██████████| 100/100 [00:00<00:00, 179.95it/s]
100%|██████████| 100/100 [00:00<00:00, 169.18it/s]
100%|██████████| 100/100 [00:00<00:00, 247.49it/s]
100%|██████████| 100/100 [00:00<00:00, 239.68it/s]
100%|██████████| 100/100 [00:00<00:00, 236.73it/s]
100%|██████████| 100/100 [00:00<00:00, 229.08it/s]
使用batch-update方法优化state-value的收敛过程并绘制图像
1 | # Figure 6.2(Example 6.3) |
100%|██████████| 100/100 [00:45<00:00, 2.29it/s]
100%|██████████| 100/100 [00:37<00:00, 2.49it/s]