Python与机器学习

2 softmax 回归

2018-12-04  本文已影响2人  水之心

softmax Regression 是解决多分类任务的模型。设有数据集 \{ x^{(1)}, x^{(2)}, \ldots, x^{(m)} \},对于每一个样本 x^{(i)} \in \mathbb{R}^ny^{(i)} \in \{1, 2, \ldots, c\}。令 \theta = \begin{pmatrix} w \\ b \end{pmatrix}\overline{X} = \begin{pmatrix} \overline{x}^{(1)} \\ \overline{x}^{(2)} \\ \vdots \\ \overline{x}^{(m)} \end{pmatrix},其中 \overline{x}^{(i)} = \left(x^{(i)}1 \right)

设每个样本的条件概率估计为

h_{\theta}(\overline{x}^{i}) = \begin{bmatrix} P(y^{(i)} = 1| \overline{x}^{(i)}; \theta) \\ P(y^{(i)} = 2| \overline{x}^{(i)}; \theta)\\ \vdots\\ P(y^{(i)} = c| \overline{x}^{(i)}; \theta)\\ \end{bmatrix} = \frac{1}{\sum_{j=1}^k e^{\theta_j^T \overline{x}^{(i)}}} \begin{bmatrix} e^{\theta_1^T \overline{x}^{(i)}} \\ e^{\theta_2^T \overline{x}^{(i)}} \\ \vdots\\ e^{\theta_c^T \overline{x}^{(i)}} \\ \end{bmatrix}

其 python 代码实现很简单:

def softmax(X):
    exp = np.exp(X)
    # 假设 exp 是矩阵,这里对行进行求和,并要求保留 axis 1,
    # 就是返回 (nrows, 1) 形状的矩阵
    partition = exp.sum(axis=1, keepdims=True)
    return exp / partition

softmax Regression 模型的损失函数不适合使用 \ell_2 损失函数,此时使用交叉熵损失函数。将 y^{(i)} 转换为 one-hot 编码形式:

y^{(i)} = t \Leftrightarrow y^{(i)}_k = \begin{cases} 1 & k = t\\ 0 & k \neq t \end{cases}

其中,k,t \in \{1, 2, \ldots, c\}。这样,{\boldsymbol y^{(i)}} = (y^{(i)}_1, y^{(i)}_2, \dots, y^{(i)}_c) 便可表示 y^{(i)} 的概率形式。这样,我们便可定义两个概率分布的“距离”:

H({\boldsymbol y^{(i)}}, {\boldsymbol y^{(i)}}) = - \sum_{j=1}^c y_j^{(i)} \log \hat{y}_j^{(i)}

由于向量 {\mathbb y^{(i)}} 中元素的特性,当一个样本中仅仅包含一个对象时上面的交叉熵我们可以化简为

H({\boldsymbol y^{(i)}}, \boldsymbol{\hat{y}^{(i)}}) = - \log \hat{y}_t^{(i)}

其中,t 表示 {\mathbb y^{(i)}}t 位置元素为 1,下面我们使用 y^{(i)} 代替 t

对于所有样本,交叉熵损失函数定义为

\ell(\boldsymbol{\Theta}) = \frac{1}{m} \sum_{i=1}^m H\left(\boldsymbol y^{(i)}, \boldsymbol {\hat y}^{(i)}\right ),

其中\boldsymbol{\Theta}代表模型参数。同样地,如果每个样本只有一个标签,那么交叉熵损失可以简写成\ell(\boldsymbol{\Theta}) = -(1/m) \sum_{i=1}^m \log \hat y_{y^{(i)}}^{(i)}。从另一个角度来看,我们知道最小化\ell(\boldsymbol{\Theta})等价于最大化\exp(-m\ell(\boldsymbol{\Theta}))=\prod_{i=1}^m \hat y_{y^{(i)}}^{(i)},即最小化交叉熵损失函数等价于最大化训练数据集所有标签类别的联合预测概率。

上一篇 下一篇

猜你喜欢

热点阅读