我正在尝试为人工智能问题编写一个深度Q学习网络。我有一个函数predict()
,它生成一个形状为(None, 3)
的张量,输入的形状为(None, 5)
。在(None, 3)
中的3对应于每个状态下可以采取的每个动作的Q值。现在,在训练步骤中,我需要多次调用predict()
,并使用结果来计算成本和训练模型。为了做到这一点,我还有另一个可用的数据数组,称为current_actions
,它是一个列表,包含在之前迭代中针对特定状态采取的动作的索引。
需要发生的是current_states_outputs
应该是一个从predict()
的输出创建的张量,其中每一行只包含一个Q值(与predict()
的输出中的三个不同),并且应该根据current_actions
的相应索引来选择哪个Q值。
例如,如果current_states_output = [[1,2,3],[4,5,6],[7,8,9]]
和current_actions=[0,2,1]
,操作后的结果应该是[1,6,8]
(更新后的)。
我该怎么做呢?
我尝试了以下方法 –
current_states_outputs = self.sess.run(self.prediction, feed_dict={self.X:current_states}) current_states_outputs = np.array([current_states_outputs[a][current_actions[a]] for a in range(len(current_actions))])
我基本上是在predict()
上运行了会话,并使用普通的Python方法完成了所需的操作。但因为这切断了成本与图的前几层的连接,所以无法进行训练。因此,我需要在TensorFlow内部进行此操作,并保持所有内容为TensorFlow张量。我该如何管理这一点?
回答:
你可以尝试,
tf.squeeze(tf.gather_nd(a,tf.stack([tf.range(b.shape[0])[...,tf.newaxis], b[...,tf.newaxis]], axis=2)))
示例代码:
a = tf.Variable(current_states_outputs)b = tf.Variable(current_actions)out = tf.squeeze(tf.gather_nd(a,tf.stack([tf.range(b.shape[0])[...,tf.newaxis], b[...,tf.newaxis]], axis=2)))sess = tf.InteractiveSession()tf.global_variables_initializer().run()sess.run(out)#output[1, 6, 8]