【问题标题】:Second derivative in Tensorflow 2.0Tensorflow 2.0 中的二阶导数
【发布时间】:2021-04-17 06:41:30
【问题描述】:

我正在尝试使用带有 tf.GradientTape 的 TF 2.3 计算标量变量 f(x) = (x,x^2,x^3) 的简单向量函数的二阶导数。

def f_ab(x):
    return x, x** 2, x** 3

import tensorflow as tf
in1 = tf.cast(tf.convert_to_tensor(tf.Variable([-1,3,0,6]))[:,None],tf.float64)
with tf.GradientTape(persistent=True) as tape2:
    tape2.watch(in1)
    with tf.GradientTape(persistent=True) as tape:
        tape.watch(in1)
        f1,f2,f3 = f_ab(in1)
    df1 = tape.gradient(f1, in1)
    df2 = tape.gradient(f2, in1)
    df3 = tape.gradient(f3, in1)

d2f1_dx2 = tape2.gradient(df1, in1)
d2f2_dx2 = tape2.gradient(df2, in1)
d2f3_dx2 = tape2.gradient(df3, in1)

由于某种原因,只有最后两个导数是正确的,而第一个导数 d2f1_dx2 原来是 None

当我将f_ab 更改为

def f_ab(x):
    return x** 1, x** 2, x**3   

我收到了d2f1_dx2 = <tf.Tensor: shape=(1, 4), dtype=float64, numpy=array([[-0., 0., nan, 0.]])> 这“几乎”是正确的结果。

仅当我将f_ab 更改为

def f_ab(inputs_train):
    return tf.math.log(tf.math.exp(x) ), x** 2, x**3

我得到了正确的结果:d2f1_dx2 = <tf.Tensor: shape=(1, 4), dtype=float64, numpy=array([[0., 0., 0., 0.]])>

以前有人遇到过这个问题吗?为什么直接给出None

【问题讨论】:

  • 这对我来说确实是一种奇怪的行为。考虑填写issue on github

标签: tensorflow machine-learning deep-learning tensorflow2.0 derivative


【解决方案1】:

我认为这是因为x 的一阶导数是一个常数。因此,当您计算二阶导数时,Yf1 彼此无关,因为 f1 是一个常数。

在 TensorFlow 中,.gradient() 方法默认为 None,如果图中两个变量之间没有可定义的路径。

gradient(
    target, sources, output_gradients=None,
    unconnected_gradients=tf.UnconnectedGradients.NONE
)

see Tensorflow doc

您可以通过0 而不是None 更改此参数,并且您应该得到constant 的导数的预期结果。

【讨论】:

  • 不,常数的导数应该为零
  • @BennyK,我知道,不知道你指的是什么。
  • @BennyK,我的解释仍然有效,我不明白这如何使我的答案无效。
  • 常数向量的导数应该是零向量,而不是None。我没有使用渐变,而是使用渐变胶带
  • @BennyK,你正在做df1 = tape.gradient(f1, in1),所以你正在使用渐变方法。现在,如果您要区分的两个变量之间没有链接,那么渐变方法默认为None。我同意它应该是0,但他们默认放入TF的是None。不,您可以更改此行为,正如我在回答中解释的那样。
猜你喜欢
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多