导数计算
以Sigmoid 函数为例求导:
s
i
g
m
o
i
d
(
x
)
=
1
1
+
e
−
x
\mathit{sigmoid}(x) = \frac{1}{1+e^{-x}}
sigmoid(x)=1+e−x1
import tensorflow as tf
#定义sigmoid函数
def sigmoid(x):
s = 1 / (1 + tf.math.exp(-x))
return s
from matplotlib import pyplot as plt
#初始化一组 [−10,10] 之间等间隔的 100 个值
x = tf.linspace(-10.0, 10.0, 100)
#定义sigmoid函数的导数
def sigmoid_derivative(x):
d_s = sigmoid(x) * (1 - sigmoid(x))
return d_s
plt.plot(x, sigmoid_derivative(x))
plt.show()
输出图像:
自动微分
TensorFlow 可以使用 tf.GradientTape
跟踪全部运算过程,以便在必要的时候计算梯度。当然,对于上方 Sigmoid 一元函数而言,也就是自动求导过程。
x = tf.Variable(x)
with tf.GradientTape() as tape: # 追踪梯度
s = 1 / (1 + tf.math.exp(-x))
grad = tape.gradient(s, x) # 计算梯度
grad
输出图像: