TensorFlow2 study notes[2]
文章目录
- tf.autodiff.ForwardAccumulator
- references
tf.autodiff.ForwardAccumulator
- the function can be used to achieve the Computation of Jacobian-vector products with forward-mode autodiff.
- primals is variables need to watch.tangents is direction vector.
tf.autodiff.ForwardAccumulator(primals, tangents
)
import tensorflow as tf# 定义函数
def f(x, y):return x ** 2 + y**5 + tf.sin(y)*tf.cos(x)# 输入变量和方向向量
x = tf.constant(2.0)
y = tf.constant(3.0)
v_x = tf.constant(1.5) # x 方向的分量
v_y = tf.constant(0.2) # y 方向的分量# 初始化 ForwardAccumulator
with tf.autodiff.ForwardAccumulator(primals=[x, y], # 要跟踪的变量tangents=[v_x, v_y] # 方向向量 v
) as acc:# 计算函数值z = f(x, y)# 提取方向导数 (JVP)
jvp = acc.jvp(z)
print("函数值:", z.numpy()) # 输出: 4.0 + sin(3) ≈ 4.14112
print("方向导数 (JVP):", jvp.numpy()) # 输出: 2*2*1 + cos(3)*0 ≈ 4.0
references
- https://tensorflow.google.cn/api_docs
- deepseek