深度强化学习(深度Q学习

2013年,在DeepMind 发表的著名论文Playing Atari with Deep Reinforcement Learning中,他们介绍了一种新算法,深度Q网络(DQN)。文章展示了AI agent如何在没有任何先验信息的情况下通过观察屏幕学习玩游戏。结果令人印象深刻。这篇文章开启了被我们成为“深度强化学习”的新时代。这种学习算法是混合了深度学习与强化学习的新算法。

每进行一个动作,agent 都会收到一个反馈。该反馈包含两部分的内容:一个是“奖励”(reward),另一个是则为“环境的下一状态”。

在Q学习算法中,有一种函数被称为Q函数,它用来估计基于一个状态的回报。

keras库使基础神经网络的使用变得非常简单。下面的代码会生成一个空的神经网络模型。“activation”,“loss”与“optimizer”是定义神经网络特征的参数但我们不打算在这里讨论它们。对于Sequential model的第一层必须包含input_shape,因为必须通过这个来告诉模型你输入的是什么类型的数据,而后续的中间层就不需要这个了,因为会默认使用第一层的shape类型。

# Neural Net for Deep Q Learning
 
# Sequential() creates the foundation of the layers.
model = Sequential()
 
# Dense is the basic form of a neural network layer
# Input Layer 4 and Hidden Layer with 128 nodes
model.add(Dense(64, input_dim=4, activation='tanh')) 
# Hidden layer with 128 nodes
model.add(Dense(128, activation='tanh'))
# Hidden layer with 128 nodes
model.add(Dense(128, activation='tanh'))
# Output Layer with 2 nodes
model.add(Dense(2, activation='linear'))
 
# Create the model based on the information above
model.compile(loss='mse',
              optimizer=RMSprop(lr=self.learning_rate))

为了让模型可以基于环境数据理解与预测,我们不得不给它提供数据。下列代码所示,“fit()”方法为模型提供“states”和“target_f”信息。你可以忽视其余参数。

这个训练过程使模型从某个状态“state”预测回报函数值“target_f”。

model.fit(state, target_f, nb_epoch=1, verbose=0)
当你在模型调用"predict()"函数时,模型根据之前训练过的数据将预测现在状态的回报函数
prediction = model.predict(state)

实现深度Q算法(DQN)

 DQN算法最重要的特征是记忆(remember)与回顾(replay)方法。它们都有很简明的概念。

记忆(remember)

对于DQN来说一个挑战就是运用在算法中的神经网络区域通过覆盖掉先前学习的经验来遗忘它们。所以我们需要记录下先前的经验与观察值以便再用这些先前数据训练模型。我们将调用代表经验的数组数据“memory”和“remember()”函数来添加状态,回报,和下次状态到“memory”中。

在本例中,“memory”列表中有以下形式的数据:

memory = [(state, action, reward, next_State)...]
“remember()”只是简单的存储上述这些数据:
 
 
def remember(self, state, action, reward, next_state, done):
    self.memory.append((state, action, reward, next_state, done))

“done”只是一个标记是否为最后一个状态的布尔量。

"replay()"从存储在“memory”中的数据(经验)中训练神经网络。首先,我们从“memory”中抽出部分数据并叫他们“bathces”

batches = min(batch_size, len(self.memory))
batches = np.random.choice(len(self.memory), batches)

为了使agent在长期运行中表现的更好,我们不仅仅需要考虑即时回报(immediate rewards),还要考虑未来回报(future rewards)。为了实现这一目标,我们定义“discount rate”(折扣因子) 即“gamma”。这样,agent将学习已有的状态然后想方设法最大化未来回报。

代码可见https://github.com/keon/deep-q-learning


猜你喜欢

转载自blog.csdn.net/weixin_38145317/article/details/79454079