# 自动微分和梯度带

## 创建

``````!pip install -q tensorflow==2.0.0-beta1
import tensorflow as tf
``````

## 梯度带

TensorFlow 为自动微分提供了 tf.GradientTape API ，根据某个函数的输入变量来计算它的导数。Tensorflow 会把 'tf.GradientTape' 上下文中执行的所有操作都记录在一个磁带上 ("tape")。 然后基于这个磁带和每次操作产生的导数，用反向微分法（"reverse mode differentiation"）来计算这些被“记录在案”的函数的导数。

``````x = tf.ones((2, 2))

t.watch(x)
y = tf.reduce_sum(x)
z = tf.multiply(y, y)

# Derivative of z with respect to the original input tensor x
for i in [0, 1]:
for j in [0, 1]:
assert dz_dx[i][j].numpy() == 8.0
``````

``````x = tf.ones((2, 2))

t.watch(x)
y = tf.reduce_sum(x)
z = tf.multiply(y, y)

# Use the tape to compute the derivative of z with respect to the
# intermediate value y.
assert dz_dy.numpy() == 8.0
``````

``````x = tf.constant(3.0)
t.watch(x)
y = x * x
z = y * y
dz_dx = t.gradient(z, x)  # 108.0 (4*x^3 at x = 3)
dy_dx = t.gradient(y, x)  # 6.0
del t  # Drop the reference to the tape
``````

### 记录控制流

``````def f(x, y):
output = 1.0
for i in range(y):
if i > 1 and i < 5:
output = tf.multiply(output, x)
return output

t.watch(x)
out = f(x, y)

x = tf.convert_to_tensor(2.0)

``````

### 高阶导数

``````x = tf.Variable(1.0)  # Create a Tensorflow variable initialized to 1.0