設置
importtensorflow astftf.enable_eager_execution()
梯度帶
TensorFlow 提供用于自動微分的 tf.GradientTapeAPI - 計算與其輸入變量相關的計算梯度。TensorFlow 通過tf.GradientTape“記錄” 在上下文中執行的所有操作到 “磁帶”(tape)上。然后,TensorFlow 使用該磁帶和與每個記錄操作相關聯的梯度來計算使用反向模式微分的 “記錄” 計算的梯度。
例如:
x = tf.ones((2, 2)) with tf.GradientTape() as t: t.watch(x) y = tf.reduce_sum(x) z = tf.multiply(y, y)# Derivative of z with respect to the original input tensor xdz_dx = t.gradient(z, x)for i in [0, 1]: for j in [0, 1]: assert dz_dx[i][j].numpy() == 8.0
您還可以根據在 “記錄”tf.GradientTape 上下文時計算的中間值請求輸出的梯度。
x = tf.ones((2, 2)) with tf.GradientTape() as t: 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.dz_dy = t.gradient(z, y)assert dz_dy.numpy() == 8.0
默認情況下,GradientTape 持有的資源會在調用 GradientTape.gradient() 方法后立即釋放。要在同一計算中計算多個梯度,創建一個持久的梯度帶。這允許多次調用 gradient() 方法。當磁帶對象 tape 被垃圾收集時釋放資源。例如:
x = tf.constant(3.0)with tf.GradientTape(persistent=True) as t: t.watch(x) y = x * x z = y * ydz_dx = t.gradient(z, x) # 108.0 (4*x^3 at x = 3)dy_dx = t.gradient(y, x) # 6.0del t # Drop the reference to the tape
記錄控制流
因為磁帶(tape)在執行時記錄操作,所以自然會處理 Python 控制流(例如使用 ifs 和 whiles):
def f(x, y): output = 1.0 for i in range(y): if i > 1 and i < 5:? ? ? output = tf.multiply(output, x)? return outputdef grad(x, y):? with tf.GradientTape() as t:? ? t.watch(x)? ? out = f(x, y)? return t.gradient(out, x) x = tf.convert_to_tensor(2.0)assert grad(x, 6).numpy() == 12.0assert grad(x, 5).numpy() == 12.0assert grad(x, 4).numpy() == 4.0
高階梯度
GradientTape 記錄上下文管理器內部的操作以實現自動區分。如果梯度是在這個上下文中計算的,那么梯度計算也會被記錄下來。因此,同樣的 API 也適用于高階梯度。例如:
x = tf.Variable(1.0) # Create a Tensorflow variable initialized to 1.0with tf.GradientTape() as t: with tf.GradientTape() as t2: y = x * x * x # Compute the gradient inside the 't' context manager # which means the gradient computation is differentiable as well. dy_dx = t2.gradient(y, x)d2y_dx2 = t.gradient(dy_dx, x)assert dy_dx.numpy() == 3.0assert d2y_dx2.numpy() == 6.0
下一步
-
機器學習
+關注
關注
66文章
8438瀏覽量
133024 -
tensorflow
+關注
關注
13文章
329瀏覽量
60615
原文標題:自動微分,優化機器學習模型的關鍵技術
文章出處:【微信號:tensorflowers,微信公眾號:Tensorflowers】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
相關推薦
評論