计算高阶变量的Hessian矩阵既不能用tf.hessians()也不能用tf.gradients()

当我们需要计算二阶梯度或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中已知的限制,目前没有更简单的方法可用。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注