TensorFlow 中 torch.autograd 的类似物

问题描述 投票:0回答:1

我想在训练后获得模型的梯度。例如,我有输入张量 X 和输出 y,即 y = model(x)。因此,使用 pytorch 我可以使用以下命令计算梯度:

y = model(x)
dydx = torch.autograd.grad(Y, X, torch.ones_like(Y), create_graph=True)[0][:, 0]

我想用TensorFlow框架训练模型后得到相同的值。

我尝试过:

y = model.predict_u(x)
dydx = tf.gradients(y, x)[0]

但我得到的 dydx 为 NoneType。我尝试将 dydx 包含在模型类中并通过 tf.Session 获取梯度,但我有:“ResourceExhaustedError:图形执行错误”。

我曾经使用过 Pytorch 框架,现在我决定尝试 TensorFlow,但我遇到了一些困难。

tensorflow pytorch neural-network automatic-differentiation
1个回答
0
投票

要在 TensorFlow 中计算梯度,类似于在 PyTorch 中的计算方式,您需要使用 TensorFlow 的自动微分功能。但是,需要记住一些关键差异:

  • TensorFlow 2.x 默认使用 eagerexecution,比较类似 PyTorch 的动态图方法。
  • 您需要使用 tf.GradientTape 来记录操作 自动微分。

以下是如何在 TensorFlow 2.x 中计算梯度,类似于 PyTorch 示例:

import tensorflow as tf

# Assuming x is your input tensor and model is your TensorFlow model
x = tf.Variable(x)  # Make sure x is a Variable or use tf.convert_to_tensor(x)

with tf.GradientTape() as tape:
    y = model(x)
    
dydx = tape.gradient(y, x)

有关该主题的更多信息: https://www.tensorflow.org/guide/autodiff https://www.tensorflow.org/api_docs/python/tf/GradientTape

© www.soinside.com 2019 - 2024. All rights reserved.