微信扫一扫打赏支持

TensorFlow2_200729系列---1、TensorFlow2自动求导实例

TensorFlow2_200729系列---1、TensorFlow2自动求导实例

一、总结

一句话总结:

用tf.GradientTape():[dy_da,dy_db,dy_dc] = tape.gradient(y, [a,b,c])
import tensorflow as tf 

# 创建4个张量
a = tf.constant(1.)
b = tf.constant(2.)
c = tf.constant(3.)
x = tf.constant(4.)


with tf.GradientTape() as tape:# 构建梯度环境
    tape.watch([a,b,c]) # 将w加入梯度跟踪列表
    # 构建计算过程
    y = a**2 * x**2 + b * x + c
# 求导
[dy_da,dy_db,dy_dc] = tape.gradient(y, [a,b,c])
print(dy_da)# 2*a*x**2=32
print(dy_db)# x=4
print(dy_dc)# 1

结果
tf.Tensor(32.0, shape=(), dtype=float32)
tf.Tensor(4.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)

 

 

1、为什么要使用TensorFlow2(TensorFlow2的好处)?

1、GPU加速
2、自动求导
3、神经网络Layers

 

 

 

二、TensorFlow2自动求导实例

博客对应课程的视频位置:

 

In [3]:
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(dy_dw)
tf.Tensor(10.0, shape=(), dtype=float32)
In [7]:
import tensorflow as tf 

# 创建4个张量
a = tf.constant(1.)
b = tf.constant(2.)
c = tf.constant(3.)
x = tf.constant(4.)


with tf.GradientTape() as tape:# 构建梯度环境
	tape.watch([a,b,c]) # 将w加入梯度跟踪列表
	# 构建计算过程
	y = a**2 * x**2 + b * x + c
# 求导
[dy_da,dy_db,dy_dc] = tape.gradient(y, [a,b,c])
print(dy_da)# 2*a*x**2=32
print(dy_db)# x=4
print(dy_dc)# 1
tf.Tensor(32.0, shape=(), dtype=float32)
tf.Tensor(4.0, shape=(), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
In [ ]:
 

 

 

 
posted @ 2020-07-29 07:41  范仁义  阅读(182)  评论(0)    收藏  举报