首页 > 解决方案 > 了解强化学习中的 Keras 损失函数输入

问题描述

根据本教程,我正在实施一种策略网络 RL 方法来解决乒乓球游戏。但是,我无法理解该custom_loss()功能。

custom_loss()函数有两个输入,y_true 和 y_pred。但是,在 RL 设置中,没有 y_true(即标签),因为您只是在环境中行动并获得奖励。

那么在这个例子中,损失函数是如何计算的呢?我唯一的假设是 y_true 是从分布中采取的行动:

( action = np.random.choice(range(num_actions),p=predict)),

y_pred 是概率分布(即策略网络的输出):

predict = model_predict.predict([state])[0]

如果是这种情况,则网络输出的概率分布不会在训练调用中传递loss = model_train.train_on_batch([states, discounted_rewards], actions_train),只有选定的 one-hot 编码动作会传递。

以下是相关代码的片段,但是按照上面的链接可能更容易。

...

def custom_loss(y_true, y_pred):
    # actual: 0 predict: 0 -> log(0 * (0 - 0) + (1 - 0) * (0 + 0)) = -inf
    # actual: 1 predict: 1 -> log(1 * (1 - 1) + (1 - 1) * (1 + 1)) = -inf
    # actual: 1 predict: 0 -> log(1 * (1 - 0) + (1 - 1) * (1 + 0)) = 0
    # actual: 0 predict: 1 -> log(0 * (0 - 1) + (1 - 0) * (0 + 1)) = 0
    log_lik = K.log(y_true * (y_true - y_pred) + (1 - y_true) * (y_true + y_pred))
    return K.mean(log_lik * adv, keepdims=True)

model_train = Model(inputs=[inp, adv], outputs=out)
model_train.compile(loss=custom_loss, optimizer=Adam(lr))
model_predict = Model(inputs=[inp], outputs=out)  

...

loss = model_train.train_on_batch([states, discounted_rewards], actions_train)

我希望损失函数考虑到网络输出的概率分布、选择的动作和优势(折扣奖励),但对实现的自定义损失函数感到困惑。

标签: pythontensorflowkeras

解决方案


推荐阅读