0%

Tensorflow之自动求导实现

1
2
3
4
5
6
7
8
9
10
11
#自动求导机制
import tensorflow as tf
#tf.Variable()用于声明一个变量,它需要一个初始值将其存储在initial_value中。
x = tf.Variable(initial_value=3.)#Pyhon中可以使用整数后加小数点表示将该整数定义为浮点数类型。例如3.表示3.0
with tf.GradientTape() as tape:
y = tf.math.log(x)#这里math.log()表示的是底数为e(只是默认为e,可以修改)的对数函数,类似的,如果要计算y=x的平方的导数,将math.log()改为square即可
y_grad = tape.gradient(y,x)
print([y,y_grad])
'''输出结果为:
[<tf.Tensor: id=93, shape=(), dtype=float32, numpy=1.0986123>, <tf.Tensor: id=96, shape=(), dtype=float32, numpy=0.33333334>]
'''