运行环境
Spyder4.0+Python3.7
来源
https://github.com/dragen1860/Deep-Learning-with-TensorFlow-book。
代码
import tensorflow as tf
# 创建4个张量
a = tf.constant(1.)
b = tf.constant(2.)
c = tf.constant(3.)
w = tf.constant(4.)
with tf.GradientTape() as tape:# 构建梯度环境
tape.watch([w]) # 将w加入梯度跟踪列表
# 构建计算过程
y = a * w**2 + b * w + c
# 求导
[dy_dw] = tape.gradient(y, [w])
print("answer is:")
print(dy_dw)
运行结果


本文详细介绍使用TensorFlow在Python环境下进行梯度计算的过程。通过创建四个张量并构建计算图,利用GradientTape实现自动求导,最终计算出目标函数关于特定变量的导数。适合初学者理解TensorFlow中自动求导机制。
3526

被折叠的 条评论
为什么被折叠?



