cs231n svm作业笔记

 1.线性分类基本概念

现在假设有一个包含很多图像的训练集x_{i},每个图像都有一个对应的分类标签y_{i}。对x_{i}y_{i}

构建一个简单的映射 :

                                      

假设图像只有4个像素(都是黑白像素,这里不考虑RGB通道),有3个分类(红色代表猫,绿色代表狗,蓝色代表船,注意,这里的红、绿和蓝3种颜色仅代表分类,和RGB通道没有关系),列如

cs231n svm作业笔记_第1张图片

 2.svm损失函数

                               cs231n svm作业笔记_第2张图片

 s_{j}代表错误标签通过f(x_{i},,W)预测所得值,s_{y_{j}}代表正确标签所得值,\Delta是超参数项,以猫猫图为例:

cs231n svm作业笔记_第3张图片

正则化项 :

                                          

完整公式为:

3.svm损失函数梯度代码 

 位于cs231n/classifiers/linear_svm.py文件中,分为标准版与向量版:

def svm_loss_naive(W, X, y, reg):
    """
    Structured SVM 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
    """
    dW = np.zeros(W.shape) # initialize the gradient as zero

    # compute the loss and the gradient
    num_classes = W.shape[1] #种类数
    num_train = X.shape[0]   #训练集图片数
    loss = 0.0               #损失值
    
    for i in range(num_train):
        scores = X[i].dot(W)    
        correct_class_score = scores[y[i]] #正确标签得分
        for j in range(num_classes): 
            if j == y[i]:
                continue       #跳过正确标签
            margin = scores[j] - correct_class_score + 1 # note delta = 1
            # 损失值计算
            if margin > 0: # max计算
                loss += margin
                dW[:, j] += X[i]*1.0    # 错误标签梯度计算
                dW[:, y[i]] -= X[i]*1.0 # 正确标签梯度计算

    # Right now the loss is a sum over all training examples, but we want it
    # to be an average instead so we divide by num_train.
    loss /= num_train 

    # Add regularization to the loss.
    loss += reg * np.sum(W * W) 正则化项计算

    #############################################################################
    # TODO:                                                                     #
    # Compute the gradient of the loss function and store it dW.                #
    # Rather than first computing the loss and then computing the derivative,   #
    # it may be simpler to compute the derivative at the same time that the     #
    # loss is being computed. As a result you may need to modify some of the    #
    # code above to compute the gradient.                                       #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    
    '''
    # verbose version:
    # try exchanging the loop of k and j !
    for i in range(num_train):
        scores = X[i].dot(W)
        for k in range(num_classes):
            if k == y[i]:
                for j in range(num_classes):
                    if j == y[i]:
                        continue
                    margin = scores[j] - scores[y[i]] + 1
                    if margin > 0:
                        dW[:, k] -= X[i]*1.0
            else:
                margin = scores[k] - scores[y[i]] + 1
                if margin > 0:
                    dW[:, k] += X[i]*1.0
                
    dW = dW / num_train + 2*reg*W
    '''
    
    dW /= num_train
    dW += 2*reg*W #正则化梯度项
    
    pass

    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    
    return loss, dW

向量形式为:

def svm_loss_vectorized(W, X, y, reg):
    """
    Structured SVM loss function, vectorized implementation.

    Inputs and outputs are the same as svm_loss_naive.
    """
    loss = 0.0
    dW = np.zeros(W.shape) # initialize the gradient as zero

    #############################################################################
    # TODO:                                                                     #
    # Implement a vectorized version of the structured SVM loss, storing the    #
    # result in loss.                                                           #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    
    num_train = X.shape[0]
    
    scores = X.dot(W)
    margin = np.maximum(0, scores.T - scores[range(num_train), y] + 1).T # note delta = 1
    margin[range(num_train), y] = 0 #相同标签置0
    data_loss = np.sum(margin) * 1.0 / num_train
    reg_loss = reg*np.sum(np.square(W)) #正则化值
    
    loss = data_loss + reg_loss
    
    pass

    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    #############################################################################
    # TODO:                                                                     #
    # Implement a vectorized version of the gradient for the structured SVM     #
    # loss, storing the result in dW.                                           #
    #                                                                           #
    # Hint: Instead of computing the gradient from scratch, it may be easier    #
    # to reuse some of the intermediate values that you used to compute the     #
    # loss.                                                                     #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    
    X_effect = (margin > 0).astype('float')                       
    # 每个样本i在非y[i]的类上产生X[i]的梯度 ,si的梯度为1
    X_effect[range(num_train), y] -= np.sum(X_effect, axis=1)   
    # 每个样本i在y[i]的类上产生sigma(margin gt 0)*X[i](除y[i]的margin)的梯度
    
    dW = X.T.dot(X_effect)
    dW /= num_train 
    dW += 2*reg*W
    
    
    ''' verbose version: 
    margin_chara = (margin > 0).astype('float')
    margin_chara_sum = np.sum(margin_chara, axis=1).astype('float')
    
    for i in range(num_train):
        dW += (margin_chara[i][:, np.newaxis]*X[i]).T  # broadcast
        # dW[:, y[i]] -= margin_chara[i, y[i]]*X[i]  # margin_chara[i, y[i]] == 0 is always 
        dW[:, y[i]] -= margin_chara_sum[i]*X[i]
    
    dW /= num_train
    dW += 2*reg*W
    '''
    
    pass

    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    return loss, dW

4.LinearClassifier代码:

该部分主要用于实现SGD(随机梯度下降)

class LinearClassifier(object):

    def __init__(self):
        self.W = None

    def train(self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100,
              batch_size=200, verbose=False):
        """
        Train this linear classifier using stochastic gradient descent.

        Inputs:
        - X: A numpy array of shape (N, D) containing training data; there are N
          training samples each of dimension D.
        - y: A numpy array of shape (N,) containing training labels; y[i] = c
          means that X[i] has label 0 <= c < C for C classes.
        - learning_rate: (float) learning rate for optimization.
        - reg: (float) regularization strength.
        - num_iters: (integer) number of steps to take when optimizing
        - batch_size: (integer) number of training examples to use at each step.
        - verbose: (boolean) If true, print progress during optimization.

        Outputs:
        A list containing the value of the loss function at each training iteration.
        """
        num_train, dim = X.shape
        num_classes = np.max(y) + 1 # 假设 y 取值 0...K-1 其中 K 是类数
        if self.W is None:
            # lazily 初始化W
            self.W = 0.001 * np.random.randn(dim, num_classes)

        # 运行随机梯度下降以优化 W
        loss_history = []
        for it in range(num_iters):
            X_batch = None
            y_batch = None

            #########################################################################
            # TODO:                                                                 #
            # Sample batch_size elements from the training data and their           #
            # corresponding labels to use in this round of gradient descent.        #
            # Store the data in X_batch and their corresponding labels in           #
            # y_batch; after sampling X_batch should have shape (batch_size, dim)   #
            # and y_batch should have shape (batch_size,)                           #
            #                                                                       #
            # Hint: Use np.random.choice to generate indices. Sampling with         #
            # replacement is faster than sampling without replacement.              #
            #########################################################################
            # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
            
            batch_idx = np.random.choice(num_train, size=batch_size, replace=False)
            # 在num_train数目中随机采样batch_size个元素,分别存储在X_batch和y_batch中
            X_batch = X[batch_idx] 
            y_batch = y[batch_idx]
            
            pass

            # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

            # evaluate loss and gradient
            loss, grad = self.loss(X_batch, y_batch, reg)
            loss_history.append(loss)

            # perform parameter update
            #########################################################################
            # TODO:                                                                 #
            # Update the weights using the gradient and the learning rate.          #
            #########################################################################
            # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
            
            self.W -= learning_rate*grad # 进行梯度下降更新
            
            pass

            # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

            if verbose and it % 100 == 0:
                print('iteration %d / %d: loss %f' % (it, num_iters, loss))

        return loss_history

    def predict(self, X):
        """
        Use the trained weights of this linear classifier to predict labels for
        data points.

        Inputs:
        - X: A numpy array of shape (N, D) containing training data (either training, validating or testing data? );
          there are N training samples each of dimension D.

        Returns:
        - y_pred: Predicted labels for the data in X. y_pred is a 1-dimensional
          array of length N, and each element is an integer giving the predicted
          class.
        """
        y_pred = np.zeros(X.shape[0])
        ###########################################################################
        # TODO:                                                                   #
        # Implement this method. Store the predicted labels in y_pred.            #
        ###########################################################################
        # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
        
        # be careful about self.W.shape = (dim, num_classes) !!
        y_pred = np.argmax(X.dot(self.W), axis=1)
        # argmax查找X.dot(self.W)最大元素在第一维中的索引值
        
        pass

        # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
        return y_pred

    def loss(self, X_batch, y_batch, reg):
        """
        Compute the loss function and its derivative.
        Subclasses will override this.

        Inputs:
        - X_batch: A numpy array of shape (N, D) containing a minibatch of N
          data points; each point has dimension D.
        - y_batch: A numpy array of shape (N,) containing labels for the minibatch.
        - reg: (float) regularization strength.

        Returns: A tuple containing:
        - loss as a single float
        - gradient with respect to self.W; an array of the same shape as W
        """
        pass


class LinearSVM(LinearClassifier):
    """ A subclass that uses the Multiclass SVM loss function """

    def loss(self, X_batch, y_batch, reg):
        return svm_loss_vectorized(self.W, X_batch, y_batch, reg)

5.验证最佳超参数:

超参数性能由val_acc衡量,越大越好

# 使用验证集来调整超参数(正则化强度和学习率)。 您应该尝试不同的学习率和正则化强度范围; 如果你小心,你应该能够在验证集上获得大约 0.39 的分类准确度。

# 注意:您可能会在超参数搜索期间看到运行时/溢出警告。 这可能是由极端值引起的,而不是错误。

#结果是将表单(learning_rate,regularization_strength)的字典映射到表单(training_accuracy,validation_accuracy)的元组。 
#准确度只是被正确分类的数据点的分数。
results = {}
best_val = -1   # The highest validation accuracy that we have seen so far.
best_svm = None # The LinearSVM object that achieved the highest validation rate.

################################################################################
# TODO:                                                                        #
# Write code that chooses the best hyperparameters by tuning on the validation #
# set. For each combination of hyperparameters, train a linear SVM on the      #
# training set, compute its accuracy on the training and validation sets, and  #
# store these numbers in the results dictionary. In addition, store the best   #
# validation accuracy in best_val and the LinearSVM object that achieves this  #
# accuracy in best_svm.                                                        #
#                                                                              #
# Hint: You should use a small value for num_iters as you develop your         #
# validation code so that the SVMs don't take much time to train; once you are #
# confident that your validation code works, you should rerun the validation   #
# code with a larger value for num_iters.                                      #
################################################################################

# Provided as a reference. You may or may not want to change these hyperparameters

learning_rates = [1e-7, 1e-6] #选取学习率校验范围
regularization_strengths = [1e4, 4e4] #正则化强度校验范围

# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

# some notes I took for myself:
# 1. first tested with small reg (=2.5e-6), I change lr interval from [1e-7, 1e-5] to [5e-8, 1e-6] cause 5e-6 dose not converge
# 2. then observe the tendency relationship of `val_acc` and `reg` for any given `lr` to shrink interval of `reg`
# 3. np.mean() can calculate accurancy in one short line !!!! not even using the list comprehension
# 4. finally, remember to train model with a larger value for num_iters
# 5. but why can he/she do so well ... orz: https://tomaxent.com/2017/03/03/cs231n-Assignment-1-svm/

for lr in np.linspace(learning_rates[0], learning_rates[1], 5):
    for reg in np.linspace(regularization_strengths[0], regularization_strengths[1], 8):

        svm = LinearSVM()
        svm.train(X_train, y_train, learning_rate=lr, reg=reg, num_iters=1500)
        
        y_train_pred = svm.predict(X_train)
        train_acc = np.mean(y_train_pred == y_train)
        y_val_pred = svm.predict(X_val)
        val_acc = np.mean(y_val_pred == y_val)
    
        results[(lr, reg)] = (train_acc, val_acc)

        print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
            lr, reg, train_acc, val_acc))
        
        if best_val < val_acc:
            best_val = val_acc
            best_svm = svm
        
pass

# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

print('best validation accuracy achieved during cross-validation: %f' % best_val)

你可能感兴趣的:(机器学习)