用梯度做最佳化
給定一個你想要最小化的損失函式:$y = x^{2}$。你可以在不同的 x 值上,用 GradientTape() 這個操作來計算斜率(梯度)。如果斜率為正,把 x 調小可以降低損失;如果斜率為負,把 x 調大可以降低損失。這就是梯度下降的原理。

在實務上,你會使用高階的 tensorflow 操作自動執行梯度下降。不過在本練習中,你會在 x 等於 -1、1 與 0 時自行計算斜率。可用的操作有:GradientTape()、multiply() 和 Variable()。
本練習屬於課程
Python 的 TensorFlow 入門
練習說明
- 將
x定義為以x0為初始值的變數。 - 將損失函式
y設為x乘以x。不要使用運算子多載。 - 將函式設為回傳
y對x的梯度。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def compute_gradient(x0):
# Define x as a variable with an initial value of x0
x = ____(x0)
with GradientTape() as tape:
tape.watch(x)
# Define y using the multiply operation
y = ____
# Return the gradient of y with respect to x
return tape.gradient(____, ____).numpy()
# Compute and print gradients at x = -1, 1, and 0
print(compute_gradient(-1.0))
print(compute_gradient(1.0))
print(compute_gradient(0.0))