20 逻辑回归代价函数详解
1. 逻辑回归的基本形式
在逻辑回归中,我们对输入特征向量 $\mathbf{x} \in \mathbb{R}^n$ 做如下预测:
$$
\hat{y} = \sigma(\mathbf{w}^\top \mathbf{x} + b)
$$
其中:
- $\mathbf{w} \in \mathbb{R}^n$ 是权重向量;
- $b \in \mathbb{R}$ 是偏置项;
- $\sigma(z)$ 是 Sigmoid 函数,定义为:
$$
\sigma(z) = \frac{1}{1 + e^{-z}}
$$
我们把 $\hat{y}$ 解释为:
在给定输入 $\mathbf{x}$ 的条件下,标签 $y = 1$ 的概率,即:
$$
\hat{y} = P(y = 1 \mid \mathbf{x}; \mathbf{w}, b)
$$
因此:
- 若真实标签 $y = 1$,则 $P(y \mid \mathbf{x}) = \hat{y}$
- 若真实标签 $y = 0$,则 $P(y \mid \mathbf{x}) = 1 - \hat{y}$
2. 将两种情况统一成一个概率表达式
由于 $y \in {0, 1}$,我们可以将上述两个情形合并为一个统一的概率公式:
$$
P(y \mid \mathbf{x}; \mathbf{w}, b) = \hat{y}^y (1 - \hat{y})^{(1 - y)}
$$
✅ 验证:
- 当 $y = 1$:上式变为 $\hat{y}^1 (1 - \hat{y})^0 = \hat{y}$
- 当 $y = 0$:上式变为 $\hat{y}^0 (1 - \hat{y})^1 = 1 - \hat{y}$
完全符合我们的期望!
3. 对数似然函数(Log-Likelihood)
为了便于优化,我们对概率取对数(因为对数函数是单调递增的,最大化概率等价于最大化对数概率):
$$
\log P(y \mid \mathbf{x}) = \log\left( \hat{y}^y (1 - \hat{y})^{(1 - y)} \right) = y \log \hat{y} + (1 - y) \log (1 - \hat{y})
$$
注意:这个值是我们希望最大化的(因为它是“对数似然”)。
但机器学习中通常采用最小化损失函数的形式,所以我们定义单个样本的损失函数为它的负值:
$$
\mathcal{L}(\hat{y}, y) = - \left[ y \log \hat{y} + (1 - y) \log (1 - \hat{y}) \right]
$$
这就是著名的 交叉熵损失(Cross-Entropy Loss) 。
4. 整个训练集的代价函数(Cost Function)
假设训练集包含 $m$ 个独立同分布(i.i.d.)的样本 ${(\mathbf{x}^{(i)}, y^{(i)})}_{i=1}^m$,则整个数据集的联合概率为:
$$
P(\text{所有标签} \mid \text{所有 } \mathbf{x}) = \prod_{i=1}^m P(y^{(i)} \mid \mathbf{x}^{(i)})
$$
取对数得:
$$
\log P = \sum_{i=1}^m \left[ y^{(i)} \log \hat{y}^{(i)} + (1 - y^{(i)}) \log (1 - \hat{y}^{(i)}) \right]
$$
根据最大似然估计(Maximum Likelihood Estimation, MLE) ,我们要最大化这个对数似然。
等价地,我们最小化其负值,即总代价函数:
$$
J(\mathbf{w}, b) = -\frac{1}{m} \sum_{i=1}^m \left[ y^{(i)} \log \hat{y}^{(i)} + (1 - y^{(i)}) \log (1 - \hat{y}^{(i)}) \right]
$$
其中:
- $\hat{y}^{(i)} = \sigma(\mathbf{w}^\top \mathbf{x}^{(i)} + b)$
- 系数 $\frac{1}{m}$ 是为了对损失进行平均,使代价函数尺度更稳定(不影响优化方向)
5. 总结:为什么用这个代价函数?
- 这个代价函数来源于概率建模:我们假设输出是伯努利分布的概率。
- 通过最大似然估计自然导出交叉熵形式。
- 它是凸函数(在逻辑回归中),保证梯度下降能找到全局最优解。
- 相比平方误差(MSE),它在分类任务中梯度更合理,避免学习缓慢的问题。
✅ 最终公式汇总
预测值:
$$
\hat{y}^{(i)} = \sigma(\mathbf{w}^\top \mathbf{x}^{(i)} + b) = \frac{1}{1 + e^{-(\mathbf{w}^\top \mathbf{x}^{(i)} + b)}}
$$单样本损失:
$$
\mathcal{L}^{(i)} = - \left[ y^{(i)} \log \hat{y}^{(i)} + (1 - y^{(i)}) \log (1 - \hat{y}^{(i)}) \right]
$$整体代价函数:
$$
J(\mathbf{w}, b) = \frac{1}{m} \sum_{i=1}^m \mathcal{L}^{(i)} = -\frac{1}{m} \sum_{i=1}^m \left[ y^{(i)} \log \hat{y}^{(i)} + (1 - y^{(i)}) \log (1 - \hat{y}^{(i)}) \right]
$$