Q-learning算法是比较经典的强化学习入门算法,本文以FrozenLake-V0为例,介绍Q-learning的相关实现。
首先定义一个Agent类,sample函数就是使用epsilon-greedy的采样方法,predict则是根据当前的观察值来预测输出的动作,learn就是通过输入当前的观察值obs,当前的动作action,奖励reward以及下一个时刻的观察值next_obs来更新Q值表。
代码:
class QLearningAgent(object):
def __init__(self, obs_n, act_n, learning_rate=0.01, gamma=0.9, e_greed=0.1):
self.act_n = act_n # 动作维度,有几个动作可选
self.lr = learning_rate # 学习率
self.gamma = gamma # reward的衰减率
self.epsilon = e_greed # 按一定概率随机选动作
self.Q = np.zeros((obs_n, act_n))
# 根据输入观察值,采样输出的动作值,带探索
def sample(self, obs):
rd_p = np.random.uniform(0, 1)
if rd_p <= self.epsilon:
action = np.random.choice(self.act_n)
else:
action = self.predict(obs)
return action
# 根据输入观察值,预测输出的动作值
def predict(self, obs):