損失函式

Python 的 TensorFlow 入門

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

損失函式入門

  • tensorflow 的基礎運算
    • 用來訓練模型
    • 衡量模型擬合度
  • 值越大 → 擬合越差
    • 目標是最小化損失函式
Python 的 TensorFlow 入門

TensorFlow 中的常見損失函式

  • TensorFlow 提供常見的損失函式

    • 均方誤差(MSE)
    • 平均絕對誤差(MAE)
    • Huber 誤差
  • 可從 tf.keras.losses() 取得損失函式

    • tf.keras.losses.mse()
    • tf.keras.losses.mae()
    • tf.keras.losses.Huber()
Python 的 TensorFlow 入門

為何在意損失函式?

此圖顯示在 -2 到 2 區間上繪製的 MSE、MAE 與 Huber 損失函式。

  • MSE
    • 對離群值懲罰強
    • 在最小值附近(梯度)敏感度高
  • MAE
    • 隨誤差大小線性成長
    • 在最小值附近敏感度低
  • Huber
    • 在最小值附近類似 MSE
    • 遠離最小值時類似 MAE
Python 的 TensorFlow 入門

定義損失函式

# Import TensorFlow under standard alias
import tensorflow as tf

# Compute the MSE loss
loss = tf.keras.losses.mse(targets, predictions)
Python 的 TensorFlow 入門

定義損失函式

# Define a linear regression model
def linear_regression(intercept, slope = slope, features = features):
    return intercept + features*slope
# Define a loss function to compute the MSE
def loss_function(intercept, slope, targets = targets, features = features):
    # Compute the predictions for a linear model
    predictions = linear_regression(intercept, slope)

    # Return the loss
    return tf.keras.losses.mse(targets, predictions)
Python 的 TensorFlow 入門

定義損失函式

# Compute the loss for test data inputs
loss_function(intercept, slope, test_targets, test_features)
10.77
# Compute the loss for default data inputs
loss_function(intercept, slope)
5.43
Python 的 TensorFlow 入門

一起來練習吧!

Python 的 TensorFlow 入門

Preparing Video For Download...