当我们需要计算二阶梯度或Hessian矩阵时,在TensorFlow中,我们可能会使用tf.hessians(F(x),x)
,或者使用tf.gradient(tf.gradients(F(x),x)[0], x)[0]
。然而,当x
不是一阶时,使用tf.hessians()
时,我遇到了以下错误。
ValueError: 无法计算Hessian,因为xs的第0个元素不是一阶的。张量model_inputs/action:0必须是一阶的。接收到的阶数为2,形状为(?, 1)
在以下代码中:
with tf.name_scope("1st scope"): self.states = tf.placeholder(tf.float32, (None, self.state_dim), name="states") self.action = tf.placeholder(tf.float32, (None, self.action_dim), name="action")with tf.name_scope("2nd scope"): with tf.variable_scope("3rd scope"): self.policy_outputs = self.policy_network(self.states) # 使用两次tf.gradients self.actor_action_gradients = tf.gradients(self.policy_outputs, self.action)[0] self.actor_action_hessian = tf.gradients(self.actor_action_gradients, self.action)[0] # 或者使用tf.hessians self.actor_action_hessian = tf.hessian(self.policy_outputs, self.action)
使用tf.gradients()
时,也会导致错误:
在create_variables中 self.actor_action_hessian = tf.gradients(self.actor_action_gradients, self.action)[0]
AttributeError: ‘NoneType’对象没有属性’dtype’
我该如何解决这个问题?在这种情况下既不能使用tf.gradients()
也不能使用tf.hessians()
吗?
回答:
第二种方法是可行的,错误出在其他地方,即你的图未连接。
self.actor_action_gradients = tf.gradients(self.policy_outputs, self.action)[0]self.actor_action_hessian = tf.gradients(self.actor_action_gradients, self.action)[0]
第二行抛出错误是因为self.actor_action_gradients为None,因此无法计算其梯度。你的代码中没有任何地方表明self.policy_outputs依赖于self.action(而且不应该,因为是动作依赖于策略,而不是策略依赖于动作)。
一旦你解决了这个问题,你会发现,“hessian”实际上不是一个真正的hessian,而是一个向量。要形成一个正确的关于x的f的hessian,你必须遍历tf.gradients返回的所有值,并独立计算每个值的tf.gradients。这是在TF中已知的限制,目前没有更简单的方法可用。