python - 了解强化学习中的 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)
我希望损失函数考虑到网络输出的概率分布、选择的动作和优势(折扣奖励),但对实现的自定义损失函数感到困惑。
解决方案
推荐阅读
- python - Python中的网页抓取:奇怪的顺序和抓取问题
- javascript - 如何在打字稿中使用 bigint 初始化程序创建一个类似枚举的对象?
- c++ - C++ 聚合初始化器在运行时或编译时有效吗?
- c# - 将 UTC 转换为不同的时区,无需夏令时
- c++ - 尝试初始化异构列表中的数组元素时出现分段错误
- php - firebird DB 列的结果是无名的,只是数字
- python - 如何使用 Colaboratory 上的 Selenium 从单击事件中下载文件?
- c# - Dbset 作为实体框架中的哈希集
- json - 转换 .txt 文件以加载到数据框中
- python - 在单元测试(Python)中模拟模块单例的依赖关系