開始使用免費開始

用梯度做最佳化

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

The image shows a plot of y equals x squared. It also shows the gradient at x equals -1, x equals 0, and x equals 1.

在實務上,你會使用高階的 tensorflow 操作自動執行梯度下降。不過在本練習中,你會在 x 等於 -1、1 與 0 時自行計算斜率。可用的操作有:GradientTape()multiply()Variable()

本練習屬於課程

Python 的 TensorFlow 入門

檢視課程

練習說明

  • x 定義為以 x0 為初始值的變數。
  • 將損失函式 y 設為 x 乘以 x。不要使用運算子多載。
  • 將函式設為回傳 yx 的梯度。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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))
編輯並執行程式碼