前言1、公式推导1.1评分函数用矩阵形式1.2标量对列向量求导规则1.3单样本对权重求导表示在全训练集2、实现代码中
前言矩阵对矩阵求导规律:
从上面的公式可以看出,矩阵导出矩阵后,维度会加倍。 也就是说,dC/dB的维度为(sp,rq )。 好在本文中只是用标量)推导矩阵,所以求倒数的维数和b一样是pqp*qpq。
另一方面,公式的推导基于softmax函数的损失函数形式与SVM基本一致,可以直接引用。
从上面的介绍可以看出,整个训练集的损失函数是
L=1nILIr(w ) w ) ) k ) jwk,L2L=(FRAC(1) n ) sum (I ) l _ { I } (lambdar (w ) w ) ) w ) ) ) w
f=X W f=XW f=XW
这里使用的是和代码相同的形状。 请注意笔记是f=W*X。 结果只是倒置关系。 为了便于编程,这里以代码中的格式进行讨论。
单个示例的评分函数公式如下
LI=FyILOGJEF
j ) ∂ L i ∂ W = − ∂ f y i ∂ W + ∂ l o g ( ∑ j e f j ) ∂ W L_{i}=-f_{y_{i}}+log(sum_{j}e^{f_{j}})\ frac{partial L_{i}}{partial W}=-frac{partial f_{y_i}}{partial W}+ frac{partial log(sum_{j}e^{f_{j}}) }{partial W} Li=−fyi+log(j∑efj)∂W∂Li=−∂W∂fyi+∂W∂log(∑jefj) 1.1 将评分函数表达为矩阵形式 1.2 标量对列向量求导规则为了得到评分函数的某一项对权重阵W求导,先引入如下规则:
从引理得到如下
对于前两个样本,假设正确分类的标签分别是第三类和第二类,则
根据线性可加原则,对于所有的N个样本,有
代码如下(示例):
def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) N = X.shape[0] C = W.shape[1] for i in range(N): score = X[i, :].dot(W) score_exp = np.exp(score) score_exp_nor = score_exp / np.sum(score_exp) loss += -np.log(score_exp_nor[y[i]]) dW[:, y[i]] += - X[i] for j in range(C): dW[:, j] += X[i]*(np.exp(score[j]) / np.sum(score_exp)) loss = loss/N + reg * np.sum(W**2) dW /= N dW += 2*reg * W矢量化实现
scores = X.dot(W) scores_exp = np.exp(scores) scores_exp_nor = scores_exp / ( np.sum(scores_exp, axis=1).reshape(N, 1) * np.ones([1, 10])) loss = np.sum(-np.log(scores_exp_nor[np.arange(N), y])) / N loss += reg*np.sum(W**2) margin = np.zeros_like(scores) margin += scores_exp_nor margin[np.arange(N), y] += -1 dW = X.T.dot(margin)/N + 2 * reg * W