使用 Keras 模型进行强化学习

Reinforcement Learning with Keras model

我试图在 Keras 中实现一个 q-learning 算法。根据文章,我找到了这些代码行。

for state, action, reward, next_state, done in sample_batch:
        target = reward
        if not done:
            #formula
          target = reward + self.gamma * np.amax(self.brain.predict(next_state)[0])
        target_f = self.brain.predict(state)
        #shape (1,2)
        target_f[0][action] = target
        print(target_f.shape)
        self.brain.fit(state, target_f, epochs=1, verbose=0)
    if self.exploration_rate > self.exploration_min:
        self.exploration_rate *= self.exploration_decay

变量 sample_batch 是包含收集数据样本 state, action, reward, next_state, done 的数组。 我还发现了以下 q-learning 公式

为什么方程(代码)中没有-符号?我发现 np.amax returns 数组的最大值或沿轴的最大值。当我调用 self.brain.predict(next_state) 时,我得到 [[-0.06427538 -0.34116858]]。那么它在这个方程中起到了预测的作用?随着我们前进,target_f 是当前状态的预测输出,然后我们还通过这一步将奖励附加到它。然后,我们在当前 state(X) 和 target_f(Y) 上训练模型。我有几个问题。 self.brain.predict(next_state)的作用是什么,为什么没有负号?为什么我们在一个模型上预测两次?例如 self.brain.predict(state) and self.brain.predict(next_state)[0]

Why is there no - sign in the equation(code)?

这是因为损失计算是在拟合函数内部完成的。

reward + self.gamma * np.amax(self.brain.predict(next_state)[0])

这与损失函数中的target分量相同。

keras loss中的fit方法内部计算如下。 对于单个训练数据点(神经网络的标准符号),

x = input state

y = predicted value

y_i = target value

loss(x) = y_i - y

在这一步 目标 - 预测 发生在内部。

Why do we predict twice on one model?

好问题!!!

 target = reward + self.gamma * np.amax(self.brain.predict(next_state)[0])

在这一步中,如果我们采取特定行动 a(表示为 Q(s,a ))

 target_f = self.brain.predict(state)

在这一步中,我们计算每个动作的所有 Q 值,我们可以在状态 s 中采取这些值。

target = 1.00    // target is a single value for action a
target_f = (0.25,0.25,0.25,0.25)   //target_f is a list of values for all actions

然后执行以下步骤。

target_f[0][action] = target

我们只更改所选操作的值。 (如果我们采取行动 3)

target_f = (0.25,0.25,1.00,0.25)  // only action 3 value will change

现在 target_f 将是 实际目标值 我们试图用正确的形状进行预测。