损失函数 (Loss Function)
📌 核心定义 (What)
Section titled “📌 核心定义 (What)”一句话定义:损失函数(也叫代价函数 Cost Function)是一个数学函数,用来衡量模型预测值与真实值之间的差距。
差距越小,说明模型越准;差距越大,说明模型越烂。训练 AI 的本质,就是想尽办法让 Loss 变小。
🏠 生活类比 (Analogy)
Section titled “🏠 生活类比 (Analogy)”🎯 “射击靶子”
Section titled “🎯 “射击靶子””- 模型:射击运动员。
- 预测值:子弹打中的位置。
- 真实值:靶心。
- Loss:子弹距离靶心的距离。
如果打在 10 环(靶心),Loss = 0。 如果打在 1 环(边缘),Loss 很大。 教练(优化器)根据这个距离,纠正运动员的姿势(更新参数)。
📉 交互演示:损失函数 (Interactive)
Section titled “📉 交互演示:损失函数 (Interactive)”调整预测值,观察 MSE 和 Cross-Entropy 损失的变化曲线。
📉 损失函数可视化
MSE = (y - ŷ)² = (1 - 0.70)² = 0.0900
MSE Loss
0.0900
CE Loss
0.3567
MSE 特性:
- 误差越大,惩罚以平方增长
- 对异常值敏感
- 最小值在 ŷ = y 时取得
💡 拖动预测值,观察 Loss 如何变化 | 目标:让 Loss 最小化
📊 常见 Loss 公式 (Math)
Section titled “📊 常见 Loss 公式 (Math)”1. 均方误差 (MSE) - 回归任务
Section titled “1. 均方误差 (MSE) - 回归任务”用于预测数值(如房价、温度)。
Mean Squared Error
- : 真实值
- : 预测值
- 特点:误差越大,惩罚越重(因为有平方)。对异常值敏感。
2. 交叉熵 (Cross Entropy) - 分类任务
Section titled “2. 交叉熵 (Cross Entropy) - 分类任务”用于预测类别(如猫/狗,0-9 数字)。
Cross Entropy Loss
- 衡量两个概率分布的差异。
- 如果真实类别是 1,预测概率是 0.9,Loss 小。
- 如果真实类别是 1,预测概率是 0.1,Loss 巨大。
💻 代码实现 (Code)
Section titled “💻 代码实现 (Code)”import torchimport torch.nn as nn
# --- 回归任务 (MSE) ---criterion_mse = nn.MSELoss()pred_price = torch.tensor([250.0, 150.0], requires_grad=True) # 预测房价real_price = torch.tensor([300.0, 150.0]) # 真实房价
loss_mse = criterion_mse(pred_price, real_price)# ((250-300)^2 + (150-150)^2) / 2 = 2500 / 2 = 1250print(f"MSE Loss: {loss_mse.item()}")
# --- 分类任务 (Cross Entropy) ---criterion_ce = nn.CrossEntropyLoss()# 3个类别的 Logits (未经过 Softmax)pred_logits = torch.tensor([[2.0, 1.0, 0.1]])# 真实类别是 Index 0real_class = torch.tensor([0])
loss_ce = criterion_ce(pred_logits, real_class)print(f"CE Loss: {loss_ce.item()}")