Q learning (Tabular)
Value-based Sequential Decision
Principle
根据 表对下一时刻的动作进行选择,下图是 表的更新方式
此时, 并未进行下一次的动作,而是预估了一下后果,由此来更新 的 表。
其中, 是学习速率, 是选择 表最大值的概率。若 ,则 概率选择 表最大值即最优动作, 的概率随机动作。
由于 是下一次的动作,会通过乘以奖励衰减值 的方式影响前一次的 表取值,因此很容易想到只要 ,以后的每次动作得到的奖励值都会影响之前动作的 表取值。
- Q估计: 状态最优动作 的Q值
- Q现实:在选择了动作 后,进入 状态。Q表中 状态对应的Q值的最大值加上执行动作 之后得到的奖励值 ,即为 现实。
Implement
class Skylark_Qlearning():
def __init__(self, env, alpha = 0.1, gamma = 0.6, epsilon=0.1):
self.q_table = np.zeros([env.observation_space.n, env.action_space.n])
self.env = env
self.alpha = alpha # learning rate
self.gamma = gamma # discount rate
self.epsilon = epsilon # epsilon-greedy
def train(self, num_epochs):
for i in range(1, num_episodes):
state = self.env.reset()
epochs, penalties, reward, = 0, 0, 0
done = False
while not done:
if np.random.uniform(0, 1) < self.epsilon:
action = self.env.action_space.sample() # Explore action space
else:
action = np.argmax(self.q_table[state]) # Exploit learned values
next_state, reward, done, info = self.env.step(action) # Interaction with Env
old_value = self.q_table[state, action]
next_max = np.max(self.q_table[next_state])
new_value = (1 - self.alpha) * old_value + self.alpha * (reward + self.gamma * next_max)
self.q_table[state, action] = new_value
if reward == -10:
penalties += 1
sum_rew += reward
state = next_state
epochs += 1
print('Episode: {} | Avg_reward: {} | Length: {}'.format(i, sum_rew/epochs, epochs))
print("Training finished.")
评论(0)
您还未登录,请登录后发表或查看评论