使用 tf.custom_gradient 计算泰勒级数近似值

时间:2021-03-14 14:59:52

标签: python tensorflow

我应该使用 TensorFlow 自定义梯度计算函数 cos(x) + 1 的泰勒级数近似值。

我写了以下代码:

def approx_cos_p1(x, n=7, dtype=tf.float32):
    """Return the approximation of cos(x) + 1 using a taylor/series expansion up to order 7"""

    result = tf.constant(2, dtype)

    for i in range(1, n//2+1):
        if i % 2 == 1:
            num=tf.math.pow(x, i*2)

            den=math.factorial(i*2)

            result=tf.math.subtract(result,tf.math.divide(num,den))

        else:
            num=tf.math.pow(x, i*2)
            

            den=math.factorial(i*2)

            result=tf.math.add(result,tf.math.divide(num,den))

    return result

@tf.custom_gradient
def approx_cos_p1_custom_grad(x):
  def backward(dy):
    return approx_cos_p1(x)
  return x, backward

x=tf.Variable(3.0,dtype=tf.float32)

with tf.GradientTape(persistent=True) as t:
  output=approx_cos_p1_custom_grad(x)

print(t.gradient(output,x))

但根据 Tensorflow 文档,tf.custom_gradients 应该如下使用:

#Establish an identity operation, but clip during the gradient pass
@tf.custom_gradient
def clip_gradients(y):
  def backward(dy):
    return tf.clip_by_norm(dy, 0.5)
  return y, backward

v = tf.Variable(2.0)
with tf.GradientTape() as t:
  output = clip_gradients(v * v)
print(t.gradient(output, v))  # calls "backward", which clips 4 to 2

approx_cos_p1() 函数完美运行。

这里的问题是函数 dy 中的 backward() 参数没有在 approx_cos_p1() 中传递,这与 Tensorflow 文档不符。但我得到了所需的输出 -3.15

当我在 dy 中传递 approx_cos_p1() 时,我得到一个不需要的输出 1.14

我对函数的实现是否正确?

0 个答案:

没有答案