根据已有数据结构填写马尔科夫决策过程值迭代以及策略迭代的代码片段。
相关知识
为了完成本关任务,你需要掌握:
掌握马尔科夫决策过程的基本模型,能够建立并理解相关数据结构。
能够根据值迭代算法伪代码完成代码片段填写。
能够根据策略迭代算法伪代码完成代码片段填写。
理解两种方法的不同。
马尔科夫决策过程基本概念
马尔可夫决策过程(Markov Decision Process, MDP)是序贯决策(sequential decision)的数学模型,用于在系统状态具有马尔可夫性质的环境中模拟智能体可实现的随机性策略与回报。
按定义,MDP包含5个模型要素,状态(state)、动作(action)、策略(policy)、奖励(reward)和回报(return)
import numpy as np
class MDP(object):
def init(self, P, nS, nA, desc=None):
“”"
mdp.P is a two-level dict where the first key is the state and the
second key is the action.
The 2D grid cells are associated with indices [0, 1, 2, ..., 15] from
left to right and top to down, as in
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
mdp.P[state][action] is a list of tuples (probability, nextstate, reward).
P[5][0] = [(1.0, 5, 0)]
"""
self.P = P # state transition and reward probabilities, explained above
self.nS = nS # number of states
self.nA = nA # number of actions
#------------------value iteration------------------------#
def value_iteration(mdp, gamma, nIt):
“”"
Inputs:
mdp: MDP
gamma: discount factor
nIt: number of iterations, corresponding to n above
Outputs:
(value_functions, policies)
len(value_functions) == nIt+1 and len(policies) == n
“”"
Vs = [np.zeros(mdp.nS)] # list of value functions contains the initial value function V^{(0)},
# which is zero
pis = []
for it in range(nIt):
oldpi = pis[-1] if len(pis) > 0 else None # \pi^{(it)} = Greedy[V^{(it-1)}]. Just used for printout
Vprev = Vs[-1] # V^{(it)}
测试数据是一个游戏,如下4x4的矩阵代表一块冰湖,其中S、G分别代表起点和终点,F是冻住的冰面,H是未冻住的地方也就是一个冰洞。
机器人可以从所在位置向向相邻的上下左右方格移动,由于冰面光滑,机器人在移动过程中可能以一定概率分布滑到目的方格临近的方格(但是不会滑出边界)。
请根据给定的概率分布、衰减参数、迭代次数等参数,计算测试数据对应的最优策略。测试点1、2分别针对上图样例计算值迭代与策略迭代。测试点3、4计算另一个8x8的样例。测试点5对比两种迭代方法的收敛速度。