設(shè)置
importtensorflow astftf.enable_eager_execution()
梯度帶
TensorFlow 提供用于自動(dòng)微分的 tf.GradientTapeAPI - 計(jì)算與其輸入變量相關(guān)的計(jì)算梯度。TensorFlow 通過tf.GradientTape“記錄” 在上下文中執(zhí)行的所有操作到 “磁帶”(tape)上。然后,TensorFlow 使用該磁帶和與每個(gè)記錄操作相關(guān)聯(lián)的梯度來(lái)計(jì)算使用反向模式微分的 “記錄” 計(jì)算的梯度。
例如:
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
您還可以根據(jù)在 “記錄”tf.GradientTape 上下文時(shí)計(jì)算的中間值請(qǐng)求輸出的梯度。
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
默認(rèn)情況下,GradientTape 持有的資源會(huì)在調(diào)用 GradientTape.gradient() 方法后立即釋放。要在同一計(jì)算中計(jì)算多個(gè)梯度,創(chuàng)建一個(gè)持久的梯度帶。這允許多次調(diào)用 gradient() 方法。當(dāng)磁帶對(duì)象 tape 被垃圾收集時(shí)釋放資源。例如:
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
記錄控制流
因?yàn)榇艓В╰ape)在執(zhí)行時(shí)記錄操作,所以自然會(huì)處理 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 記錄上下文管理器內(nèi)部的操作以實(shí)現(xiàn)自動(dòng)區(qū)分。如果梯度是在這個(gè)上下文中計(jì)算的,那么梯度計(jì)算也會(huì)被記錄下來(lái)。因此,同樣的 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
下一步
以上教程中,我們介紹了 TensorFlow 中的梯度計(jì)算。有了這些,我們就有了足夠的基本要素來(lái)構(gòu)建和訓(xùn)練神經(jīng)網(wǎng)絡(luò)。
-
機(jī)器學(xué)習(xí)
+關(guān)注
關(guān)注
66文章
8460瀏覽量
133420 -
tensorflow
+關(guān)注
關(guān)注
13文章
329瀏覽量
60732
原文標(biāo)題:自動(dòng)微分,優(yōu)化機(jī)器學(xué)習(xí)模型的關(guān)鍵技術(shù)
文章出處:【微信號(hào):tensorflowers,微信公眾號(hào):Tensorflowers】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論