前言
其实svm和softmax的一个大区别在他们的损失函数不同,然后其梯度求导就会不同。首先,先来回顾一下softmax
softmax
所谓softmax,把它拆开看,soft & max ,可以理解为是带soft一点的max。那就会有纯max,纯max就好比一个评分函数中,得分最高的那个就是所求的分类,那么带有soft的max呢它是通过一种概率的方式,来把得分转变为概率的形式来展现,得分最高的那类自然概率也就最高,那么得分低的也存在概率,也有一定的几率能够取到,而不是很绝对的只取最高。这算是是一种softmax感性的认识。
softmax函数为
softmax的输入和svm相同,S=Wx,而它的损失函数变成了“交叉熵损失函数”(cross-entropy loss)
也或者写成等价形式
在实际使用中,常常因为指数太大而出现数值爆炸问题,两个非常大的数相除会出现数值不稳定问题,因此我们需要在分子和分母中同时进行以下处理:
其中C 的设置是任意的,在实际变成中,往往把C设置成:
即第 i 个样本所有分值中最大的值,当现有分值减去该最大分值后结果≤0,放在 e 的指数上可以保证分子分布都在0-1之内
※梯度推导(难点)
然后代码就可以依据以上的数学推导来编写。
※代码实现
softmax.py
import numpy as np
from random import shuffle
from past.builtins import xrange
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)
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
num_classes = W.shape[1]
num_train = X.shape[0]
for i in range(num_train):
scores = np.dot