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 [ ]:
 
 
我的旨在学过的东西不再忘记(主要使用艾宾浩斯遗忘曲线算法及其它智能学习复习算法)的偏公益性质的完全免费的编程视频学习网站: fanrenyi.com;有各种前端、后端、算法、大数据、人工智能等课程。
博主25岁,前端后端算法大数据人工智能都有兴趣。
大家有啥都可以加博主联系方式(qq404006308,微信fan404006308)互相交流。工作、生活、心境,可以互相启迪。
聊技术,交朋友,修心境,qq404006308,微信fan404006308
26岁,真心找女朋友,非诚勿扰,微信fan404006308,qq404006308
人工智能群:939687837

作者相关推荐

原文地址:https://www.cnblogs.com/Renyi-Fan/p/13394939.html