修改損失函式
在前一個練習中,你定義了一個 tensorflow 的損失函式,然後針對一組實際值與預測值評估了一次。在本練習中,你會在另一個名為 loss_function() 的函式內計算損失;這個函式會先根據資料與變數產生預測值。這麼做的目的是要建構一個以可訓練模型變數為自變數、並回傳損失值的函式。接著你就能反覆以不同的變數值評估此函式,直到找到最小值。實務上,你會將這個函式傳給 tensorflow 的最佳化器。注意,features 與 targets 已經定義並可使用。此外,Variable、float32 與 keras 也已可用。
本練習屬於課程
Python 的 TensorFlow 入門
練習說明
- 定義一個變數
scalar,初始值為 1.0,型別為float32。 - 定義名為
loss_function()的函式,依序以scalar、features、targets作為引數。 - 使用平均絕對誤差的損失函式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize a variable named scalar
scalar = ____(1.0, ____)
# Define the model
def model(scalar, features = features):
return scalar * features
# Define a loss function
def loss_function(____, features = features, targets = targets):
# Compute the predicted values
predictions = model(scalar, features)
# Return the mean absolute error loss
return keras.losses.____(targets, predictions)
# Evaluate the loss function and print the loss
print(loss_function(scalar).numpy())