設定線性迴歸
單變數線性迴歸會找出單一特徵與目標張量之間的關係。在這個練習中,我們會使用房地產的基地面積與價格。就像在影片中討論的,我們會對兩個張量取自然對數,分別已提供為 price_log 與 size_log。
這個練習中,你會定義模型與損失函式。接著,針對兩組不同的 intercept 與 slope 值評估損失函式。請記得,預測值為 intercept + features*slope。另外,keras.losses.mse() 可供你使用。此外,slope 與 intercept 已經定義為變數。
本練習屬於課程
Python 的 TensorFlow 入門
練習說明
- 定義一個函式,使用
intercept、features、slope來回傳線性迴歸的預測值,且不要使用add()或multiply()。 - 完成
loss_function(),將模型的變數intercept與slope加入為引數。 - 使用
targets與predictions計算均方誤差。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define a linear regression model
def linear_regression(intercept, slope, features = size_log):
return ____
# Set loss_function() to take the variables as arguments
def loss_function(____, ____, features = size_log, targets = price_log):
# Set the predicted values
predictions = linear_regression(intercept, slope, features)
# Return the mean squared error loss
return keras.losses.____
# Compute the loss for different slope and intercept values
print(loss_function(0.1, 0.1).numpy())
print(loss_function(0.1, 0.5).numpy())