[CS231n@Stanford] Assignment1-Q3 (python) Softmax实现


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_classes = W.shape[1]
  num_train = X.shape[0]
  for i in xrange(num_train):
      scores = X[i].dot(W)
      shift_scores = scores - max(scores)
      loss_i = -shift_scores[y[i]] + np.log(np.sum(np.exp(shift_scores)))
      loss += loss_i
      for j in xrange(num_classes):
        softmax_output = np.exp(shift_scores[j])/np.sum(np.exp(shift_scores))
        if j == y[i]:
            dW[:,j] += (softmax_output-1) *X[i] 
        else: 
            dW[:,j] += softmax_output *X[i] 
  
  loss /= num_train 
  loss +=  0.5* reg * np.sum(W * W)
  dW = dW/num_train + reg* W    
   
  pass
  #############################################################################
  #                          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_classes = W.shape[1]
  num_train = X.shape[0]
  scores = X.dot(W)
  shift_scores = scores - np.max(scores, axis = 1).reshape(-1,1)
  softmax_output = np.exp(shift_scores)/np.sum(np.exp(shift_scores), axis = 1).reshape(-1,1)
  loss = -np.sum(np.log(softmax_output[np.arange(num_train), y]))
  loss /= num_train 
  loss +=  0.5* reg * np.sum(W * W)
  

  softmax_output[np.arange(num_train), y] += -1
  dW = (X.T).dot(softmax_output)
  dW = dW/num_train + reg* W 
  
  pass
  #############################################################################
  #                          END OF YOUR CODE                                 #
  #############################################################################

  return loss, dW

linear_classifier.py 的实现参见:http://blog.csdn.net/zzhangjizhi/article/details/52457278


softmax.ipynb的部分代码实现

# Use the validation set to tune hyperparameters (regularization strength and
# learning rate). You should experiment with different ranges for the learning
# rates and regularization strengths; if you are careful you should be able to
# get a classification accuracy of over 0.35 on the validation set.
from linear_classifier import Softmax
results = {}
best_val = -1
best_softmax = None
learning_rates = [1e-7, 5e-7]
regularization_strengths = [5e4, 1e8]

################################################################################
# TODO:                                                                        #
# Use the validation set to set the learning rate and regularization strength. #
# This should be identical to the validation that you did for the SVM; save    #
# the best trained softmax classifer in best_softmax.                          #
################################################################################


iters = 2000  
for lr in learning_rates:  
    for reg in regularization_strengths:  
        softmax = Softmax()  
        softmax.train(X_train, y_train, learning_rate=lr, reg=reg, num_iters=iters)  
          
        y_train_pred = softmax.predict(X_train)  
        acc_train = np.mean(y_train == y_train_pred)  
          
        y_val_pred = softmax.predict(X_val)  
        acc_val = np.mean(y_val == y_val_pred)  
  
        results[(lr, reg)] = (acc_train, acc_val)  
          
        if best_val < acc_val:  
            best_val = acc_val  
            best_softmax = softmax  




pass
################################################################################
#                              END OF YOUR CODE                                #
################################################################################
    
# Print out results.
for lr, reg in sorted(results):
    train_accuracy, val_accuracy = results[(lr, reg)]
    print 'lr %e reg %e train accuracy: %f val accuracy: %f' % (
                lr, reg, train_accuracy, val_accuracy)
    
print 'best validation accuracy achieved during cross-validation: %f' % best_val


lr 1.000000e-07 reg 5.000000e+04 train accuracy: 0.333633 val accuracy: 0.343000
lr 1.000000e-07 reg 1.000000e+08 train accuracy: 0.100265 val accuracy: 0.087000
lr 5.000000e-07 reg 5.000000e+04 train accuracy: 0.326980 val accuracy: 0.341000
lr 5.000000e-07 reg 1.000000e+08 train accuracy: 0.100265 val accuracy: 0.087000
best validation accuracy achieved during cross-validation: 0.343000
softmax on raw pixels final test set accuracy: 0.348000





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Stanford CoreNLP是一个开源的自然语言处理工具包,提供了一系列的NLP工具和库,用于文本分析、信息提取、语义标注、句法分析等任务。而stanford-corenlp-full-2015-12-09则是这个工具包的一个特定版本。 stanford-corenlp-full-2015-12-09包含了所有Stanford CoreNLP工具和库的完整集合。它包括了多种NLP模型,用于处理不同的语言和任务。这个版本发布于2015年12月09日,并且提供了丰富的功能和性能优化。它支持英语、中文等多种语言的文本处理,并且可以用于词性标注、命名实体识别、关系抽取、情感分析、依存句法分析等多种任务。 使用stanford-corenlp-full-2015-12-09,我们可以通过简单的调用API接口来使用各种NLP功能。它可以处理单个文本、文本集合甚至是大规模的文本数据。我们可以提取文本的关键信息,如实体识别、情感分析和关键词提取等。此外,它还提供了丰富的语言处理技术,如分词、词性标注、命名实体识别和依存句法分析,可以帮助研究人员和开发者进行更深入的文本分析和语义理解。 总而言之,stanford-corenlp-full-2015-12-09是一个功能强大且广泛使用的NLP工具包,提供了多种NLP任务的解决方案。它可以帮助使用者快速准确地分析文本,提取有用的信息,并为后续的文本处理和语义分析任务提供基础支持。 ### 回答2: Stanford CoreNLP是斯坦福大学开发的一款自然语言处理工具包,其完整版2015-12-09是指CoreNLP的一个特定版本,发布于2015年12月9号。Stanford CoreNLP提供了一系列强大的功能,包括分词、词性标注、命名实体识别、句法分析、依存关系分析等。这些功能能够帮助用户对文本进行深入的语言理解和分析。 Stanford CoreNLP使用Java编写,可以通过命令行或API接口进行使用。它支持多种语言,包括英语、中文、阿拉伯语等。用户可以通过简单的调用相应的功能模块,实现对文本的处理和分析。 在中文处理方面,Stanford CoreNLP通过使用中文分词器以及中文词性标注器,能够将中文文本进行分词和词性标注。此外,它还能够进行中文的命名实体识别,例如识别人名、地名、时间等实体。同时,Stanford CoreNLP还提供了句法分析和依存关系分析功能,可以帮助用户理解句子的结构和句法关系。 总之,Stanford CoreNLP完整版2015-12-09是一款功能强大的自然语言处理工具,能够帮助用户对文本进行深入的语言分析和理解。它具有广泛的应用领域,包括信息提取、机器翻译、文本分类等。用户可以使用它来处理中文文本,并通过其提供的多种功能模块对文本进行处理和分析。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值