cs231n assignment1_Q3_softmax

前言

其实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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值