class ValueIteration:
""" 价值迭代算法 """
def __init__(self,env,theta,gamma):
self.env=env
self.theta=theta#策略评估收敛阈值
self.gamma=gamma#折扣因子
self.v=[0]*(self.env.ncol*self.env.nrow)#初始化价值为0
self.pi=[None for i in range(self.env.ncol*self.env.nrow)]
def value_iteration(self):
count=0
while 1:
max_diff=0
new_v=[0]*self.env.ncol*self.env.nrow
for s in range(self.env.ncol*self.env.nrow):
Qsa_list=[]#开始计算状态s下面的所有Q(s,a)价值
for a in range(4):
Qsa=0
for res in self.env.P[s][a]:
p,next_state,reward,done=res
Qsa+=p*(reward+self.gamma*self.v[next_state]*(1-done))
Qsa_list.append(Qsa)
new_v[s]=max(Qsa_list)
max_diff=max(max_diff,abs(new_v[s]-self.v[s]))
self.v=new_v
if max_diff<self.theta:break
count+=1
print("价值迭代进行%d轮后完成"%count)
self.getpolicy()
def getpolicy(self):#价值迭代完成后,根据价值函数导出一个贪婪策略
for s in range(self.env.ncol*self.env.nrow):
Qsa_list=[]
for a in range(4):
Qsa=0
for res in self.env.P[s][a]:
p,next_state,reward,done=res
Qsa+=p*(reward+self.gamma*self.v[next_state]*(1-done))
Qsa_list.append(Qsa)
max_Qsa=max(Qsa_list)
count_max_Qsa=Qsa_list.count(max_Qsa)
self.pi[s]=[1/count_max_Qsa if p==max_Qsa else 0 for p in Qsa_list]
def print_agent(agent,action_meaning,disater=[],end=[]):
print("状态价值:")
for i in range(agent.env.nrow):
for j in range(agent.env.ncol):
print('%6.6s' % ('%.3f' % agent.v[i*agent.env.ncol+j]),end=' ')
print()
print("策略:")
for i in range(agent.env.nrow):
for j in range(agent.env.ncol):
#一些特殊的状态,例如悬崖漫步中的悬崖
if (i*agent.env.ncol+j) in disater:
print('****',end=' ')
elif (i*agent.env.ncol+j) in end:#目标状态
print('EEEE',end=' ')
else:
a=agent.pi[i*agent.env.ncol+j]
pi_str=''
for k in range(len(action_meaning)):
pi_str+=action_meaning[k] if a[k]>0 else 'o'
print(pi_str,end=' ')
print()#换行
import gym
import cv2
env=gym.make("FrozenLake-v1",map_name="4x4",render_mode='human')#创建环境 render_mode='human'/'rgb_array'/'ansi'
env.reset()
env=env.unwrapped#解封装才能访问状态转移矩阵P
action_meaning=['↑','↓','←','→']
theta=1e-5
gamma=0.9
agent=PolicyIteration(env,theta,gamma)
agent.policy_iteration()
print_agent(agent,action_meaning,[5,7,11,12],[15])
强化学习之价值迭代动态规划算法求解冰湖环境最优策略及最优状态价值
最新推荐文章于 2024-09-03 17:37:40 发布