多元線性迴歸
在多數情況下,只做單變量線性迴歸無法得到足以做出精準預測的模型。在本練習中,你將執行多元迴歸,也就是使用超過一個特徵。
你會使用 price_log 作為目標,size_log 與 bedrooms 作為特徵。這些張量都已定義並可使用。你也會把損失函式從均方誤差換成平均絕對誤差:keras.losses.mae()。最後,預測值的計算如下:params[0] + feature1*params[1] + feature2*params[2]。請注意,我們把參數向量 params 定義為一個變數,而不是使用三個變數。在這裡,params[0] 是截距,params[1] 和 params[2] 是斜率。
本練習屬於課程
Python 的 TensorFlow 入門
練習說明
- 定義一個會回傳預測值的線性迴歸模型。
- 設定
loss_function()接受參數向量作為輸入。 - 使用平均絕對誤差作為損失函式。
- 完成最小化操作。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define the linear regression model
def linear_regression(params, feature1 = size_log, feature2 = bedrooms):
return params[0] + feature1*____ + feature2*____
# Define the loss function
def loss_function(____, targets = price_log, feature1 = size_log, feature2 = bedrooms):
# Set the predicted values
predictions = linear_regression(params, feature1, feature2)
# Use the mean absolute error loss
return keras.losses.____(targets, predictions)
# Define the optimize operation
opt = keras.optimizers.Adam()
# Perform minimization and print trainable variables
for j in range(10):
opt.minimize(lambda: loss_function(____), var_list=[____])
print_results(params)