開始使用免費開始

訓練線性模型

在這個練習中,我們將延續前一個練習的內容。截距與斜率 interceptslope 已經被定義並初始化。此外,也已定義函式 loss_function(intercept, slope),用於根據資料與模型變數計算損失。

你現在要把最佳化操作定義為 opt。接著,透過最小化損失來訓練單變數線性模型,以找出 interceptslope 的最佳值。請注意,opt 操作每一步都會往最適解靠近,但需要很多步才會收斂。因此,你必須重複執行這個操作。

本練習屬於課程

Python 的 TensorFlow 入門

檢視課程

練習說明

  • 使用學習率 0.5 將 Adam 最佳化器初始化為 opt
  • 對最佳化器呼叫 .minimize() 方法。
  • 以 lambda 函式的形式,將帶有正確引數的 loss_function() 傳入 .minimize()
  • var_list 提供需要被更新的變數清單。

動手互動練習

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

# Initialize an Adam optimizer
opt = keras.optimizers.____(0.5)

for j in range(100):
	# Apply minimize, pass the loss function, and supply the variables
	opt.____(lambda: ____(____, ____), var_list=[____, ____])

	# Print every 10th value of the loss
	if j % 10 == 0:
		print(loss_function(intercept, slope).numpy())

# Plot data and regression line
plot_results(intercept, slope)
編輯並執行程式碼