autograd.py 330 B

1234567891011121314151617
  1. import tensorflow as tf
  2. # 创建4个张量
  3. a = tf.constant(1.)
  4. b = tf.constant(2.)
  5. c = tf.constant(3.)
  6. w = tf.constant(4.)
  7. with tf.GradientTape() as tape:# 构建梯度环境
  8. tape.watch([w]) # 将w加入梯度跟踪列表
  9. # 构建计算过程
  10. y = a * w**2 + b * w + c
  11. # 求导
  12. [dy_dw] = tape.gradient(y, [w])
  13. print(dy_dw)