损失函数

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 入门

Vamos praticar!

Python 中的 TensorFlow 入门

Preparing Video For Download...