• CS231n assignment1 Q3 Softmax


    Softmax简介:
    Softmax分类器也叫多项Logistic回归(Multinomial Logistic Regression)。
    对公式的理解:首先将一个负数x通过指数变成整数,求它的概率分布也就是每部分除以总和。
    损失函数
    avatar
    即交叉熵损失函数(cross entroy)

    softmax.py

    import numpy as np
    from random import shuffle
    
    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_train = X.shape[0] #N
      num_classes = W.shape[1] #C
      loss = 0.0
      for i in range(num_train):
        f_i = X[i].dot(W)
        f_i -= np.max(f_i)
        #为避免数值不稳定的问题,每个分值向量都减去向量中的最大值
        sum_j = np.sum(np.exp(f_i))
        p = lambda k:np.exp(f_i[k]) / sum_j
        loss += -np.log(p(y[i]))
        # 计算loss
        for k in range(num_classes):
            p_k = p(k)
            dW[:,k] += (p_k - (k==y[i])) * X[i]
            # 计算梯度
      loss /= num_train
      loss += 0.5 * reg * np.sum(W * W)
      dW /= num_train
      dW += reg*W
      #############################################################################
      #                          END OF YOUR CODE                                 #
      #############################################################################
    
      return loss, dW
    
    
    def softmax_loss_vectorized(W, X, y, reg):
      """
      Softmax loss function, vectorized version.
    
      Inputs and outputs are the same as softmax_loss_naive.
      """
      # Initialize the loss and gradient to zero.
      loss = 0.0
      dW = np.zeros_like(W)
    
      #############################################################################
      # TODO: Compute the softmax loss and its gradient using no 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_train = X.shape[0] #N
      f = X.dot(W)
      #X(N,D) W(D,C) f(N,C)
      f -= np.max(f,axis = 1,keepdims = True)
      #为避免数值不稳定的问题,每个分值向量都减去向量中的最大值
      sum_f = np.sum(np.exp(f),axis = 1,keepdims = True)
      p = np.exp(f)/sum_f
      loss = np.sum(-np.log(p[np.arange(num_train),y]))
      #计算loss
      ind = np.zeros_like(p)
      ind[np.arange(num_train),y] = 1
      #label正确的那一栏为1,其余为0
      dW = X.T.dot(p - ind)
      """
        计算梯度
        它的含义是,当我们有一个分值向量f,损失函数对这个分值向量求导的结果等于向量里每个类别对应的概率值,但除了那个正确类别的概率值,它要再减去1。例如,我们的概率向量为p = [0.2, 0.3, 0.5],第二类为正确的类别,那么的分值梯度就为df = [0.2, -0.7, 0.5]。
      """
      loss /= num_train
      loss += 0.5 * reg * np.sum(W * W)
      #加上正则化项
      dW /= num_train
      dW += reg*W
      #############################################################################
      #                          END OF YOUR CODE                                 #
      #############################################################################
    
      return loss, dW
    
    
  • 相关阅读:
    计算字符个数
    字符串最后一个单词的长度
    C++面试宝典
    给定三角形ABC和一点P(x,y,z),判断点P是否在ABC内,给出思路并手写代码
    N-皇后问题(N Queens)
    图着色算法详解(Graph Coloring)
    c++学习路线连接
    数据结构--经典排序算法
    5. 最长回文子串
    4. 寻找两个有序数组的中位数
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/10178999.html
Copyright © 2020-2023  润新知