在 Tensorflow 中计算动作和奖励的损失

Calculating loss from action and reward in Tensorflow

我正在尝试计算具有 3 个离散操作的 RL 项目中的损失。我有我的模型的输出预测(来自 tf.layers.dense())(例如 3 种可能的操作,批量大小 2):

[[10, 20.2, 4.3],
 [5, 3, 8.9]]

我有代理人采取的行动(例如):

[[1],
 [2]]

并且我从环境中采取该行动得到奖励(例如):

[[30.0],
 [15.0]]

我想计算所采取行动的损失,将行动作为指标和奖励。我没有关于未采取的行动的任何信息。如果它只是计算差异,我预计损失(从前面的例子)是:

[[0, 9.8, 0],
 [0, 0, 6.1]]

我试过:

updated = tf.scatter_update(logits, action, reward)
loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=updated, logits=logits)

但这给出了 AttributeError: 'Tensor' object has no attribute '_lazy_read'。我相信这是因为输入是张量而不是 scatter_update() 需要的变量。

如何计算损失?

您不能使用 scatter_update,因为那是针对一维数据的。您可能需要看一下 gather_nd and scatter_nd 是如何工作的。但是以下代码可以解决您的问题。

import tensorflow as tf

num_actions = 3
batch_size = 2
tf.reset_default_graph()

output = tf.convert_to_tensor([[10, 20.2, 4.3],[5, 3, 8.9]])

# There's a bit of dark magic looking reshaping going here
# Essentially to get tensor a in the correct shape of indices
# gather_nd requires
a_idx = tf.reshape(tf.range(batch_size),[-1,1])

a = tf.convert_to_tensor([[1],[2]])

a_reshaped = tf.reshape(tf.concat([a_idx,a],axis=1),[-1,1,2])

r = tf.convert_to_tensor([[30.0],[15.0]])

diff = tf.gather_nd(output, a_reshaped)
loss = tf.scatter_nd(a_reshaped, r-diff, (batch_size, num_actions))